doc.js 63.1 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';
49 50
    var INDEX_JSON = 'docs/index.json';
    var ICONS_JSON = 'docs/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
    var $body, $window, $grid, $sectionTemplate,
C
Catouse 已提交
68
        $queryInput, $chapters, $chaptersCols, $pageAttrs,
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

            var url = section.url;
            if(typeof url === 'undefined') {
220
                section.url = 'docs/part/' + section.chapter + '-' + section.id + '.html';
221
                section.target = 'page';
C
Catouse 已提交
222
            } else if(isExternalUrl(url)) {
223
                section.target = 'external';
C
Catouse 已提交
224 225 226
            } else if(url && url.endsWith('.md')) {
                section.target = 'page';
                section.targetType = 'markdown';
227 228 229 230
            } else {
                section.target = '';
            }

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

252
                    if(typeof topic.id === 'undefined') topic.id = tName;
C
Catouse 已提交
253
                    var topicUrl = typeof topic.url === 'undefined' ? (sectionUrl + '/' + (topicId++)) : topic.url;
C
Catouse 已提交
254 255

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

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

C
Catouse 已提交
305 306 307
    var isChoosedSection = function($section) {
        if($section === UNDEFINED) {
            $section = $choosedSection;
C
Catouse 已提交
308
        }
C
Catouse 已提交
309
        return $section && $section.hasClass('choosed') && $section.hasClass('show');
C
Catouse 已提交
310 311
    };

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

C
Catouse 已提交
328 329
    var choosePrevSection = function() {
        var $all = $sections.filter('.show');
C
Catouse 已提交
330
        if(isChoosedSection()) {
C
Catouse 已提交
331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347
            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 已提交
348
        if(isChoosedSection()) {
C
Catouse 已提交
349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370
            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 已提交
371
        if(isChoosedSection()) {
C
Catouse 已提交
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 397 398 399 400
            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 已提交
401
        if(isChoosedSection()) {
C
Catouse 已提交
402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429
            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 已提交
430 431 432 433 434 435 436 437 438
    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 已提交
439
        $body.removeClass('query-enabled').attr('data-query', '');
C
Catouse 已提交
440 441
    };

442
    var chooseIcon = function($icon){
C
Catouse 已提交
443
        var $search = $('#section-control-icon');
444 445 446 447 448 449 450 451
        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 已提交
452
            $preview = $('#iconPreviewTemplate').clone().attr('id', '');
453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475
            $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 已提交
476
        var $section = $('#section-control-icon');
477 478 479 480 481 482 483 484 485 486 487 488 489
        $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 已提交
490
                    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>');
491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520
                    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;
521
                    } else if(key.startsWith('\\') && icon.code && icon.code.toLowerCase().includes(key.substr(1))) {
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
                        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 已提交
548
                var $li = $('#control-icon-' + iconId).toggleClass('hide', !choosed);
549 550 551 552 553 554 555 556 557
                if(choosed && bestMatchWeight < weight) {
                    bestMatchWeight = weight;
                    $bestMatch = $li;
                }
            });
            chooseIcon($bestMatch);
        });
    };

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

564 565
        if(typeof keyString === 'undefined') keyString = null;

C
Catouse 已提交
566 567 568 569 570
        if($queryInput.data('queryString') !== keyString) {
            $queryInput.data('queryString', keyString).val(keyString);
            $grid.css('min-height', $grid.height());
        }

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

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

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

C
Catouse 已提交
588 589 590 591
        var keys = [];
        $.each(keyString.split(' '), function(i, key){
            key = $.trim(key).toLowerCase();
            var keyOption = {origin: key};
592
            if(key.startsWith('@')) {
C
Catouse 已提交
593
                keyOption.type = 'id';
594 595 596 597 598
                keyOption.chapter = key.substr(1);
                keyOption.val = keyOption.chapter;
            } else if(key.startsWith('#')) {
                keyOption.type = 'id';
                keyOption.val = key.substr(2);
C
Catouse 已提交
599 600 601 602 603
            } else if(key.startsWith('icon-') || key.startsWith('icon:')) {
                keyOption.type = 'icon';
                keyOption.val = key.substr(5);
            } else if(key.startsWith('i:')) {
                keyOption.type = 'icon';
604
                keyOption.val = key.substr(2);
C
Catouse 已提交
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 630 631 632 633
            } 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;
                }
            }
