doc.js 62.3 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;
        };
    }

31 32 33 34 35 36 37 38
    var getQueryString = function(name, defaultValue)
    {
        var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
        var r = window.location.search.substr(1).match(reg);
        if (r !== null) return unescape(r[2]); return defaultValue;
    };

    var debug = getQueryString('debug', 0);
C
Catouse 已提交
39
    if(debug) console.error("DEBUG ENABLED.");
C
Catouse 已提交
40 41

    var chapters = {
42 43 44 45 46 47
        learn: {col: 1},
        start: {col: 1},
        basic: {col: 1},
        control: {col: 2},
        component: {col: 2},
        javascript: {col: 3},
48
        view: {col: 3},
C
Catouse 已提交
49
        promotion: {col: 1, row: 2},
C
Catouse 已提交
50 51
        resource: {col: 1, row: 2},
        contribution: {col: 1, row: 2}
C
Catouse 已提交
52 53
    };
    var LAST_RELOAD_ANIMATE_ID = 'lastReloadAnimate';
C
Catouse 已提交
54
    var LAST_QUERY_ID = 'LAST_QUERY_ID';
55 56
    var INDEX_JSON = 'docs/index.json';
    var ICONS_JSON = 'docs/icons.json';
57
    var PKG_JSON = 'package.json';
C
Catouse 已提交
58
    var UNDEFINED = undefined;
C
Catouse 已提交
59 60
    var dataVersion;
    var storageEnable;
C
Catouse 已提交
61
    var docIndex, iconsIndex;
62
    var pkgLibs = {standard: null, lite: null, separate: null};
C
Catouse 已提交
63

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

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

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

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

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

C
Catouse 已提交
116 117
    var loadData = function(url, callback, delayLoadRemote) {
        var cacheData = null;
C
Catouse 已提交
118
        var isIndexJson = url === INDEX_JSON;
C
Catouse 已提交
119
        var isIconsJson = url === ICONS_JSON;
C
Catouse 已提交
120 121 122 123
        var isHasCache = false;
        if(isIndexJson && docIndex) {
            cacheData = {data: docIndex, version: docIndex.version};
            isHasCache = true;
C
Catouse 已提交
124 125 126
        } else if(isIconsJson && iconsIndex) {
            cacheData = iconsIndex;
            isHasCache = true;
C
Catouse 已提交
127
        } else if(storageEnable) {
C
Catouse 已提交
128
            var storedData = $.zui.store.get('//' + url, null);
C
Catouse 已提交
129
            if(storedData !== null) {
C
Catouse 已提交
130
                var storedVersion = $.zui.store.get('//' + url + '::V');
C
Catouse 已提交
131 132 133
                if(storedVersion) {
                    cacheData = {data: storedData, version: storedVersion};
                    isHasCache = true;
C
Catouse 已提交
134 135 136
                    if(!docIndex && isIndexJson) {
                        docIndex = storedData;
                    }
C
Catouse 已提交
137
                    if(debug) console.log('Load', url, 'from storage:', cacheData);
C
Catouse 已提交
138
                }
C
Catouse 已提交
139
            }
C
Catouse 已提交
140 141
        }

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

        var dataType = url.endsWith('.json') ? 'json' : 'html';
C
Catouse 已提交
149 150 151 152 153 154
        var loadFromRemote = function(){
            $.get(url, function(data){
                if(data !== null) {
                    if(isIndexJson) {
                        dataVersion = data.version;
                        docIndex = data;
C
Catouse 已提交
155 156
                    } else if(isIconsJson) {
                        iconsIndex = {data: data, version: dataVersion};
C
Catouse 已提交
157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172
                    }
                    cacheData = {data: data, version: dataVersion};
                    $.zui.store.set('//' + url, data);
                    $.zui.store.set('//' + url + '::V', dataVersion);

                    if(debug) console.log('Load', url, 'from remote:', cacheData);
                    callback(data, 'remote');
                } else if(isHasCache && !isIndexJson) {
                    if(debug) console.log('Failed load', url, 'from remote, instead load cache:', cacheData);
                    callback(cacheData.data, 'cache');
                }
            }, 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, 'cache');
C
Catouse 已提交
173
                }
C
Catouse 已提交
174

C
Catouse 已提交
175 176 177 178 179 180 181 182 183 184 185
                if($body.hasClass('page-open')) {
                    $pageBody.children('.loader').addClass('with-error');
                }
            });
        }

        if(delayLoadRemote !== false) {
            if(delayLoadRemote) {
                setTimeout(loadFromRemote, delayLoadRemote);
            } else {
                loadFromRemote();
C
Catouse 已提交
186
            }
C
Catouse 已提交
187
        }
