summaryrefslogtreecommitdiffstats
path: root/theme/javascript/core/search.js
blob: f17f746cbfb05b4daafe31a824f52724e389e618 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
define([
    "jQuery",
    "lodash",
    "lunr",
    "utils/storage",
    "core/state",
    "core/sidebar"
], function($, _, lunr, storage, state, sidebar) {
    var index = null;

    // Use a specific idnex
    var useIndex = function(data) {
        index = lunr.Index.load(data);
    };

    // Load complete index
    var loadIndex = function() {
        $.getJSON(state.basePath+"/search_index.json")
        .then(useIndex);
    };

    // Search for a term
    var search = function(q) {
        if (!index) return;
        var results = _.chain(index.search(q))
        .map(function(result) {
            var parts = result.ref.split("#")
            return {
                path: parts[0],
                hash: parts[1]
            }
        })
        .value();

        return results;
    };

    // Toggle search bar
    var toggleSearch = function(_state) {
        if (state != null && isSearchOpen() == _state) return;

        var $searchInput = $(".book-search input");
        state.$book.toggleClass("with-search", _state);

        // If search bar is open: focus input
        if (isSearchOpen()) {
            sidebar.toggle(true);
            $searchInput.focus();
        } else {
            $searchInput.blur();
            $searchInput.val("");
            sidebar.filter(null);
        }
    };

    // Return true if search bar is open
    var isSearchOpen = function() {
        return state.$book.hasClass("with-search");
    };


    var init = function() {
        loadIndex();

        // Toggle search
        $(document).on("click", ".book-header .toggle-search", function(e) {
            e.preventDefault();
            toggleSearch();
        });


        // Type in search bar
        $(document).on("keyup", ".book-search input", function(e) {
            var key = (e.keyCode ? e.keyCode : e.which);
            var q = $(this).val();

            if (key == 27) {
                e.preventDefault();
                toggleSearch(false);
                return;
            }
            if (q.length == 0) {
                sidebar.filter(null);
            } else {
                var results = search(q);
                sidebar.filter(
                    _.pluck(results, "path")
                );
            }
        })
    };

    return {
        init: init,
        search: search,
        toggle: toggleSearch
    };
});