634
            if(keyOption.val.length || (keyOption.type && keyOption.type !== 'any')) {
C
Catouse 已提交
635 636
                keys.push(keyOption);
            }
C
Catouse 已提交
637 638
        });

C
Catouse 已提交
639 640 641 642 643
        if(!keys.length) {
            resetQuery();
            return;
        }

C
Catouse 已提交
644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659
        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 已提交
660
                        chooseThis = section.id === 'icon';
661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676
                        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 已提交
677 678
                        break;
                    default:
C
Catouse 已提交
679 680
                        var sectionName = section.name.toLowerCase();
                        if(sectionName.includes(keyVal)) {
C
Catouse 已提交
681 682
                            chooseThisKey = true;
                            matchType = ['section', 'name'];
683 684 685 686 687 688 689
                            weight = sectionName.startsWith(keyVal) ? 85 : 82;
                            break;
                        }
                        if(section.filter && section.filter.includes(keyVal)) {
                            chooseThisKey = true;
                            matchType = ['section', 'filter'];
                            weight = 80;
C
Catouse 已提交
690 691
                            break;
                        }
C
Catouse 已提交
692 693
                        var chapterName = chapter.name.toLowerCase();
                        if(chapterName.includes(keyVal)) {
C
Catouse 已提交
694 695
                            chooseThisKey = true;
                            matchType = ['chapter', 'name'];
696 697 698 699 700 701 702
                            weight = chapterName.startsWith(keyVal) ? 75 : 73;
                            break;
                        }
                        if(chapter.filter && chapter.filter.includes(keyVal)) {
                            chooseThisKey = true;
                            matchType = ['chapter', 'filter'];
                            weight = 70;
C
Catouse 已提交
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 747 748 749 750
                            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 已提交
751
                }
C
Catouse 已提交
752 753 754
                if(!chooseThisKey) {
                    chooseThis = false;
                    return false;
C
Catouse 已提交
755
                } else {
C
Catouse 已提交
756
                    matches.push({key: key, type: matchType});
C
Catouse 已提交
757
                }
C
Catouse 已提交
758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774
            });

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

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

            if($hide.length) {
                $hide.removeClass('in');
C
Catouse 已提交
815
                setTimeout(function(){$hide.removeClass('show');}, 100);
C
Catouse 已提交
816 817 818 819 820
            }
            if($show.length) {
                $show.addClass('show');
                setTimeout(function(){$show.addClass('in');}, 20);
            }
C
Catouse 已提交
821 822

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

    var toggleCompactMode = function(toggle, callback) {
C
Catouse 已提交
830 831 832 833
        if(toggle === UNDEFINED) {
            toggle = !$body.hasClass('compact-mode');
        }

C
Catouse 已提交
834 835 836 837 838 839 840 841 842 843
        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 已提交
844
                    }, 300);
C
Catouse 已提交
845 846 847 848 849 850 851 852 853 854 855
                }, 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 已提交
856
                }, 300);