C
Catouse 已提交
188 189 190 191 192 193 194
    };

    var eachSection = function(callback, eachChapterCallback) {
        if (!docIndex) {
            console.error("Document index is empty.");
            return false;
        };
C
Catouse 已提交
195

C
Catouse 已提交
196 197
        $.each(chapters, function(chapterName, chapter){
            if(!docIndex.chapters[chapterName]) return;
C
Catouse 已提交
198 199 200 201 202 203 204 205 206 207 208 209
            $.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 已提交
210 211 212
    };

    var displaySectionIcon = function($icon, section) {
213 214 215 216
        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 已提交
217
        }
218 219 220 221
        if (icon.startsWith('icon-')) {
            $icon.addClass(icon);
        } else if(icon.endsWith('.png')) {
            $icon.css('background-image', 'url(' + icon + ')').addClass('with-img');
C
Catouse 已提交
222
        } else {
223
            $icon.addClass('text-icon').text(icon);
C
Catouse 已提交
224 225
        }
    };
C
Catouse 已提交
226

C
Catouse 已提交
227
    var displaySection = function() {
C
Catouse 已提交
228
        var order = 0;
C
Catouse 已提交
229 230
        if(eachSection(function(chapter, section, $sectionList){
            var chapterName = chapter.id;
C
Catouse 已提交
231
            section.chapter = chapterName;
232
            section.chapterName = chapter.name;
233 234 235

            var url = section.url;
            if(typeof url === 'undefined') {
236
                section.url = 'docs/part/' + section.chapter + '-' + section.id + '.html';
237
                section.target = 'page';
C
Catouse 已提交
238
            } else if(isExternalUrl(url)) {
239
                section.target = 'external';
C
Catouse 已提交
240 241 242
            } else if(url && url.endsWith('.md')) {
                section.target = 'page';
                section.targetType = 'markdown';
C
Catouse 已提交
243 244 245
                if(url === '.md') {
                    section.url = 'docs/part/' + section.chapter + '-' + section.id + '.md';
                }
246 247 248 249
            } else {
                section.target = '';
            }

C
Catouse 已提交
250
            var id = chapterName + '-' + section.id;
251
            var $tpl = $sectionTemplate.clone().data('section', section);
252
            $tpl.attr({
253
                'id': 'section-' + id,
254 255 256
                'data-id': section.id,
                'data-chapter': chapterName,
                'data-order': order++,
257 258
                'data-accent': chapter.accent,
                'data-target': section.target
259
            });
C
Catouse 已提交
260
            var $head = $tpl.children('.card-heading');
261 262
            var sectionUrl = '#' + chapterName + '/' + section.id;
            $head.find('.name').text(section.name).attr('href', sectionUrl);
C
Catouse 已提交
263
            // $head.children('.desc').text(section.desc);
C
Catouse 已提交
264
            displaySectionIcon($head.children('.icon'), section);
C
Catouse 已提交
265 266
            var $topics = $tpl.find('.topics');
            if (section.topics && section.topics.length) {
C
Catouse 已提交
267
                var topicId = 0;
C
Catouse 已提交
268
                $.each(section.topics, function(tName, topic){
269
                    if(typeof topic.id === 'undefined') topic.id = tName;
C
Catouse 已提交
270
                    var topicUrl = typeof topic.url === 'undefined' ? (sectionUrl + '/' + (topicId++)) : topic.url;
C
Catouse 已提交
271 272

                    $topics.append('<li data-id="' + tName + '"><a href="' + topicUrl + '"' + (isExternalUrl(topicUrl) ? ' target="_blank"' : '') + '>' + topic.name + '</a></li>');
C
Catouse 已提交
273
                });
C
Catouse 已提交
274 275 276 277
            } else {
                $topics.remove('.card-content');
                $tpl.addClass('without-topics');
            }
C
Catouse 已提交
278
            $sectionList.append($tpl.addClass('show' + (sectionsShowed ? ' in' : '')));
C
Catouse 已提交
279
        }, function(chapter, sections){
280
            chapter.$.attr('data-accent', chapter.accent);
C
Catouse 已提交
281 282
            var $sectionList = chapter.$sections;
            $sectionList.children().remove();
C
Catouse 已提交
283 284
            return $sectionList;
        })) {
C
Catouse 已提交
285
            $body.children('.loader').removeClass('loading');
C
Catouse 已提交
286
            $sections = $grid.find('.section');
C
Catouse 已提交
287 288 289
            if(!sectionsShowed) {
                clearTimeout($grid.data(LAST_RELOAD_ANIMATE_ID));
                $grid.data(LAST_RELOAD_ANIMATE_ID, setTimeout(function(){
C
Catouse 已提交
290
                    $sections.addClass('in');
C
Catouse 已提交
291 292 293 294
                    $chapterHeadings.addClass('in');
                }, 100));
                sectionsShowed = true;
            }
C
Catouse 已提交
295 296 297 298 299
        } else if(debug) {
            console.error("Display sections failed.");
        }
    };

C
Catouse 已提交
300 301 302 303 304 305 306 307 308 309
    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 已提交
310 311 312 313 314 315 316 317 318
    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 已提交
319 320
        }
    };
C
Catouse 已提交
321

C
Catouse 已提交
322 323 324
    var isChoosedSection = function($section) {
        if($section === UNDEFINED) {
            $section = $choosedSection;
C
Catouse 已提交
325
        }
C
Catouse 已提交
326
        return $section && $section.hasClass('choosed') && $section.hasClass('show');
C
Catouse 已提交
327 328
    };

C
Catouse 已提交
329
    var chooseSection = function($section, keepOtherOpen, notOpenSelf) {
C
Catouse 已提交
330
        if($sections) {
C
Catouse 已提交
331
            if(isChoosedSection($section || null) && !notOpenSelf) {
C
Catouse 已提交
332 333
                $choosedSection = $section.addClass('open');
                scrollToSection($section);
C
Catouse 已提交
334 335 336
                return;
            }
            var isOpened = $section && $section.hasClass('open');
C
Catouse 已提交
337
            $sections.removeClass(keepOtherOpen ? 'choosed' : 'choosed open');
C
Catouse 已提交
338
            if($section && $section.hasClass('section')) {
C
Catouse 已提交
339
                $choosedSection = $section.addClass((notOpenSelf && !isOpened) ? 'choosed' : 'choosed open');
C
Catouse 已提交
340
                scrollToSection($section);
C
Catouse 已提交
341
            }
C
Catouse 已提交
342
        }
C
Catouse 已提交
343
    };
C
Catouse 已提交
344

