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

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

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

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

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

C
Catouse 已提交
51 52 53 54
    var $body, $window, $grid, $sectionTemplate,
        $queryInput, $chapters, $chaptersCols,
        $choosedSection,
        $header, $sections, $chapterHeadings; // elements
C
Catouse 已提交
55 56 57 58 59 60

    var loadData = function(url, callback, forceLoad) {
        var data = dataset[url];
        var isFirstLoad = data === null;
        if(isFirstLoad) {
            data = $.store.get(url, null);
C
Catouse 已提交
61
            dataset[url] = data;
C
Catouse 已提交
62
            if(data !== null) {
C
Catouse 已提交
63 64 65
                if(debug) {
                    console.log('Load data from storage: ', url, '=', data);
                }
C
Catouse 已提交
66 67
                callback(data);
            }
C
Catouse 已提交
68 69
        }

C
Catouse 已提交
70 71 72 73 74 75 76 77
        if(data === null || forceLoad || isFirstLoad || (!saveTraffic)) {
            var dataType = url.endsWith('.json') ? 'json' : 'html';
            $.get(url, function(remoteData){
                if(!debug && data !== null) {
                    if(dataType === 'json' && $.isPlainObject(remoteData) && data.version && remoteData.version && remoteData.version === data.version) return;
                    if(dataType === 'html' && data === remoteData) return;
                }
                dataset[url] = remoteData;
C
Catouse 已提交
78 79 80
                if(debug) {
                    console.log('Load data from remote: ', url, '=', remoteData);
                }
C
Catouse 已提交
81 82 83 84
                callback(remoteData);
                $.store.set(url, remoteData);
            }, dataType);
        }
C
Catouse 已提交
85 86 87 88 89 90 91 92
    };

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