C
Catouse 已提交
857 858 859 860 861 862 863
            } else if(callback) {
                callback();
            }
        }
    };

    var closePage = function() {
864
        window['afterPageLoad'] = null;
C
Catouse 已提交
865 866 867 868 869
        window['onPageLoad'] = null;
        if($.isFunction(window['onPageClose'])) {
            window['onPageClose']();
            window['onPageClose'] = null;
        }
C
Catouse 已提交
870
        if($body.hasClass('page-open')) {
C
Catouse 已提交
871
            var style = $page.data('trans-style');
C
Catouse 已提交
872 873 874 875
            if(style){
                style['max-height'] = '';
                $page.css(style);
            }
C
Catouse 已提交
876
            $body.addClass('page-show-out').removeClass('page-open page-show-in');
877

878 879 880 881
            if($queryInput.val() !== '') {
                $queryInput.focus();
            }

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

893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918
    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 已提交
919 920 921
    var mutePageLoading = function() {
        $page.removeClass('loading');
        $pageLoader.removeClass('loading');
C
Catouse 已提交
922
        setTimeout(resizePage, 400);
C
Catouse 已提交
923 924
    };

C
Catouse 已提交
925
    var handlePageLoad = function() {
C
Catouse 已提交
926 927 928
        var delayMutedPageLoading = false;
        if($.isFunction(window['onPageLoad'])) {
            delayMutedPageLoading = window['onPageLoad']() === false;
C
Catouse 已提交
929 930
        }

C
Catouse 已提交
931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946
        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 已提交
947 948
    };

C
Catouse 已提交
949
    var openPage = function($section, section, topic) {
C
Catouse 已提交
950 951 952 953 954
        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 已提交
955
        chooseSection($section, false, true);
C
Catouse 已提交
956

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

964
        $body.attr('data-page-accent', $section.data('accent')).attr('data-page', pageId);
C
Catouse 已提交
965
        displaySectionIcon($pageHeader.find('.icon'), section);
C
Catouse 已提交
966
        $pageHeader.find('.name').text(section.name).attr('href', pageUrl);
C
Catouse 已提交
967
        $pageHeader.find('.desc').text(section.desc);
C
Catouse 已提交
968 969 970 971

        // page attributes
        $pageAttrs.hide();
        $pageAttrs.children('.badge-author').toggle(!!section.author).find('.author-name').text(section.author);
C
Catouse 已提交
972
        $pageAttrs.children('.badge-source').toggle(!!section.url).attr('href', 'https://github.com/easysoft/zui/tree/master/' + section.url);
C
Catouse 已提交
973 974 975 976 977 978 979 980 981 982 983
        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);
            
            $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 已提交
984
        $pageContent.html('');
C
Catouse 已提交
985 986
        $page.addClass('loading');
        $pageLoader.removeClass('with-error').addClass('loading');
C
Catouse 已提交
987 988
        var lastShowDataCall;
        var pageSh
C
Catouse 已提交
989 990

        loadData(section.url, function(data){
C
Catouse 已提交
991
            var showData = function(){
C
Catouse 已提交
992
                if(marked && section.targetType === 'markdown') {
C
Catouse 已提交
993
                    var $article = $();
C
Catouse 已提交
994
                    var $markdown = $(marked(data));
C
Catouse 已提交
995 996 997 998 999
                    var $lastSection, checkFirstH1 = true;
                    var hasH2 = $markdown.filter('h2').length > 0;
                    $markdown.each(function(){
                        var $tag = $(this);
                        var tagName = $tag.prop('tagName');
C
Catouse 已提交
1000 1001 1002 1003
                        if(tagName === 'STYLE' || tagName === 'SCRIPT') {
                            $article = $article.add($tag);
                            return;
                        }
C
Catouse 已提交
1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037
                        if(checkFirstH1) {
                            if(tagName === 'H1') {
                                $pageHeader.find('h2 > .name').text($tag.html());
                            }
                            checkFirstH1 = false;
                            return;
                        }
                        if((hasH2 && (tagName === 'H1' || tagName === 'H2')) || (!hasH2 && tagName === 'H3')) {
                            if($lastSection) {
                                $article = $article.add($lastSection);
                            }
                            $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());
                                }
                            }
                            if(!$lastSection) {
                                $lastSection = $('<article></article>');
                            }
                            if($lastSection.prop('tagName') === 'ARTICLE') {
                                $lastSection.append($tag);
                            } else {
                                $lastSection.children('article').append($tag);
                            }
                        }
                    });
                    if($lastSection) {
                        $article = $article.add($lastSection);
C
Catouse 已提交
1038 1039 1040 1041 1042
                    }
                    $pageContent.empty().append($article);
                } else {
                    $pageContent.html(data);
                }
C
Catouse 已提交
1043 1044 1045
                $pageBody.scrollTop(0);
                showPageTopic(topic);
                handlePageLoad();
C
Catouse 已提交
1046
                $pageAttrs.show();
C
Catouse 已提交
1047 1048 1049 1050 1051 1052 1053
            }
            if($page.hasClass('openning')) {
                if(lastShowDataCall) clearTimeout(lastShowDataCall);
                lastShowDataCall = setTimeout(showData, 320);
            } else {
                showData();
            }
C
Catouse 已提交
1054
        });
C
Catouse 已提交
1055

C
Catouse 已提交
1056 1057 1058 1059 1060 1061 1062
        if($body.hasClass('page-open')) {
            if(debug) console.log('open section in open page', section);
            return;
        }

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