C
Catouse 已提交
345 346
    var choosePrevSection = function() {
        var $all = $sections.filter('.show');
C
Catouse 已提交
347
        if(isChoosedSection()) {
C
Catouse 已提交
348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364
            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 已提交
365
        if(isChoosedSection()) {
C
Catouse 已提交
366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387
            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 已提交
388
        if(isChoosedSection()) {
C
Catouse 已提交
389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417
            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 已提交
418
        if(isChoosedSection()) {
C
Catouse 已提交
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
            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 已提交
447
    var resetQuery = function() {
C
Catouse 已提交
448
        $grid.find('.col.hide').removeClass('hide');
C
Catouse 已提交
449 450 451 452 453 454 455
        $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 已提交
456
        $body.removeClass('query-enabled').attr('data-query', '');
C
Catouse 已提交
457 458
    };

459
    var chooseIcon = function($icon){
C
Catouse 已提交
460
        var $search = $('#section-control-icon');
461 462 463 464 465 466 467 468
        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 已提交
469
            $preview = $('#iconPreviewTemplate').clone().attr('id', '');
470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492
            $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];
        }

C
Catouse 已提交
493
        var $section = $('#section-control-icon');
494 495 496 497 498 499 500 501 502 503 504 505 506
        $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){
C
Catouse 已提交
507
                    var $li = $('<li id="control-icon-' + iconName + '" data-id="' + iconName + '"><a href="#control/icons/' + iconName + '"><i class="icon icon-' + iconName + '"></i> icon-' + iconName + '</a></li>');
508 509 510 511 512 513 514 515 516 517 518 519 520
                    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;
            }

C
Catouse 已提交
521
            keys.forEach(function(keyVal, keyIndex){
522
                keys[keyIndex] = keys[keyIndex].toLowerCase();
C
Catouse 已提交
523
            });
524 525 526 527 528 529 530 531 532 533 534 535 536 537

            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;
538
                    } else if(key.startsWith('\\') && icon.code && icon.code.toLowerCase().includes(key.substr(1))) {
539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564
                        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;
                    }
                });

C
Catouse 已提交
565
                var $li = $('#control-icon-' + iconId).toggleClass('hide', !choosed);
566 567 568 569 570 571 572 573 574
                if(choosed && bestMatchWeight < weight) {
                    bestMatchWeight = weight;
                    $bestMatch = $li;
                }
            });
            chooseIcon($bestMatch);
        });
    };

C
Catouse 已提交
575
    var query = function(keyString) {
C
Catouse 已提交
576 577 578 579
        if(!$sections) {
            if(debug) console.log('Query failed, $sections is empty. key:', keyString);
            return;
        }
C
Catouse 已提交
580

581 582
        if(typeof keyString === 'undefined') keyString = null;

C
Catouse 已提交
583 584 585 586 587
        if($queryInput.data('queryString') !== keyString) {
            $queryInput.data('queryString', keyString).val(keyString);
            $grid.css('min-height', $grid.height());
        }

588
        if(keyString === null || !keyString.length) {
C
Catouse 已提交
589
            resetQuery();
590
            $search.removeClass('with-query-text');
C
Catouse 已提交
591 592
            return;
        }
593
        $search.addClass('with-query-text');
C
Catouse 已提交
594

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

C
Catouse 已提交
597
        // Send ga data
C
Catouse 已提交
598
        if(window['ga'] && $.isFunction(ga)) {
C
Catouse 已提交
599 600 601 602 603 604
            if(queryGaCallback) clearTimeout(queryGaCallback);
            queryGaCallback = setTimeout(function(){
                ga('send', 'pageview', window.location.pathname + '#search/' + keyString);
            }, 2000);
        }

C
Catouse 已提交
605 606 607 608
        var keys = [];
        $.each(keyString.split(' '), function(i, key){
            key = $.trim(key).toLowerCase();
            var keyOption = {origin: key};
609
            if(key.startsWith('@')) {
C
Catouse 已提交
610
                keyOption.type = 'id';
611 612 613 614 615
                keyOption.chapter = key.substr(1);
                keyOption.val = keyOption.chapter;
            } else if(key.startsWith('#')) {
                keyOption.type = 'id';
                keyOption.val = key.substr(2);
C
Catouse 已提交
616 617 618
            } else if(key.startsWith('icon-') || key.startsWith('icon:')) {
                keyOption.type = 'icon';
                keyOption.val = key.substr(5);
C
Catouse 已提交
619
            } else if(key.startsWith('i:') || key.startsWith('i-')) {
C
Catouse 已提交
620
                keyOption.type = 'icon';
621
                keyOption.val = key.substr(2);
C
Catouse 已提交
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
            } 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;
                }
            }
651
            if(keyOption.val.length || (keyOption.type && keyOption.type !== 'any')) {
C
Catouse 已提交
652 653
                keys.push(keyOption);
            }
C
Catouse 已提交
654 655
        });

C
Catouse 已提交
656 657 658 659 660
        if(!keys.length) {
            resetQuery();
            return;
        }

C
Catouse 已提交
661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676
        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':
C
Catouse 已提交
677
                        chooseThis = section.id === 'icon';
678 679 680 681 682 683 684
                        if(chooseThis) {
                            weight = 120;
                            matches.push({key: key, type: ['section', 'id']});
                            var iconKeys = [];
                            if(key.val || key.val.length) {
                                iconKeys.push(key.val);
                            }
C
Catouse 已提交
685
                            keys.forEach(function(iconKey){
686 687 688
                                if(iconKey.val !== key.val && (iconKey.val || iconKey.val.length)) {
                                    iconKeys.push(iconKey.val);
                                }
C
Catouse 已提交
689
                            });
690 691 692
                            queryIcon(iconKeys);
                            return false;
                        }
C
Catouse 已提交
693 694
                        break;
                    default:
C
Catouse 已提交
695 696
                        var sectionName = section.name.toLowerCase();
                        if(sectionName.includes(keyVal)) {
C
Catouse 已提交
697 698
                            chooseThisKey = true;
                            matchType = ['section', 'name'];
699 700 701 702 703 704 705
                            weight = sectionName.startsWith(keyVal) ? 85 : 82;
                            break;
                        }
                        if(section.filter && section.filter.includes(keyVal)) {
                            chooseThisKey = true;
                            matchType = ['section', 'filter'];
                            weight = 80;
C
Catouse 已提交
706 707
                            break;
                        }
C
Catouse 已提交
708 709
                        var chapterName = chapter.name.toLowerCase();
                        if(chapterName.includes(keyVal)) {
C
Catouse 已提交
710 711
                            chooseThisKey = true;
                            matchType = ['chapter', 'name'];
712 713 714 715 716 717 718
                            weight = chapterName.startsWith(keyVal) ? 75 : 73;
                            break;
                        }
                        if(chapter.filter && chapter.filter.includes(keyVal)) {
                            chooseThisKey = true;
                            matchType = ['chapter', 'filter'];
                            weight = 70;
C
Catouse 已提交
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 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766
                            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 已提交
767
                }
