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