on e56cbdf help sign in
urbit.org/static/scripts.js
286 lines 8.4 kB history raw
1//
2 // styling of input fields
3//
5var inputElements = document.querySelectorAll('input.tlon-input');
6for (var i = 0; i < inputElements.length; i++) {
7 //listen for changes in input
8 inputElements[i].addEventListener('input', function() {
9 // if input has a value do this
10 if (this.value) {
11 var inputContainer = this.parentNode;
12 var validInputs = inputContainer.querySelectorAll('input.tlon-input:valid');
13 var inputs = inputContainer.querySelectorAll('input.tlon-input');
14 if (validInputs.length !== 0) {
15 // has valid input
16 for (var i = 0; i < validInputs.length; i++) {
17 if (this.classList.contains('is-valid') == false ) {
18 validInputs[i].parentNode.classList.add('has-valid-input');
19 }
20 }
21 } else {
22 // doesn't have valid input
23 for (var i = 0; i < inputs.length; i++) {
24 inputs[i].parentNode.classList.remove('has-valid-input');
25 }
26 }
27 } else {
28 this.parentNode.classList.remove('has-valid-input');
29 }
30 });
33//
34 // toggling of navigation menus
35//
37var toggleMainNav = document.getElementById('js-main-nav-toggle');
38if (toggleMainNav !== null) {
39 toggleMainNav.onclick = function() {
40 document.body.classList.toggle('has-active-main-nav');
41 }
44var toggleContentNav = document.getElementById('js-content-nav-toggle');
45if (toggleContentNav !== null) {
46 toggleContentNav.onclick = function() {
47 document.body.classList.toggle('has-active-content-nav');
48 }
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}*/
61function 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 }
70//
71 // search functionality
72//
74function debounce(func, wait) {
75 var timeout;
77 return function () {
78 var context = this;
79 var args = arguments;
80 clearTimeout(timeout);
82 timeout = setTimeout(function () {
83 timeout = null;
84 func.apply(context, args);
85 }, wait);
86 };
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>.
99function 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;
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]
112 // split in sentences, then words
113 var sentences = body.toLowerCase().split(". ");
115 for (var i in sentences) {
116 var words = sentences[i].split(" ");
117 var value = FIRST_WORD_WEIGHT;
119 for (var j in words) {
120 var word = words[j];
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 }
133 index += word.length;
134 index += 1; // ' ' or '.' if last word in sentence
135 }
137 index += 1; // because we split at a two-char boundary '. '
138 }
140 if (weighted.length === 0) {
141 return body;
142 }
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);
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 }
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 }
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 }
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));
189 if (word[1] === TERM_WEIGHT) {
190 teaser.push("</b>");
191 }
192 }
193 teaser.push("…");
194 return teaser.join("");
197function 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;
205// Go from the book view to the search view
206function 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 }
221function 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);
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;
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);
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 }
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 }
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));
277if (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 });