C
Catouse 已提交
768 769 770
                if(!chooseThisKey) {
                    chooseThis = false;
                    return false;
C
Catouse 已提交
771
                } else {
C
Catouse 已提交
772
                    matches.push({key: key, type: matchType});
C
Catouse 已提交
773
                }
C
Catouse 已提交
774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790
            });

            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 已提交
791
                } else {
C
Catouse 已提交
792 793 794 795 796
                    $show = $show.add($section);
                    if(choosedWeight < result.weight) {
                        $choosed = $section;
                        choosedWeight = result.weight;
                    }
C
Catouse 已提交
797
                }
C
Catouse 已提交
798
                chooseSection($choosed);
C
Catouse 已提交
799
            });
C
Catouse 已提交
800 801 802 803 804 805 806

            var $chapter, hide, chapter;
            $.each(chapterMap, function(chapterId, resultCount){
                chapter = chapters[chapterId];
                hide = !resultCount;
                chapter.$.toggleClass('hide', hide);
            });
C
Catouse 已提交
807 808 809 810 811 812 813 814 815 816 817 818 819 820 821
            var finalShowColsCount = 0;
            $grid.find('.row').each(function(){
                var showColsCount = 0;
                var $row = $(this);
                $row.children('.col').each(function(){
                    var $col = $(this);
                    var showCol = $col.children('.chapter:not(.hide)').length;
                    $col.toggleClass('hide', !showCol);
                    if(showCol) {
                        showColsCount++;
                        if(!$body.hasClass('compact-mode')) {
                            var showCount = $col.find('.section:not(.hide)').length;
                            if(showCount > 2 && $window.height() < ($header.height() + showCount * 70)) {
                                toggleCompactMode(true);
                            }
C
Catouse 已提交
822 823
                        }
                    }
C
Catouse 已提交
824 825
                });
                finalShowColsCount = Math.max(finalShowColsCount, showColsCount);
C
Catouse 已提交
826
            });
C
Catouse 已提交
827
            $grid.attr('data-show-col', finalShowColsCount);
C
Catouse 已提交
828 829 830

            if($hide.length) {
                $hide.removeClass('in');
C
Catouse 已提交
831
                setTimeout(function(){$hide.removeClass('show');}, 100);
C
Catouse 已提交
832 833 834 835 836
            }
            if($show.length) {
                $show.addClass('show');
                setTimeout(function(){$show.addClass('in');}, 20);
            }
C
Catouse 已提交
837 838

            $window.scrollTop(1);
C
Catouse 已提交
839
            closePage();
C
Catouse 已提交
840 841 842
        } else if(debug) {
            console.error("Query failed with key: ", keys);
        }
C
Catouse 已提交
843 844 845
    };

    var toggleCompactMode = function(toggle, callback) {
C
Catouse 已提交
846 847 848 849
        if(toggle === UNDEFINED) {
            toggle = !$body.hasClass('compact-mode');
        }

C
Catouse 已提交
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();
C
Catouse 已提交
860
                    }, 300);
C
Catouse 已提交
861 862 863 864 865 866 867 868 869 870 871
                }, 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();
C
Catouse 已提交
872
                }, 300);
C
Catouse 已提交
873 874 875 876 877 878 879
            } else if(callback) {
                callback();
            }
        }
    };

    var closePage = function() {
880
        window['afterPageLoad'] = null;
C
Catouse 已提交
881 882 883 884 885
        window['onPageLoad'] = null;
        if($.isFunction(window['onPageClose'])) {
            window['onPageClose']();
            window['onPageClose'] = null;
        }
C
Catouse 已提交
886
        if($body.hasClass('page-open')) {
C
Catouse 已提交
887
            var style = $page.data('trans-style');
C
Catouse 已提交
888 889 890 891
            if(style){
                style['max-height'] = '';
                $page.css(style);
            }
C
Catouse 已提交
892
            $body.addClass('page-show-out').removeClass('page-open page-show-in');
893

894 895 896 897
            if($queryInput.val() !== '') {
                $queryInput.focus();
            }

898
            window.document.title = documentTitle;
899
            window.location.hash = '#/';
C
Catouse 已提交
900
            setTimeout(function(){
C
Catouse 已提交
901
                $body.removeClass('page-show page-show-out');
C
Catouse 已提交
902
                resetScrollbar();
C
Catouse 已提交
903
            }, 300);
C
Catouse 已提交
904
            return true;
C
Catouse 已提交
905
        }
C
Catouse 已提交
906
        return false;
C
Catouse 已提交
907 908
    };

909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934
    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 已提交
935 936 937 938 939
    var mutePageLoading = function() {
        $page.removeClass('loading');
        $pageLoader.removeClass('loading');
    };

C
Catouse 已提交
940
    var handlePageLoad = function() {
C
Catouse 已提交
941 942 943
        var delayMutedPageLoading = false;
        if($.isFunction(window['onPageLoad'])) {
            delayMutedPageLoading = window['onPageLoad']() === false;
C
Catouse 已提交
944 945
        }

C
Catouse 已提交
946 947 948 949 950 951 952 953 954 955 956 957 958
        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']();
            }
C
Catouse 已提交
959
        }, 200);
C
Catouse 已提交
960 961

        if(!delayMutedPageLoading) mutePageLoading();
C
Catouse 已提交
962 963
    };

