summaryrefslogtreecommitdiffstats
path: root/theme/javascript/core/search.js
diff options
context:
space:
mode:
Diffstat (limited to 'theme/javascript/core/search.js')
-rw-r--r--theme/javascript/core/search.js106
1 files changed, 106 insertions, 0 deletions
diff --git a/theme/javascript/core/search.js b/theme/javascript/core/search.js
new file mode 100644
index 0000000..bc1a31b
--- /dev/null
+++ b/theme/javascript/core/search.js
@@ -0,0 +1,106 @@
+define([
+ "jQuery",
+ "lodash",
+ "lunr",
+ "utils/storage",
+ "core/state",
+ "core/sidebar"
+], function($, _, lunr, storage, state, sidebar) {
+ var index = null;
+ var $searchBar = state.$book.find(".book-search");
+ var $searchInput = $searchBar.find("input");
+
+ // Use a specific idnex
+ var useIndex = function(data) {
+ index = lunr.Index.load(data);
+ };
+
+ // Load complete index
+ var loadIndex = function() {
+ var cacheKey = state.revision+":"+"searchIndex";
+ var cache = storage.get(cacheKey);
+
+ if (cache) return useIndex(cache);
+
+ $.getJSON(state.basePath+"/search_index.json")
+ .then(function(index) {
+ storage.set(cacheKey, index);
+ return index;
+ })
+ .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;
+
+ 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
+ state.$book.find(".book-header .toggle-search").click(function(e) {
+ e.preventDefault();
+ toggleSearch();
+ });
+
+ $searchInput.keyup(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
+ };
+}); \ No newline at end of file