C
Catouse 已提交
1063 1064
        toggleCompactMode(true, function(){
            var offset = $section.offset();
C
Catouse 已提交
1065 1066
            var sectionHeight = $section.outerHeight();
            var style = {
C
Catouse 已提交
1067 1068
                left: Math.floor(offset.left - $grid.children('.container').offset().left - 5),
                top: Math.floor(offset.top - $window.scrollTop() - 60),
C
Catouse 已提交
1069
                width: $section.outerWidth(),
C
Catouse 已提交
1070 1071 1072
                height: sectionHeight,
                'max-height': sectionHeight
            };
C
Catouse 已提交
1073 1074
            checkScrollbar();
            $body.addClass('page-show');
C
Catouse 已提交
1075 1076
            $page.css(style).data('trans-style', style);
            $pageBody.css('width', bestPageWidth);
1077

C
Catouse 已提交
1078 1079
            setTimeout(function(){
                $body.addClass('page-show-in');
C
Catouse 已提交
1080
                if($page.hasClass('loading')) $page.addClass('openning').css('height', 470);
C
Catouse 已提交
1081 1082 1083 1084
                $pageBody.scrollTop(0);
                setTimeout(function(){
                    $page.removeClass('openning');
                    bestPageWidth = $pageBody.css('width', '').width() + 40;
C
Catouse 已提交
1085
                    resizePage();
C
Catouse 已提交
1086
                }, 300);
C
Catouse 已提交
1087 1088 1089
            }, 10);
        });
    };
C
Catouse 已提交
1090

C
Catouse 已提交
1091
    var openSection = function(section, topic) {
C
Catouse 已提交
1092
        // if(debug) console.log('openSection', section, topic);
C
Catouse 已提交
1093 1094
        section = section || $choosedSection;

C
Catouse 已提交
1095
        var $section;
C
Catouse 已提交
1096
        if($.isArray(section)) {
1097
            if(typeof topic !== 'undefined') section = section.push(topic);
C
Catouse 已提交
1098 1099 1100 1101
            if(!section[0]) {
                if(debug) console.error("Open section failed: can't find the section with id " + section.join('-'));
                return;
            }
1102 1103 1104 1105
            if(section.length > 0 && section[0] === 'search') {
                query(section[1]);
                return;
            }
C
Catouse 已提交
1106
            var docIndex = dataset[INDEX_JSON].data;
C
Catouse 已提交
1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122
            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 已提交
1123
                    if(debug) console.error("Open section failed: can't find the section with id " + section.join('-'));
C
Catouse 已提交
1124 1125 1126 1127 1128 1129 1130 1131 1132
                    return;
                }
            } else {
                if(debug) {
                    console.error("Open section stop by null docIndex or wrong section value.");
                }
                return;
            }
        }
C
Catouse 已提交
1133 1134 1135 1136 1137 1138 1139 1140
        if($.isPlainObject(section)) {
            $section = $('#section-' + section.chapter + '-' + section.id);
        } else {
            var $temp = section;
            section = $temp.data('section');
            $section = $temp;
        }

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

1146 1147 1148 1149 1150 1151 1152 1153 1154
        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 已提交
1155 1156 1157 1158
        }
    };

    var resizePage = function() {
C
Catouse 已提交
1159
        if($body.hasClass('page-show-out') || $page.hasClass('loading')) return;
C
Catouse 已提交
1160 1161 1162
        var height;
        if($body.hasClass(PAGE_SHOW_FULL)) {
            height = $window.height();
1163
            $pageBody.toggleClass('with-scrollbar', $pageContent.outerHeight() > (height - 40 - $pageHeader.outerHeight() - $pageAttrs.outerHeight()));
C
Catouse 已提交
1164
        } else {
1165
            height = Math.min($pageContainer.outerHeight(), $pageHeader.outerHeight() + $pageContent.outerHeight() + 50 + $pageAttrs.outerHeight() + 20);
C
Catouse 已提交
1166
        }
C
Catouse 已提交
1167
        $page.css('height', height);
C
Catouse 已提交
1168 1169
    };

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

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

C
Catouse 已提交
1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228
    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;
    };

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 1286 1287
    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;
    };