C
Catouse 已提交
964
    var openPage = function($section, section, topic) {
C
Catouse 已提交
965 966 967 968 969
        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 已提交
970
        chooseSection($section, false, true);
C
Catouse 已提交
971

C
Catouse 已提交
972 973 974
        // Send ga data
        var pageUrl = '#' + section.chapter + '/' + section.id;
        if(topic) pageUrl += '/' + topic;
975
        window.document.title = section.chapterName + ' > ' + section.name + ' - ' + documentTitle;
C
Catouse 已提交
976
        window.location.hash = pageUrl;
C
Catouse 已提交
977
        if(window['ga'] && $.isFunction(ga)) ga('send','pageview', window.location.pathname + pageUrl);
C
Catouse 已提交
978

979
        $body.attr('data-page-accent', $section.data('accent')).attr('data-page', pageId);
C
Catouse 已提交
980
        displaySectionIcon($pageHeader.find('.icon'), section);
C
Catouse 已提交
981
        $pageHeader.find('.name').text(section.name).attr('href', pageUrl);
C
Catouse 已提交
982
        // $pageHeader.find('.desc').text(section.desc);
C
Catouse 已提交
983 984 985 986

        // page attributes
        $pageAttrs.hide();
        $pageAttrs.children('.badge-author').toggle(!!section.author).find('.author-name').text(section.author);
C
Catouse 已提交
987
        $pageAttrs.children('.badge-source').toggle(!!section.url).attr('href', 'https://github.com/easysoft/zui/tree/master/' + section.url);
C
Catouse 已提交
988 989 990 991 992 993
        var lib = section.lib;
        if(lib) {
            $pageAttrs.children('.badge-zui').toggle(!!lib.bundles.standard);
            $pageAttrs.children('.badge-lite').toggle(!!lib.bundles.lite);
            $pageAttrs.children('.badge-lib').toggle(!!lib.bundles.separate);
            $pageAttrs.children('.badge-custom').toggle(!!lib.custom);
C
Catouse 已提交
994

C
Catouse 已提交
995 996 997 998
            $pageAttrs.children('.badge-version').toggle(!!lib.ver).text(lib.ver + '+');
            $pageAttrs.children('.badge-party').toggle(!!lib.thirdpart).attr('href', lib.partUrl || 'javascript:;').find('.product-ver').text(lib.pver);
        }

C
Catouse 已提交
999
        $pageContent.empty();
C
Catouse 已提交
1000 1001
        $page.addClass('loading');
        $pageLoader.removeClass('with-error').addClass('loading');
C
Catouse 已提交
1002
        var lastShowDataCall;
C
Catouse 已提交
1003

C
Catouse 已提交
1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020
        loadData(section.url, function(data){
            var showData = function(){
                if(marked && section.targetType === 'markdown') {
                    var $article = $();
                    var $markdown = $(marked(data));
                    var $lastSection, checkFirstH1 = true;
                    var hasH2 = $markdown.filter('h2').length > 0;
                    $markdown.each(function(){
                        var $tag = $(this);
                        var tagName = $tag.prop('tagName');
                        if(tagName === 'STYLE' || tagName === 'SCRIPT') {
                            $article = $article.add($tag);
                            return;
                        }
                        if(checkFirstH1) {
                            if(tagName === 'H1') {
                                $pageHeader.find('h2 > .name').text($tag.html());
C
Catouse 已提交
1021
                            }
C
Catouse 已提交
1022 1023 1024 1025 1026 1027
                            checkFirstH1 = false;
                            return;
                        }
                        if((hasH2 && (tagName === 'H1' || tagName === 'H2')) || (!hasH2 && tagName === 'H3')) {
                            if($lastSection) {
                                $article = $article.add($lastSection);
C
Catouse 已提交
1028
                            }
C
Catouse 已提交
1029 1030 1031 1032 1033 1034 1035 1036 1037
                            $lastSection = $('<section><header><h3>' + $tag.html() + '</h3></header><article></article></section>');
                        } else {
                            if(hasH2) {
                                if(tagName === 'H3') {
                                    $tag = $('<h4>').html($tag.html());
                                } else if(tagName === 'H4') {
                                    $tag = $('<h5>').html($tag.html());
                                } else if(tagName === 'H5') {
                                    $tag = $('<h6>').html($tag.html());
C
Catouse 已提交
1038
                                }
C
Catouse 已提交
1039 1040 1041 1042 1043 1044
                            }
                            if(!$lastSection) {
                                $lastSection = $('<article></article>');
                            }
                            if($lastSection.prop('tagName') === 'ARTICLE') {
                                $lastSection.append($tag);
C
Catouse 已提交
1045
                            } else {
C
Catouse 已提交
1046
                                $lastSection.children('article').append($tag);
C
Catouse 已提交
1047 1048
                            }
                        }
C
Catouse 已提交
1049 1050 1051
                    });
                    if($lastSection) {
                        $article = $article.add($lastSection);
C
Catouse 已提交
1052
                    }
C
Catouse 已提交
1053
                    $pageContent.empty().append($article);
C
Catouse 已提交
1054
                } else {
C
Catouse 已提交
1055
                    $pageContent.html(data);
C
Catouse 已提交
1056
                }
C
Catouse 已提交
1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068
                $pageBody.scrollTop(0);
                showPageTopic(topic);
                handlePageLoad();
                $pageAttrs.show();
            }
            if(lastShowDataCall) clearTimeout(lastShowDataCall);
            if($page.hasClass('openning')) {
                lastShowDataCall = setTimeout(showData, 700);
            } else {
                showData();
            }
        }, 400);
C
Catouse 已提交
1069

C
Catouse 已提交
1070 1071 1072 1073 1074 1075 1076
        if($body.hasClass('page-open')) {
            if(debug) console.log('open section in open page', section);
            return;
        }

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

C
Catouse 已提交
1077 1078 1079
        toggleCompactMode(true, function(){
            checkScrollbar();
            $body.addClass('page-show');
1080

C
Catouse 已提交
1081 1082
            setTimeout(function(){
                $body.addClass('page-show-in');
C
Catouse 已提交
1083
                if($page.hasClass('loading')) $page.addClass('openning');
C
Catouse 已提交
1084 1085 1086
                $pageBody.scrollTop(0);
                setTimeout(function(){
                    $page.removeClass('openning');
C
Catouse 已提交
1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097
                    if(firstOpenPage) {
                        firstOpenPage = $.zui.store.get('first_open_page', true);
                        if(firstOpenPage) {
                            firstOpenPage = false;
                            $.zui.store.set('first_open_page', false);
                            setTimeout(function(){
                                $('#pageCloseBtn').tooltip('show').addClass('active');
                                setTimeout(function(){$('#pageCloseBtn').tooltip('hide').removeClass('active');}, 6000);
                            }, 500);
                        }
                    }
C
Catouse 已提交
1098
                }, 300);
C
Catouse 已提交
1099 1100 1101
            }, 10);
        });
    };