C
Catouse 已提交
94 95
        $.each(chapters, function(chapterName, chapter){
            if(!docIndex.chapters[chapterName]) return;
C
Catouse 已提交
96 97 98 99 100 101 102 103 104 105 106 107 108
            $.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 已提交
109

C
Catouse 已提交
110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139
    var displaySection = function() {
        if(eachSection(function(chapter, section, $sectionList){
            var chapterName = chapter.id;
            var $tpl = $sectionTemplate.clone().attr('id', 'section-' + chapterName + '-' + section.id);
            $tpl.attr('data-id', section.id);
            var $head = $tpl.children('.card-heading');
            $head.find('.name').text(section.name);
            $head.children('.desc').text(section.desc);
            var $icon = $head.children('.icon');
            if (section.icon === undefined || section.icon === null || section.icon === "") {
                section.icon = section.name.substr(0, 1).toUpperCase();
            }
            if (section.icon.indexOf('icon-') === 0) {
                $icon.addClass(section.icon);
            } else {
                $icon.addClass('text-icon').text(section.icon);
            }
            var $topics = $tpl.find('.topics');
            if (section.topics && section.topics.length) {
                for (var tName in section.topics) {
                    var topic = section.topics[tName];
                    topic.id = tName;
                    $topics.append('<li data-id="' + tName + '">' + topic.name + '</li>');
                }
            } else {
                $topics.remove('.card-content');
                $tpl.addClass('without-topics');
            }
            $sectionList.append($tpl.addClass('show'));
        }, function(chapter, sections){
C
Catouse 已提交
140 141
            var $sectionList = chapter.$sections;
            $sectionList.children().remove();
C
Catouse 已提交
142 143 144 145 146 147
            return $sectionList;
        })) {
            clearTimeout($grid.data(LAST_RELOAD_ANIMATE_ID));
            $grid.data(LAST_RELOAD_ANIMATE_ID, setTimeout(function(){
                $sections = $grid.find('.section').addClass('in');
                $chapterHeadings.addClass('in');
C
Catouse 已提交
148
            }, 100));
C
Catouse 已提交
149 150 151 152 153 154
        } else if(debug) {
            console.error("Display sections failed.");
        }
    };

    var chooseSection = function($section) {
C
Catouse 已提交
155 156 157 158 159
        if($sections) {
            $sections.removeClass('choosed open');
            if($section && $section.hasClass('section')) {
                $choosedSection = $section.addClass('choosed open');
            }
C
Catouse 已提交
160 161 162
        }
    }

C
Catouse 已提交
163 164 165 166 167 168 169 170 171 172 173 174
    var resetQuery = function() {
        $chaptersCols.removeClass('hide');
        $chapters.removeClass('hide');
        $sections.addClass('show');
        $chapterHeadings.addClass('show');
        $grid.data(LAST_RELOAD_ANIMATE_ID, setTimeout(function(){
            $sections.addClass('in');
            $chapterHeadings.addClass('in');
        }, 20));
        $body.removeClass('query-enabled');
    };

C
Catouse 已提交
175 176 177 178 179 180 181 182 183
    var query = function(keyString) {
        if(!$sections) return;

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

        if(keyString === UNDEFINED || keyString === null || !keyString.length) {
C
Catouse 已提交
184
            resetQuery();
C
Catouse 已提交
185 186 187
            return;
        }

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

C
Catouse 已提交
190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231
        var keys = [];
        $.each(keyString.split(' '), function(i, key){
            key = $.trim(key).toLowerCase();
            var keyOption = {origin: key};
            if(key.startsWith('#')) {
                keyOption.type = 'id';
                keyOption.val = key.substr(1);
            } else if(key.startsWith('icon-') || key.startsWith('icon:')) {
                keyOption.type = 'icon';
                keyOption.val = key.substr(5);
            } else if(key.startsWith('i:')) {
                keyOption.type = 'icon';
                keyOption.val = key.substr(1);
            } else if(key.startsWith('ver:')) {
                keyOption.type = 'version';
                keyOption.val = key.substr(4);
            } else if(key.startsWith('v:')) {
                keyOption.type = 'version';
                keyOption.val = key.substr(2);
            } else if(key.startsWith('version:')) {
                keyOption.type = 'version';
                keyOption.val = key.substr(8);
            } else if(key.startsWith('grunt:') || key.startsWith('build:')) {
                keyOption.type = 'build';
                keyOption.val = key.substr(6);
            } else if(key.startsWith('g:') || key.startsWith('b:')) {
                keyOption.type = 'build';
                keyOption.val = key.substr(2);
            } else {
                $.each(chapters, function(name){
                    if(key.startsWith(name + ':')) {
                        keyOption.type = 'id';
                        keyOption.chapter = name;
                        keyOption.val = key.substr(name.length);
                        return false;
                    }
                });
                if(!keyOption.type) {
                    keyOption.type = 'any';
                    keyOption.val = key;
                }
            }
C
Catouse 已提交
232 233 234
            if(keyOption.val.length) {
                keys.push(keyOption);
            }
C
Catouse 已提交
235 236
        });

C
Catouse 已提交
237 238 239 240 241
        if(!keys.length) {
            resetQuery();
            return;
        }

C
Catouse 已提交
242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320
        var resultMap = {}, chapterMap = {}, weight, id, chooseThis, chooseThisKey, keyVal, matches, matchType;
        if(eachSection(function(chapter, section){
            chooseThis = true;
            matches = [];
            weight = 0;
            $.each(keys, function(keyIndex, key){
                keyVal = key.val;
                matchType = null;
                chooseThisKey = false;
                switch(key.type) {
                    case 'id':
                        chooseThisKey = (key.chapter ? chapter : section).id.includes(keyVal);
                        if(chooseThisKey) matchType = [key.chapter ? 'chapter' : 'section', 'id'];
                        weight = 100;
                        break;
                    case 'icon':
                        chooseThisKey = section.id === 'icons';
                        if(chooseThisKey) matchType = ['section', 'id'];
                        weight = 100;
                        break;
                    default:
                        if(section.name.toLowerCase().includes(keyVal)) {
                            chooseThisKey = true;
                            matchType = ['section', 'name'];
                            weight = 80;
                            break;
                        }
                        if(chapter.name.toLowerCase().includes(keyVal)) {
                            chooseThisKey = true;
                            matchType = ['chapter', 'name'];
                            weight = 70;
                            break;
                        }
                        if(keyVal.length > 1) {
                            if(section.id.includes(keyVal)) {
                                chooseThisKey = true;
                                matchType = ['section', 'id'];
                                weight = 65;
                                break;
                            }
                            if(chapter.id.includes(keyVal)) {
                                chooseThisKey = true;
                                matchType = ['chapter', 'id'];
                                weight = 60;
                                break;
                            }
                            if($.isArray(section.topics)) {
                                var isBreak = false;
                                $.each(section.topics, function(topicIndex, topic){
                                    if(topic.name && topic.name.toLowerCase().includes(keyVal)) {
                                        chooseThisKey = true;
                                        matchType = ['section', 'topic', topicIndex];
                                        isBreak = true;
                                        weight = 20;
                                        return false;
                                    }
                                });
                                if(isBreak) break;
                            }
                            if(section.desc.toLowerCase().includes(keyVal)) {
                                chooseThisKey = true;
                                matchType = 'section.desc';
                                weight = 30;
                                break;
                            }
                        } else {
                            if(chapter.id.startsWith(keyVal)) {
                                chooseThisKey = true;
                                matchType = ['chapter', 'id'];
                                weight = 60;
                                break;
                            }
                            if(section.id.startsWith(keyVal)) {
                                chooseThisKey = true;
                                matchType = ['section', 'id'];
                                weight = 50;
                                break;
                            }
                        }
C
Catouse 已提交
321
                }
C
Catouse 已提交
322 323 324
                if(!chooseThisKey) {
                    chooseThis = false;
                    return false;
C
Catouse 已提交
325
                } else {
C
Catouse 已提交
326
                    matches.push({key: key, type: matchType});
C
Catouse 已提交
327
                }
C
Catouse 已提交
328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344
            });

            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 已提交
345
                } else {
C
Catouse 已提交
346 347 348 349 350
                    $show = $show.add($section);
                    if(choosedWeight < result.weight) {
                        $choosed = $section;
                        choosedWeight = result.weight;
                    }
C
Catouse 已提交
351
                }
C
Catouse 已提交
352
                chooseSection($choosed);
C
Catouse 已提交
353
            });
C
Catouse 已提交
354 355 356 357 358 359 360 361

            var $chapter, hide, chapter;
            $.each(chapterMap, function(chapterId, resultCount){
                chapter = chapters[chapterId];
                hide = !resultCount;
                chapter.$.toggleClass('hide', hide);
            });
            var $col;
C
Catouse 已提交
362
            var showColCount = 0;
C
Catouse 已提交
363 364
            $chaptersCols.each(function(){
                $col = $(this);
C
Catouse 已提交
365 366 367 368 369 370 371 372 373 374 375 376 377 378 379
                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 已提交
380
            });
C
Catouse 已提交
381
            $grid.attr('data-show-col', showColCount);
C
Catouse 已提交
382 383 384

            if($hide.length) {
                $hide.removeClass('in');
C
Catouse 已提交
385
                setTimeout(function(){$hide.removeClass('show');}, 100);
C
Catouse 已提交
386 387 388 389 390 391 392 393
            }
            if($show.length) {
                $show.addClass('show');
                setTimeout(function(){$show.addClass('in');}, 20);
            }
        } else if(debug) {
            console.error("Query failed with key: ", keys);
        }
C
Catouse 已提交
394 395
    }

C
Catouse 已提交
396
    $(function() {
C
Catouse 已提交
397 398 399 400
        var stopPropagation = function(e) {
            e.stopPropagation();
        }

C
Catouse 已提交
401 402 403 404
        $window = $(window);
        $body = $('body');
        $grid = $('#grid');
        $header = $('#header');
C
Catouse 已提交
405 406 407 408
        $chaptersCols = $grid.find('.col');
        $chapters = $grid.find('.chapter');
        $queryInput = $('#searchInput');
        $chapterHeadings = $grid.find('.chapter-heading');
C
Catouse 已提交
409
        $sectionTemplate = $('#sectionTemplate').attr('id', null);
C
Catouse 已提交
410 411 412 413 414 415
        $.each(chapters, function(chapterId, chapter){
            chapterId = chapterId.toLowerCase();
            chapter.$ = $('#chapter-' + chapterId);
            chapter.id = chapterId;
            chapter.$sections = $('#sections-' + chapterId);
        });
C
Catouse 已提交
416 417 418 419

        loadData(INDEX_JSON, displaySection)

        // Bind events
C
Catouse 已提交
420 421 422 423 424
        $(document).on('click', function(){
            chooseSection();
            $sections.removeClass('open');
        });
        $grid.on('click', '.card-heading', function(e) {
C
Catouse 已提交
425 426 427 428 429 430
            var $card = $(this).closest('.card');
            if($card.hasClass('without-topics')) {
                $card.find('.btn-toggle').trigger('click');
            } else {
                $card.toggleClass('open');
            }
C
Catouse 已提交
431 432 433
        }).on('click', '.card', function(e){
            chooseSection($(this));
            e.stopPropagation();
C
Catouse 已提交
434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468
        }).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');
        });

        var scrollHeight = $('#navbar').outerHeight();
        var isScrollAnimating = false;
        var lastScrollTop;
        $window.on('scroll', function(e){
            if(isScrollAnimating) {
                $window.scrollTop(lastScrollTop);
            }
            lastScrollTop = $window.scrollTop();
            if(lastScrollTop > scrollHeight && !$body.hasClass('compact-mode')) {
                isScrollAnimating = true;
                $body.addClass('compact-mode')
                setTimeout(function(){
                    $window.scrollTop(1);
                    $body.addClass('compact-mode-in');
                    isScrollAnimating = false;
                }, 10);
            } else if($body.hasClass('compact-mode')) {
                if(lastScrollTop < 1) {
                    isScrollAnimating = true;
                    $body.removeClass('compact-mode-in');
                    setTimeout(function(){
                        $body.removeClass('compact-mode');
                        isScrollAnimating = false;
                    }, 500);
                } else {
                    $header.toggleClass('with-shadow', lastScrollTop > 20);
                }
            }
        });
C
Catouse 已提交
469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484

        $queryInput.on('change keyup paste input propertychange', function(){
            var val = $queryInput.val();
            if(val === $queryInput.data('queryString')) return;
            clearTimeout($queryInput.data(LAST_QUERY_ID));
            $queryInput.data(LAST_QUERY_ID, setTimeout(function(){
                query(val);
            }, 150))
        }).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 已提交
485
    });
C
Catouse 已提交
486
}(window, jQuery));