1288 1289
    var loadPackage = function (){
        loadData(PKG_JSON, function(pkg) {
1290 1291 1292 1293
            $('.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 已提交
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 1326 1327 1328 1329 1330

            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;
                            }
                        }
                    }
                }
                
                section.lib = lib;
            });
1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 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 1376 1377 1378 1379 1380 1381 1382 1383
        });
    };

    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});
1384 1385 1386
        });
    };

C
Catouse 已提交
1387
    $(function() {
1388 1389
        documentTitle = window.document.title;

C
Catouse 已提交
1390 1391 1392 1393
        var stopPropagation = function(e) {
            e.stopPropagation();
        }

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

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

C
Catouse 已提交
1420
        $body.toggleClass(PAGE_SHOW_FULL, $.zui.store.get(PAGE_SHOW_FULL, false));
C
Catouse 已提交
1421 1422

        // check storage
C
Catouse 已提交
1423
        storageEnable = $.zui.store && $.zui.store.enable;
C
Catouse 已提交
1424 1425 1426 1427 1428 1429

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

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

C
Catouse 已提交
1431
        // Load index.json
C
Catouse 已提交
1432
        loadData(INDEX_JSON, function(data){
C
Catouse 已提交
1433
            var firstLoad = !sectionsShowed;
1434

C
Catouse 已提交
1435
            displaySection(data);
C
Catouse 已提交
1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446

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

                var hash = window.location.hash
                if(hash) {
1447
                    openPageUrl(hash);
C
Catouse 已提交
1448 1449 1450
                } else {
                    $queryInput.focus();
                }
1451 1452

                loadPackage();
C
Catouse 已提交
1453 1454
            }
        });
C
Catouse 已提交
1455 1456

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

C
Catouse 已提交
1513
        $pageContent.on('click', 'section > header > h3', function(){
C
Catouse 已提交
1514
            togglePageSection($(this).closest('section'));
C
Catouse 已提交
1515 1516 1517 1518 1519
        }).on('mouseenter', 'section > header > h3', function(){
            $(this).closest('section').addClass('hover');
        }).on('mouseleave', 'section > header > h3', function(){
            $(this).closest('section').removeClass('hover');
        });
C
Catouse 已提交
1520
        $page.on('click', '#pageTogger', function(){
C
Catouse 已提交
1521
            togglePageSection();
C
Catouse 已提交
1522 1523
        });

C
Catouse 已提交
1524 1525 1526
        $pageContent.on('resize', resizePage);
        $window.resize(resizePage);

C
Catouse 已提交
1527 1528
        $pageHeader.on('click', '.path-close-btn', function(){
            closePage();
C
Catouse 已提交
1529 1530
        }).on('click', '.path-max-btn', function(){
            $body.toggleClass(PAGE_SHOW_FULL);
C
Catouse 已提交
1531
            setTimeout(resizePage, 300);
C
Catouse 已提交
1532
            $.zui.store.set(PAGE_SHOW_FULL, $body.hasClass(PAGE_SHOW_FULL));
C
Catouse 已提交
1533 1534
        });

C
Catouse 已提交
1535 1536 1537
        var scrollHeight = $('#navbar').outerHeight();
        var lastScrollTop;
        $window.on('scroll', function(e){
C
Catouse 已提交
1538
            var isScrollAnimating = $body.data('isScrollAnimating');
C
Catouse 已提交
1539
            if(isScrollAnimating) {
C
Catouse 已提交
1540
                $window.scrollTop(1);
C
Catouse 已提交
1541
                return;
C
Catouse 已提交
1542 1543 1544
            }
            lastScrollTop = $window.scrollTop();
            if(lastScrollTop > scrollHeight && !$body.hasClass('compact-mode')) {
C
Catouse 已提交
1545
                toggleCompactMode(true);
C
Catouse 已提交
1546
            } else if(!$body.hasClass('page-show') && $body.hasClass('compact-mode')) {
C
Catouse 已提交
1547
                if(lastScrollTop < 1) {
C
Catouse 已提交
1548
                    toggleCompactMode(false);
C
Catouse 已提交
1549 1550 1551 1552
                } else {
                    $header.toggleClass('with-shadow', lastScrollTop > 20);
                }
            }
C
Catouse 已提交
1553 1554
        }).on('keydown', function(e){
            var code = e.which;
C
Catouse 已提交
1555
            // console.log('keydown', code);
C
Catouse 已提交
1556
            var isPageNotShow = !$body.hasClass('page-show');
C
Catouse 已提交
1557
            var isInputFocus = $body.hasClass('input-query-focus');
1558 1559 1560 1561 1562 1563
            if(code === 9) { // Tab
                if(!$body.hasClass('input-query-focus')) {
                    $queryInput.focus();
                    e.preventDefault();
                }
            } else if(code === 13) { // Enter
C
Catouse 已提交
1564 1565
                if(isPageNotShow && isChoosedSection()) {
                    openSection();
C
Catouse 已提交
1566 1567 1568
                }
            } else if(code === 27) { // Esc
                if(!closePage()) {
C
Catouse 已提交
1569
                    if(!isInputFocus) {
1570
                        $queryInput.focus();
C
Catouse 已提交
1571
                    }
1572
                    lastQueryString = '';
1573
                    query();
C
Catouse 已提交
1574
                }
C
Catouse 已提交
1575 1576 1577 1578 1579 1580 1581 1582 1583 1584
            // } 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 已提交
1585
            } else if(code === 37) { // Left
C
Catouse 已提交
1586
                // if(!$body.hasClass('input-query-focus')){
1587 1588
                    chooseLeftSection();
                    e.preventDefault();
C
Catouse 已提交
1589
                // }
C
Catouse 已提交
1590
            } else if(code === 39) { // Right
C
Catouse 已提交
1591
                // if(!$body.hasClass('input-query-focus')){
1592 1593
                    chooseRightSection();
                    e.preventDefault();
C
Catouse 已提交
1594
                // }
C
Catouse 已提交
1595
            } else if(code === 38) { // Top
C
Catouse 已提交
1596 1597
                if(isPageNotShow) {
                    choosePrevSection();
C
Catouse 已提交
1598
                    e.preventDefault();
C
Catouse 已提交
1599 1600 1601
                } else {
                    scrollToThis($pageBody, 'up');
                }
C
Catouse 已提交
1602
            } else if(code === 40) { // Down
C
Catouse 已提交
1603 1604
                if(isPageNotShow) {
                    chooseNextSection();
C
Catouse 已提交
1605
                    e.preventDefault();
C
Catouse 已提交
1606 1607 1608
                } else {
                    scrollToThis($pageBody);
                }
C
Catouse 已提交
1609 1610 1611 1612 1613 1614
                e.preventDefault();
            }
        });

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

1617
        $search = $('#search');
1618

1619
        $queryInput.focus().on('change keyup paste input propertychange', function(){
C
Catouse 已提交
1620
            var val = $queryInput.val();
C
Catouse 已提交
1621 1622 1623
            if(val === lastQueryString) return;
            lastQueryString = val;
            $search.toggleClass('with-query-text', val.length > 0);
C
Catouse 已提交
1624 1625
            clearTimeout($queryInput.data(LAST_QUERY_ID));
            $queryInput.data(LAST_QUERY_ID, setTimeout(function(){
C
Catouse 已提交
1626 1627
                if(lastQueryString === $queryInput.data('queryString')) return;
                query(lastQueryString);
C
Catouse 已提交
1628
            }, 150));
C
Catouse 已提交
1629 1630 1631 1632 1633 1634 1635 1636
        }).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 已提交
1637

C
Catouse 已提交
1638 1639
        $('#searchHelpBtn').on('click', function(e){
            if($search.hasClass('with-query-text')) {
1640
                lastQueryString = '';
C
Catouse 已提交
1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651
                query();
                $queryInput.focus();
                $search.removeClass('with-query-text');
            } else {
                // query('#help');
                openSection(['resource', 'help']);
                $(this).blur();
            }
            stopPropagation(e);
        });

C
Catouse 已提交
1652
        $('[data-toggle="tooltip"]').tooltip({container: 'body'});
C
Catouse 已提交
1653
    });
1654 1655 1656 1657

    $.doc = {
        query: query,
        openSection: openSection,
C
Catouse 已提交
1658
        closePage: closePage,
C
Catouse 已提交
1659
        loadData: loadData,
1660 1661
        mutePageLoading: mutePageLoading,
        displayPkgLibTable: displayPkgLibTable
1662
    };
C
Catouse 已提交
1663
}(window, jQuery));