C
Catouse 已提交
1102

C
Catouse 已提交
1103
    var openSection = function(section, topic) {
C
Catouse 已提交
1104
        // if(debug) console.log('openSection', section, topic);
C
Catouse 已提交
1105 1106
        section = section || $choosedSection;

C
Catouse 已提交
1107
        var $section;
C
Catouse 已提交
1108
        if($.isArray(section)) {
1109
            if(typeof topic !== 'undefined') section = section.push(topic);
C
Catouse 已提交
1110 1111 1112 1113
            if(!section[0]) {
                if(debug) console.error("Open section failed: can't find the section with id " + section.join('-'));
                return;
            }
1114 1115 1116 1117
            if(section.length > 0 && section[0] === 'search') {
                query(section[1]);
                return;
            }
C
Catouse 已提交
1118 1119 1120 1121
            if(docIndex && section.length > 1) {
                var sectionId = section[1];
                var sections = docIndex.chapters[section[0]].sections;
                var ok = false;
C
Catouse 已提交
1122
                $.each(sections, function(i, s){
C
Catouse 已提交
1123 1124 1125 1126 1127 1128
                    if(s.id === sectionId) {
                        if(section.length > 2) {
                            topic = section[2];
                        }
                        section = s;
                        ok = true;
C
Catouse 已提交
1129
                        return false;
C
Catouse 已提交
1130
                    }
C
Catouse 已提交
1131
                });
C
Catouse 已提交
1132
                if(!ok) {
C
Catouse 已提交
1133
                    if(debug) console.error("Open section failed: can't find the section with id " + section.join('-'));
C
Catouse 已提交
1134 1135 1136 1137 1138 1139 1140 1141 1142
                    return;
                }
            } else {
                if(debug) {
                    console.error("Open section stop by null docIndex or wrong section value.");
                }
                return;
            }
        }
C
Catouse 已提交
1143 1144 1145 1146 1147 1148 1149 1150
        if($.isPlainObject(section)) {
            $section = $('#section-' + section.chapter + '-' + section.id);
        } else {
            var $temp = section;
            section = $temp.data('section');
            $section = $temp;
        }

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

1156 1157 1158 1159 1160 1161 1162 1163 1164
        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 已提交
1165 1166 1167
        }
    };

C
Catouse 已提交
1168
    var togglePageSection = function($section, toggle) {
1169 1170 1171 1172 1173 1174
        var valType = typeof $section;
        if(valType === 'object') {
            if(typeof toggle === 'undefined') {
                toggle = $section.hasClass('collapsed');
            }
            $section.toggleClass('collapsed', !toggle);
C
Catouse 已提交
1175 1176 1177
            var $setions = $pageContent.children('section');
            var sectionsCount = $setions.length, collapsedSectionCount = $setions.filter('.collapsed').length;
            if(collapsedSectionCount === 0) {
C
Catouse 已提交
1178
                $page.removeClass('page-collapsed');
C
Catouse 已提交
1179
            } else if(collapsedSectionCount === sectionsCount) {
C
Catouse 已提交
1180
                $page.addClass('page-collapsed');
C
Catouse 已提交
1181 1182
            }
        } else {
1183
            toggle = valType === 'boolean' ? $section : $page.hasClass('page-collapsed');
C
Catouse 已提交
1184
            $page.toggleClass('page-collapsed', !toggle);
1185
            if(!toggle) {
C
Catouse 已提交
1186 1187 1188 1189 1190 1191 1192
                $pageContent.children('section').addClass('collapsed');
            } else {
                $pageContent.children('section').removeClass('collapsed');
            }
        }
    };

1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204
    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 已提交
1205
        } else if(isExternalUrl(url)) {
1206
            window.open(url, '_blank');
C
Catouse 已提交
1207 1208
        } else {
            if(debug) console.error('Open page url failed: unknown url', url);
1209 1210 1211
        }
    };

C
Catouse 已提交
1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226
    var isInLib = function(name, libNames, lib) {
        if(libNames) {
            var len = libNames.length;
            name = name.toLowerCase();
            var names = name + 's', nameDot = name + '.', namesDot = name + 's.';
            for(var i = 0; i < len; ++i) {
                var item = libNames[i];
                if(item === name || item === names || (lib && !lib.src && isInLib(name, lib.dpds))) {
                    return true;
                }
            }
        }
        return false;
    };

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 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285
    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;
    };

1286 1287
    var loadPackage = function (){
        loadData(PKG_JSON, function(pkg) {
1288 1289 1290 1291
            $('.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);
C
Catouse 已提交
1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325

            eachSection(function(chapter, section, $sectionList){
                var pkgLib = pkg.lib[section.id] || pkg.lib[section.id + 's'];
                var lib = {bundles: {}};
                $.each(pkgLibs, function(name, libNames){
                    if(isInLib(section.id, libNames, pkgLib)) {
                        lib.bundles[name] = true;
                    }
                });

                if(pkgLib) {
                    if(pkgLib.thirdpart) {
                        lib.thirdpart = true;
                        lib.partUrl = pkgLib.website;
                        lib.pver = pkgLib.pver;
                    }

                    if(!pkgLib.src && pkgLib.dpds) {
                        lib.custom = true;
                    }

                    if(pkgLib.ver) {
                        lib.ver = pkgLib.ver;
                    } else if(lib.custom) {
                        for(var j = 0; j < pkgLib.dpds.length; ++j) {
                            var dpdsLibName = pkgLib.dpds[j];
                            var dpdsLib = pkg.lib[dpdsLibName] || pkg.lib[dpdsLibName + 's'];
                            if(dpdsLib && dpdsLib.ver) {
                                lib.ver = dpdsLib.ver;
                                break;
                            }
                        }
                    }
                }
C
Catouse 已提交
1326

C
Catouse 已提交
1327 1328
                section.lib = lib;
            });
1329 1330 1331 1332 1333 1334 1335 1336 1337 1338
        });
    };

    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;
C
Catouse 已提交
1339 1340
            $.each(data.lib, function(itemName, item){
                if(item.custom) return;
1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375

                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);
C
Catouse 已提交
1376
            });
