on 5bcc390 help sign in
urbit.org/static/scripts.js
349 lines 10 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}*/
61//
62 // hotkeys
63//
65function initHotKeys() {
67 var bodyEl = document.body;
68 var searchInput = document.getElementById('search');
70 document.addEventListener('keyup', function (event) {
71 if (event.defaultPrevented) {
72 return;
73 }
75 var key = event.key || event.keyCode;
77 // ESC to close search window
78 if (key === 'Escape' || key === 'Esc' || key === 27) {
79 document.body.classList.remove('has-active-search-window');
80 }
82 //when search is active TAB puts search input into focus
83 if (bodyEl.classList.contains('has-active-search-window')) {
84 if (key === 'Tab' || key === 'Tab' || key === 9) {
85 searchInput.focus();
86 }
87 }
88 });
89};
93//
94 // search functionality
95//
97function debounce(func, wait) {
98 var timeout;
100 return function () {
101 var context = this;
102 var args = arguments;
103 clearTimeout(timeout);
105 timeout = setTimeout(function () {
106 timeout = null;
107 func.apply(context, args);
108 }, wait);
109 };
112// Taken from mdbook
113// The strategy is as follows:
114// First, assign a value to each word in the document:
115// Words that correspond to search terms (stemmer aware): 40
116// Normal words: 2
117// First word in a sentence: 8
118// Then use a sliding window with a constant number of words and count the
119// sum of the values of the words within the window. Then use the window that got the
120// maximum sum. If there are multiple maximas, then get the last one.
121// Enclose the terms in <b>.
122function makeTeaser(body, terms) {
123 var TERM_WEIGHT = 40;
124 var NORMAL_WORD_WEIGHT = 2;
125 var FIRST_WORD_WEIGHT = 8;
126 //var TEASER_MAX_WORDS = 17;
127 var TEASER_MAX_CHARS = 63;
129 var stemmedTerms = terms.map(function (w) {
130 return elasticlunr.stemmer(w.toLowerCase());
131 });
132 var termFound = false;
133 var index = 0;
134 var weighted = []; // contains elements of ["word", weight, index_in_document]
136 // split in sentences, then words
137 var sentences = body.toLowerCase().split(". ");
139 for (var i in sentences) {
140 var words = sentences[i].split(" ");
141 var value = FIRST_WORD_WEIGHT;
143 for (var j in words) {
144 var word = words[j];
146 if (word.length > 0) {
147 for (var k in stemmedTerms) {
148 if (elasticlunr.stemmer(word).startsWith(stemmedTerms[k])) {
149 value = TERM_WEIGHT;
150 termFound = true;
151 }
152 }
153 weighted.push([word, value, index]);
154 value = NORMAL_WORD_WEIGHT;
155 }
157 index += word.length;
158 index += 1; // ' ' or '.' if last word in sentence
159 }
161 index += 1; // because we split at a two-char boundary '. '
162 }
164 if (weighted.length === 0) {
165 return body;
166 }
168 var windowWeights = [];
169 var windowSize = 0;
171 // loop over words (weighted) till max chars is reached adding a counter to windowSize every time a new word has passed
172 var sumChars = 0;
173 for (var i = 0; i < weighted.length; i++) {
174 sumChars += weighted[i][0].length;
175 if (sumChars <= TEASER_MAX_CHARS) {
176 windowSize++;
177 }
178 }
180 // We add a window with all the weights first
181 var curSum = 0;
182 for (var i = 0; i < windowSize; i++) {
183 curSum += weighted[i][1];
184 }
185 windowWeights.push(curSum);
187 for (var i = 0; i < weighted.length - windowSize; i++) {
188 curSum -= weighted[i][1];
189 curSum += weighted[i + windowSize][1];
190 windowWeights.push(curSum);
191 }
193 // If we didn't find the term, just pick the first window
194 var maxSumIndex = 0;
195 if (termFound) {
196 var maxFound = 0;
197 // backwards
198 for (var i = windowWeights.length - 1; i >= 0; i--) {
199 if (windowWeights[i] > maxFound) {
200 maxFound = windowWeights[i];
201 maxSumIndex = i;
202 }
203 }
204 }
206 var teaser = [];
207 var startIndex = weighted[maxSumIndex][2];
208 for (var i = maxSumIndex; i < maxSumIndex + windowSize; i++) {
209 var word = weighted[i];
210 if (startIndex < word[2]) {
211 // missing text from index to start of `word`
212 teaser.push(body.substring(startIndex, word[2]));
213 startIndex = word[2];
214 }
216 // add <em/> around search terms
217 if (word[1] === TERM_WEIGHT) {
218 teaser.push("<b>");
219 }
220 startIndex = word[2] + word[0].length;
221 teaser.push(body.substring(word[2], startIndex));
223 if (word[1] === TERM_WEIGHT) {
224 teaser.push("</b>");
225 }
226 }
227 teaser.push("…");
228 return teaser.join("");
231function formatSearchResultTitle(path) {
232 var pathArray = path.split( 'docs/' );
233 var slug = pathArray[1];
234 var slugArray = slug.split( '/' );
235 var lastPartTitle = slugArray.splice(slugArray.length - 2, slugArray.length).join('');
236 var firstPartTitle = slugArray.join(' / ');
238 var fullTitle = firstPartTitle + ' / ' + '<span class="search-results__item__title__slug-end">' + lastPartTitle + '</span>';
240 return fullTitle;
243function formatSearchResultItem(item, terms) {
244 var li = document.createElement("li");
245 var createA = document.createElement("a");
246 li.appendChild(createA);
247 var teaserTitle = formatSearchResultTitle(item.ref);
248 li.classList.add("search-results__item");
249 var hrefA = item.ref;
250 createA.setAttribute('href', hrefA);
251 createA.innerHTML = `<span class="search-results__item__title">${teaserTitle}</span>`;
252 createA.innerHTML += `<div class="search-results__teaser">${makeTeaser(item.doc.body, terms)}</div>`;
253 return li;
256function initSearch() {
257 var searchInput = document.getElementById("search");
259 if (!searchInput) {
260 return;
261 }
263 var searchResults = document.querySelector(".search-results");
264 var searchResultsHeader = document.querySelector(".search-results__header");
265 var searchResultsItems = document.querySelector(".search-results__items");
266 var MAX_ITEMS = 200;
268 var options = {
269 bool: "AND",
270 fields: {
271 title: {boost: 2},
272 body: {boost: 1},
273 }
274 };
275 var currentTerm = "";
276 var index = elasticlunr.Index.load(window.searchIndex);
278 // toggle search window
279 var toggleSearchWindow = document.getElementById('js-search-window-toggle');
280 var bodyEl = document.body;
281 var searchOverlay = document.getElementById('search-overlay');
282 var searchWindow = document.getElementById('search-window');
283 var searchActive = bodyEl.classList.contains('has-active-search-window');
284 if (toggleSearchWindow !== null) {
285 toggleSearchWindow.onclick = function() {
286 //activate search
287 bodyEl.classList.toggle('has-active-search-window');
288 //put input in focus when activating search
289 searchInput.focus();
290 searchInput.value = "";
291 searchResultsHeader.value = "";
292 searchResults.style.display = searchInput.value.trim() === "" ? "none" : "block";
293 }
294 searchOverlay.addEventListener('click', function(e){
295 if (!searchWindow.contains(e.target)){
296 bodyEl.classList.toggle('has-active-search-window');
297 }
298 })
299 }
301 // when typing
302 searchInput.addEventListener("keyup", debounce(function() {
303 searchResultsHeader.value = "";
305 var term = searchInput.value.trim();
307 /*
308 //removed to fix: a state where there’s a valid search term, but no results
310 if (term === currentTerm || !index) {
311 return;
312 }*/
314 searchResults.style.display = term === "" ? "none" : "block";
315 searchResults.style.overflowY = term === "" ? "hidden" : "scroll";
316 searchResultsItems.innerHTML = "";
317 if (term === "") {
318 return;
319 }
321 var results = index.search(term, options).filter(function (r) {
322 return r.doc.body !== "";
323 });
324 if (results.length === 0) {
325 searchResultsHeader.innerText = `No search results for '${term}'.`;
326 return;
327 }
329 currentTerm = term;
330 searchResultsHeader.innerText = `${results.length} search results for '${term}':`;
331 for (var i = 0; i < Math.min(results.length, MAX_ITEMS); i++) {
332 if (!results[i].doc.body) {
333 continue;
334 }
335 searchResultsItems.appendChild(formatSearchResultItem(results[i], term.split(" ")));
336 }
337 }, 150));
340if (document.readyState === "complete" ||
341 (document.readyState !== "loading" && !document.documentElement.doScroll)
342) {
343 initToggleSearchWindow();
344} else {
345 document.addEventListener("DOMContentLoaded", function () {
346 initSearch();
347 initHotKeys();
348 });