on master help sign in
finished the search functionality
commite56cbdf369b7f32bdf57645c27850b69b89a343f authorfriederjanmoerman <hijbrid@gmail.com> dateTue 28 May 2019, 18:28 (7 years ago) parentd80a301
4 files changed+267−20
sass/_main.scss+7−1 static/scripts.js+255−18 templates/base.html+4 templates/partials/navigation-docs.html+1−1
sass/_main.scss+7−1
@@ -47,7 +47,6 @@ iframe {
4747 margin: 14rem auto;
4848 background: #fff;
4949 padding: 7rem 14rem;
50− height: 400px; //temporary
5150}
5251
5352.container--fixed {
@@ -296,6 +295,7 @@ iframe {
296295 top: 0;
297296 left: 0;
298297 z-index: 10;
298+ display: none;
299299 .search-bar {
300300 width: 100%;
301301 padding: 0;
@@ -315,6 +315,12 @@ iframe {
315315 }
316316}
317317
318+.has-active-search-window {
319+ .search-overlay {
320+ display: block;
321+ }
322+}
323+
318324/*
319325 * styling
320326 */
static/scripts.js+255−18
@@ -1,21 +1,3 @@
1−//
2− // toggling of navigation menus
3−//
4−
5−var toggleMainNav = document.getElementById('js-main-nav-toggle');
6−if (toggleMainNav !== null) {
7− toggleMainNav.onclick = function() {
8− document.body.classList.toggle('has-active-main-nav');
9− }
10−}
11−
12−var toggleContentNav = document.getElementById('js-content-nav-toggle');
13−if (toggleContentNav !== null) {
14− toggleContentNav.onclick = function() {
15− document.body.classList.toggle('has-active-content-nav');
16− }
17−}
18−
191//
202 // styling of input fields
213//
@@ -47,3 +29,258 @@ for (var i = 0; i < inputElements.length; i++) {
4729 }
4830 });
4931}
32+
33+//
34+ // toggling of navigation menus
35+//
36+
37+var toggleMainNav = document.getElementById('js-main-nav-toggle');
38+if (toggleMainNav !== null) {
39+ toggleMainNav.onclick = function() {
40+ document.body.classList.toggle('has-active-main-nav');
41+ }
42+}
43+
44+var toggleContentNav = document.getElementById('js-content-nav-toggle');
45+if (toggleContentNav !== null) {
46+ toggleContentNav.onclick = function() {
47+ document.body.classList.toggle('has-active-content-nav');
48+ }
49+}
50+
51+/*function initToggleMenu() {
52+ var menu = document.querySelector(".menu");
53+ var menuIcon = document.querySelector(".menu-icon");
54+ var page = document.querySelector(".page");
55+ menuIcon.addEventListener("click", function() {
56+ menu.classList.toggle("menu-hidden");
57+ page.classList.toggle("page-without-menu");
58+ });
59+}*/
60+
61+function initToggleMenu() {
62+ var toggleContentNav = document.getElementById('js-search-window-toggle');
63+ if (toggleContentNav !== null) {
64+ toggleContentNav.onclick = function() {
65+ document.body.classList.toggle('has-active-search-window');
66+ }
67+ }
68+}
69+
70+//
71+ // search functionality
72+//
73+
74+function debounce(func, wait) {
75+ var timeout;
76+
77+ return function () {
78+ var context = this;
79+ var args = arguments;
80+ clearTimeout(timeout);
81+
82+ timeout = setTimeout(function () {
83+ timeout = null;
84+ func.apply(context, args);
85+ }, wait);
86+ };
87+}
88+
89+// Taken from mdbook
90+// The strategy is as follows:
91+// First, assign a value to each word in the document:
92+// Words that correspond to search terms (stemmer aware): 40
93+// Normal words: 2
94+// First word in a sentence: 8
95+// Then use a sliding window with a constant number of words and count the
96+// sum of the values of the words within the window. Then use the window that got the
97+// maximum sum. If there are multiple maximas, then get the last one.
98+// Enclose the terms in <b>.
99+function makeTeaser(body, terms) {
100+ var TERM_WEIGHT = 40;
101+ var NORMAL_WORD_WEIGHT = 2;
102+ var FIRST_WORD_WEIGHT = 8;
103+ var TEASER_MAX_WORDS = 30;
104+
105+ var stemmedTerms = terms.map(function (w) {
106+ return elasticlunr.stemmer(w.toLowerCase());
107+ });
108+ var termFound = false;
109+ var index = 0;
110+ var weighted = []; // contains elements of ["word", weight, index_in_document]
111+
112+ // split in sentences, then words
113+ var sentences = body.toLowerCase().split(". ");
114+
115+ for (var i in sentences) {
116+ var words = sentences[i].split(" ");
117+ var value = FIRST_WORD_WEIGHT;
118+
119+ for (var j in words) {
120+ var word = words[j];
121+
122+ if (word.length > 0) {
123+ for (var k in stemmedTerms) {
124+ if (elasticlunr.stemmer(word).startsWith(stemmedTerms[k])) {
125+ value = TERM_WEIGHT;
126+ termFound = true;
127+ }
128+ }
129+ weighted.push([word, value, index]);
130+ value = NORMAL_WORD_WEIGHT;
131+ }
132+
133+ index += word.length;
134+ index += 1; // ' ' or '.' if last word in sentence
135+ }
136+
137+ index += 1; // because we split at a two-char boundary '. '
138+ }
139+
140+ if (weighted.length === 0) {
141+ return body;
142+ }
143+
144+ var windowWeights = [];
145+ var windowSize = Math.min(weighted.length, TEASER_MAX_WORDS);
146+ // We add a window with all the weights first
147+ var curSum = 0;
148+ for (var i = 0; i < windowSize; i++) {
149+ curSum += weighted[i][1];
150+ }
151+ windowWeights.push(curSum);
152+
153+ for (var i = 0; i < weighted.length - windowSize; i++) {
154+ curSum -= weighted[i][1];
155+ curSum += weighted[i + windowSize][1];
156+ windowWeights.push(curSum);
157+ }
158+
159+ // If we didn't find the term, just pick the first window
160+ var maxSumIndex = 0;
161+ if (termFound) {
162+ var maxFound = 0;
163+ // backwards
164+ for (var i = windowWeights.length - 1; i >= 0; i--) {
165+ if (windowWeights[i] > maxFound) {
166+ maxFound = windowWeights[i];
167+ maxSumIndex = i;
168+ }
169+ }
170+ }
171+
172+ var teaser = [];
173+ var startIndex = weighted[maxSumIndex][2];
174+ for (var i = maxSumIndex; i < maxSumIndex + windowSize; i++) {
175+ var word = weighted[i];
176+ if (startIndex < word[2]) {
177+ // missing text from index to start of `word`
178+ teaser.push(body.substring(startIndex, word[2]));
179+ startIndex = word[2];
180+ }
181+
182+ // add <em/> around search terms
183+ if (word[1] === TERM_WEIGHT) {
184+ teaser.push("<b>");
185+ }
186+ startIndex = word[2] + word[0].length;
187+ teaser.push(body.substring(word[2], startIndex));
188+
189+ if (word[1] === TERM_WEIGHT) {
190+ teaser.push("</b>");
191+ }
192+ }
193+ teaser.push("…");
194+ return teaser.join("");
195+}
196+
197+function formatSearchResultItem(item, terms) {
198+ var li = document.createElement("li");
199+ li.classList.add("search-results__item");
200+ li.innerHTML = `<a href="${item.ref}">${item.doc.title}</a>`;
201+ li.innerHTML += `<div class="search-results__teaser">${makeTeaser(item.doc.body, terms)}</div>`;
202+ return li;
203+}
204+
205+// Go from the book view to the search view
206+function toggleSearchMode() {
207+ var bookContent = document.querySelector(".book-content");
208+ var searchContainer = document.querySelector(".search-container");
209+ if (searchContainer.classList.contains("search-container--is-visible")) {
210+ searchContainer.classList.remove("search-container--is-visible");
211+ document.body.classList.remove("search-mode");
212+ bookContent.style.display = "block";
213+ } else {
214+ searchContainer.classList.add("search-container--is-visible");
215+ document.body.classList.add("search-mode");
216+ $bookContent.style.display = "none";
217+ document.getElementById("search").focus();
218+ }
219+}
220+
221+function initSearch() {
222+ var searchInput = document.getElementById("search");
223+ if (!searchInput) {
224+ return;
225+ }
226+ var searchIcon = document.getElementById("js-search-window-toggle");
227+ searchIcon.addEventListener("click", toggleSearchMode);
228+
229+ var searchResults = document.querySelector(".search-results");
230+ var searchResultsHeader = document.querySelector(".search-results__header");
231+ var searchResultsItems = document.querySelector(".search-results__items");
232+ var MAX_ITEMS = 10;
233+
234+ var options = {
235+ bool: "AND",
236+ fields: {
237+ title: {boost: 2},
238+ body: {boost: 1},
239+ }
240+ };
241+ var currentTerm = "";
242+ var index = elasticlunr.Index.load(window.searchIndex);
243+
244+ searchInput.addEventListener("keyup", debounce(function() {
245+ var term = searchInput.value.trim();
246+ if (term === currentTerm || !index) {
247+ return;
248+ }
249+ searchResults.style.display = term === "" ? "none" : "block";
250+ searchResultsItems.innerHTML = "";
251+ if (term === "") {
252+ return;
253+ }
254+
255+ var results = index.search(term, options).filter(function (r) {
256+ return r.doc.body !== "";
257+ });
258+ if (results.length === 0) {
259+ searchResultsHeader.innerText = `No search results for '${term}'.`;
260+ return;
261+ }
262+
263+ currentTerm = term;
264+ searchResultsHeader.innerText = `${results.length} search results for '${term}':`;
265+ for (var i = 0; i < Math.min(results.length, MAX_ITEMS); i++) {
266+ if (!results[i].doc.body) {
267+ continue;
268+ }
269+ // var item = document.createElement("li");
270+ // item.innerHTML = formatSearchResultItem(results[i], term.split(" "));
271+ console.log(results[i]);
272+ searchResultsItems.appendChild(formatSearchResultItem(results[i], term.split(" ")));
273+ }
274+ }, 150));
275+}
276+
277+if (document.readyState === "complete" ||
278+ (document.readyState !== "loading" && !document.documentElement.doScroll)
279+) {
280+ initToggleMenu();
281+} else {
282+ document.addEventListener("DOMContentLoaded", function () {
283+ initToggleMenu();
284+ initSearch();
285+ });
286+}
templates/base.html+4
@@ -26,6 +26,10 @@
2626 {% block content %}
2727 {% endblock content %}
2828 <!-- scripts -->
29+ {% if config.build_search_index %}
30+ <script type="text/javascript" src="{{ get_url(path="elasticlunr.min.js") | safe }}"></script>
31+ <script type="text/javascript" src="{{ get_url(path="search_index.en.js") | safe }}"></script>
32+ {% endif %}
2933 <script src="{{ config.base_url }}/scripts.js"></script>
3034 </body>
3135</html>
templates/partials/navigation-docs.html+1−1
@@ -1,7 +1,7 @@
11{% block content %}
22<div id="js-content-nav-toggle" class="content-nav-icon"></div>
33<nav class="content-nav">
4− <button type="button" class="search-bar content-nav__search-bar mb2">Search</button>
4+ <button id="js-search-window-toggle" type="button" class="search-bar content-nav__search-bar mb2">Search</button>
55 <ul class="list content-nav__index">
66 {% block menu %}
77 {% set index = get_section(path="docs/_index.md") %}