1377 1378 1379
            $table.find('tbody').remove();
            $table.append($tbody);
            $table.datatable({rowHover: false, fixedHeaderOffset: 200});
1380 1381 1382
        });
    };

C
Catouse 已提交
1383
    var init = function(){
1384 1385
        documentTitle = window.document.title;

C
Catouse 已提交
1386 1387 1388 1389
        var stopPropagation = function(e) {
            e.stopPropagation();
        }

C
Catouse 已提交
1390 1391
        $window = $(window);
        $body = $('body');
C
Catouse 已提交
1392
        $navbar = $('#navbar');
C
Catouse 已提交
1393 1394
        $grid = $('#grid');
        $header = $('#header');
C
Catouse 已提交
1395 1396
        $page = $('#page');
        $pageHeader = $('#pageHeader');
C
Catouse 已提交
1397
        $pageAttrs = $('#pageAttrs');
C
Catouse 已提交
1398
        $pageLoader = $('#pageLoader');
C
Catouse 已提交
1399
        $pageContent = $('#pageContent');
C
Catouse 已提交
1400 1401 1402
        $chapters = $grid.find('.chapter');
        $queryInput = $('#searchInput');
        $chapterHeadings = $grid.find('.chapter-heading');
C
Catouse 已提交
1403
        $sectionTemplate = $('#sectionTemplate').attr('id', null);
C
Catouse 已提交
1404
        $pageBody = $('#pageBody');
C
Catouse 已提交
1405 1406 1407 1408 1409 1410
        $.each(chapters, function(chapterId, chapter){
            chapterId = chapterId.toLowerCase();
            chapter.$ = $('#chapter-' + chapterId);
            chapter.id = chapterId;
            chapter.$sections = $('#sections-' + chapterId);
        });
C
Catouse 已提交
1411

C
Catouse 已提交
1412
        bestPageWidth = $grid.children('.container').outerWidth();
C
Catouse 已提交
1413 1414 1415


        // check storage
C
Catouse 已提交
1416
        storageEnable = $.zui.store && $.zui.store.enable;
C
Catouse 已提交
1417 1418 1419

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

C
Catouse 已提交
1421
        // Load index.json
C
Catouse 已提交
1422
        loadData(INDEX_JSON, function(data){
C
Catouse 已提交
1423
            var firstLoad = !sectionsShowed;
1424

C
Catouse 已提交
1425
            displaySection(data);
C
Catouse 已提交
1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436

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

                var hash = window.location.hash
                if(hash) {
1437
                    openPageUrl(hash);
C
Catouse 已提交
1438 1439 1440
                } else {
                    $queryInput.focus();
                }
1441 1442

                loadPackage();
C
Catouse 已提交
1443
            }
C
Catouse 已提交
1444 1445

            $('.doc-version').text(data.version);
C
Catouse 已提交
1446
        });
C
Catouse 已提交
1447 1448

        // Bind events
1449
        var oldActivePreivewId;
1450
        var cancelClickInPage;
C
Catouse 已提交
1451
        $(document).on('click', function(e){
1452 1453 1454 1455
            if(cancelClickInPage) {
                cancelClickInPage = false;
                return;
            }
C
Catouse 已提交
1456 1457 1458
            if(!$body.attr('data-query')) {
                chooseSection();
            }
1459 1460 1461 1462 1463
        }).on('click', 'a[href^="#"]', function(){
            openPageUrl($(this).attr('href'));
        });
        $page.on('click', function(e){
            cancelClickInPage = true;
C
Catouse 已提交
1464 1465
        });
        $grid.on('click', '.card-heading', function(e) {
C
Catouse 已提交
1466
            var $card = $(this).closest('.card');
C
Catouse 已提交
1467 1468
            if(!$card.hasClass('choosed')) {
                chooseSection($card, true);
C
Catouse 已提交
1469 1470 1471
            } else {
                $card.toggleClass('open');
            }
C
Catouse 已提交
1472
            stopPropagation(e);
1473 1474
        }).on('click', '.chapter-heading > h4 > .name', function(){
            $queryInput.focus().val('@' + $(this).closest('.chapter').data('id')).change();
C
Catouse 已提交
1475
        }).on('click', '.card', function(e){
C
Catouse 已提交
1476
            chooseSection($(this), true);
C
Catouse 已提交
1477 1478
            stopPropagation(e);
        }).on('click', '.card-heading > h5 > .name, .card-heading > .icon', function(e){
C
Catouse 已提交
1479
            openSection($(this).closest('.section'));
C
Catouse 已提交
1480
            stopPropagation(e);
C
Catouse 已提交
1481 1482 1483 1484
        }).on('click', '.topics > li > a', function(e){
            var $a = $(this);
            openPageUrl($a.attr('href'));
            e.preventDefault();
C
Catouse 已提交
1485
            stopPropagation(e);
C
Catouse 已提交
1486 1487 1488 1489
        }).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 已提交
1490 1491
        }).on('mouseenter', '#section-control-icon .section-search > ul > li > a', function(){
            oldActivePreivewId = $('#section-control-icon').data('preview');
1492
            chooseIcon($(this).closest('li'));
C
Catouse 已提交
1493
        }).on('mouseleave', '#section-control-icon .section-search > ul > li > a', function(){
1494
            if(oldActivePreivewId) {
C
Catouse 已提交
1495
                chooseIcon($('#control-icon-' + oldActivePreivewId));
1496
            }
C
Catouse 已提交
1497
        }).on('click', '#section-control-icon .section-search > ul > li > a', function(){
1498
            oldActivePreivewId = $(this).closest('li').data('id');
C
Catouse 已提交
1499 1500
        });

C
Catouse 已提交
1501
        $pageContent.on('click', 'section > header > h3', function(){
C
Catouse 已提交
1502
            togglePageSection($(this).closest('section'));
C
Catouse 已提交
1503 1504 1505 1506 1507
        }).on('mouseenter', 'section > header > h3', function(){
            $(this).closest('section').addClass('hover');
        }).on('mouseleave', 'section > header > h3', function(){
            $(this).closest('section').removeClass('hover');
        });
C
Catouse 已提交
1508
        $page.on('click', '#pageTogger', function(){
C
Catouse 已提交
1509
            togglePageSection();
C
Catouse 已提交
1510 1511
        });

C
Catouse 已提交
1512 1513 1514 1515
        $pageHeader.on('click', '.path-close-btn', function(){
            closePage();
        });

C
Catouse 已提交
1516 1517 1518
        var scrollHeight = $('#navbar').outerHeight();
        var lastScrollTop;
        $window.on('scroll', function(e){
C
Catouse 已提交
1519
            if($body.hasClass('layout-classic')) return;
C
Catouse 已提交
1520
            var isScrollAnimating = $body.data('isScrollAnimating');
C
Catouse 已提交
1521
            if(isScrollAnimating) {
1522
                $window.scrollTop(0);
C
Catouse 已提交
1523
                return;
C
Catouse 已提交
1524 1525 1526
            }
            lastScrollTop = $window.scrollTop();
            if(lastScrollTop > scrollHeight && !$body.hasClass('compact-mode')) {
C
Catouse 已提交
1527
                toggleCompactMode(true);
1528 1529
            } else if(!$body.hasClass('page-show')) {
                $header.toggleClass('with-shadow', lastScrollTop > 20);
C
Catouse 已提交
1530
            }
C
Catouse 已提交
1531 1532
        }).on('keydown', function(e){
            var code = e.which;
C
Catouse 已提交
1533
            var isPageNotShow = !$body.hasClass('page-show');
C
Catouse 已提交
1534
            var isInputFocus = $body.hasClass('input-query-focus');
1535 1536 1537 1538 1539 1540
            if(code === 9) { // Tab
                if(!$body.hasClass('input-query-focus')) {
                    $queryInput.focus();
                    e.preventDefault();
                }
            } else if(code === 13) { // Enter
C
Catouse 已提交
1541 1542
                if(isPageNotShow && isChoosedSection()) {
                    openSection();
C
Catouse 已提交
1543 1544 1545
                }
            } else if(code === 27) { // Esc
                if(!closePage()) {
C
Catouse 已提交
1546
                    if(!isInputFocus) {
1547
                        $queryInput.focus();
C
Catouse 已提交
1548
                    }
1549
                    lastQueryString = '';
1550
                    query();
C
Catouse 已提交
1551 1552
                }
            } else if(code === 37) { // Left
C
Catouse 已提交
1553
                // if(!$body.hasClass('input-query-focus')){
1554 1555
                    chooseLeftSection();
                    e.preventDefault();
C
Catouse 已提交
1556
                // }
C
Catouse 已提交
1557
            } else if(code === 39) { // Right
C
Catouse 已提交
1558
                // if(!$body.hasClass('input-query-focus')){
1559 1560
                    chooseRightSection();
                    e.preventDefault();
C
Catouse 已提交
1561
                // }
C
Catouse 已提交
1562
            } else if(code === 38) { // Top
C
Catouse 已提交
1563 1564
                if(isPageNotShow) {
                    choosePrevSection();
C
Catouse 已提交
1565
                    e.preventDefault();
C
Catouse 已提交
1566 1567 1568
                } else {
                    scrollToThis($pageBody, 'up');
                }
C
Catouse 已提交
1569
            } else if(code === 40) { // Down
C
Catouse 已提交
1570 1571
                if(isPageNotShow) {
                    chooseNextSection();
C
Catouse 已提交
1572
                    e.preventDefault();
C
Catouse 已提交
1573
                }
C
Catouse 已提交
1574 1575 1576 1577 1578
            }
        });

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

1581
        $search = $('#search');
1582

1583
        $queryInput.focus().on('change keyup paste input propertychange', function(){
C
Catouse 已提交
1584
            var val = $queryInput.val();
C
Catouse 已提交
1585 1586 1587
            if(val === lastQueryString) return;
            lastQueryString = val;
            $search.toggleClass('with-query-text', val.length > 0);
C
Catouse 已提交
1588 1589
            clearTimeout($queryInput.data(LAST_QUERY_ID));
            $queryInput.data(LAST_QUERY_ID, setTimeout(function(){
C
Catouse 已提交
1590 1591
                if(lastQueryString === $queryInput.data('queryString')) return;
                query(lastQueryString);
C
Catouse 已提交
1592
            }, 150));
C
Catouse 已提交
1593 1594 1595 1596 1597 1598 1599 1600
        }).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 已提交
1601

C
Catouse 已提交
1602 1603
        $('#searchHelpBtn').on('click', function(e){
            if($search.hasClass('with-query-text')) {
1604
                lastQueryString = '';
C
Catouse 已提交
1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615
                query();
                $queryInput.focus();
                $search.removeClass('with-query-text');
            } else {
                // query('#help');
                openSection(['resource', 'help']);
                $(this).blur();
            }
            stopPropagation(e);
        });

C
Catouse 已提交
1616
        $('#navbar .navbar-brand').on('click', function(e){
C
Catouse 已提交
1617 1618 1619 1620 1621
            if($body.hasClass('page-show')) {
                closePage();
                stopPropagation(e);
                e.preventDefault();
            } else if($body.hasClass('compact-mode-in')) {
C
Catouse 已提交
1622 1623
                $window.scrollTop(0);
                toggleCompactMode(false);
C
Catouse 已提交
1624
                stopPropagation(e);
C
Catouse 已提交
1625 1626
                e.preventDefault();
            }
1627 1628
        });

C
Catouse 已提交
1629
        $('[data-toggle="tooltip"]').tooltip({container: 'body'});
C
Catouse 已提交
1630 1631 1632
    };

    init();
1633 1634 1635 1636

    $.doc = {
        query: query,
        openSection: openSection,
C
Catouse 已提交
1637
        closePage: closePage,
C
Catouse 已提交
1638
        loadData: loadData,
1639 1640
        mutePageLoading: mutePageLoading,
        displayPkgLibTable: displayPkgLibTable
1641
    };
C
Catouse 已提交
1642
}(window, jQuery));