on d09c724 help sign in
urbit.org/static/scripts.js
379 lines 11 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 });
141 var termFound = false;
142 var index = 0;
143 var weighted = []; // contains elements of ["word", weight, index_in_document]
145 // split in sentences, then words
146 var sentences = body.toLowerCase().split(". ");
148 for (var i in sentences) {
149 var words = sentences[i].split(" ");
150 var value = FIRST_WORD_WEIGHT;
152 for (var j in words) {
153 var word = words[j];
155 if (word.length > 0) {
156 for (var k in stemmedTerms) {
157 if (elasticlunr.stemmer(word).startsWith(stemmedTerms[k])) {
158 value = TERM_WEIGHT;
159 termFound = true;
160 }
161 }
162 weighted.push([word, value, index]);
163 value = NORMAL_WORD_WEIGHT;
164 }
166 index += word.length;
167 index += 1; // ' ' or '.' if last word in sentence
168 }
170 index += 1; // because we split at a two-char boundary '. '
171 }
173 if (weighted.length === 0) {
174 return body;
175 }
177 var windowWeights = [];
178 var windowSize = 0;
180 // loop over words (weighted) till max chars is reached adding a counter to windowSize every time a new word has passed
181 var sumChars = 0;
182 for (var i = 0; i < weighted.length; i++) {
183 sumChars += weighted[i][0].length;
184 if (sumChars <= TEASER_MAX_CHARS) {
185 windowSize++;
186 }
187 }
189 // We add a window with all the weights first
190 var curSum = 0;
191 for (var i = 0; i < windowSize; i++) {
192 curSum += weighted[i][1];
193 }
194 windowWeights.push(curSum);
196 for (var i = 0; i < weighted.length - windowSize; i++) {
197 curSum -= weighted[i][1];
198 curSum += weighted[i + windowSize][1];
199 windowWeights.push(curSum);
200 }
202 // If we didn't find the term, just pick the first window
203 var maxSumIndex = 0;
204 if (termFound) {
205 var maxFound = 0;
206 // backwards
207 for (var i = windowWeights.length - 1; i >= 0; i--) {
208 if (windowWeights[i] > maxFound) {
209 maxFound = windowWeights[i];
210 maxSumIndex = i;
211 }
212 }
213 }
215 var teaser = [];
216 var startIndex = weighted[maxSumIndex][2];
217 for (var i = maxSumIndex; i < maxSumIndex + windowSize; i++) {
218 var word = weighted[i];
219 if (startIndex < word[2]) {
220 // missing text from index to start of `word`
221 teaser.push(body.substring(startIndex, word[2]));
222 startIndex = word[2];
223 }
225 // add dark color around search terms
226 if (word[1] === TERM_WEIGHT) {
227 teaser.push("<span class='gray70'>");
228 }
229 startIndex = word[2] + word[0].length;
230 teaser.push(body.substring(word[2], startIndex));
232 if (word[1] === TERM_WEIGHT) {
233 teaser.push("</span>");
234 }
235 }
236 teaser.push("…");
237 return teaser.join("");
240function formatSearchResultTitle(path) {
241// console.log(path);
242 var pathArray = path.split( '/' );
243 //console.log(pathArray);
244 /*var slug = pathArray[1];
245// console.log(slug);
246 var slugArray = slug.split( '/' );
247 var lastPartTitle = slugArray.splice(slugArray.length - 2, slugArray.length).join('');
248 var firstPartTitle = slugArray.join(' / ');
249//console.log(lastPartTitle);
250//console.log(firstPartTitle);
251*/
252 var firstPartTitle = pathArray[3]; // first directory is in 4th element of path array
253 var lastPartTitle = pathArray[pathArray.length-2]; // last directory is in 2nd to last element of array
254 var fullTitle = firstPartTitle + '<span class="gray90">' + ' / ' + lastPartTitle + '</span>';
255 console.log(fullTitle);
256 return fullTitle;
257/*
258 var pathArray = path.split( 'docs/' );
259// console.log(pathArray);
260 var slug = pathArray[1];
261// console.log(slug);
262 var slugArray = slug.split( '/' );
263 var lastPartTitle = slugArray.splice(slugArray.length - 2, slugArray.length).join('');
264 var firstPartTitle = slugArray.join(' / ');
266 var fullTitle = firstPartTitle + '<span class="gray90">' + ' / ' + lastPartTitle + '</span>';
268 return fullTitle;
269 */
272function formatSearchResultItem(item, terms) {
273 var li = document.createElement("li");
274 var createA = document.createElement("a");
275 li.appendChild(createA);
276 var teaserTitle = formatSearchResultTitle(item.ref);
277 li.classList.add("search-results__item");
278 var hrefA = item.ref;
279 createA.setAttribute('href', hrefA);
280 createA.setAttribute('class','no-underline block pl6 pv2');
281 createA.innerHTML = `<span class="fs45 capitalize gray30">${teaserTitle}</span>`;
282 createA.innerHTML += `<div class="fs35 gray30">${makeTeaser(item.doc.body, terms)}</div>`;
283 return li;
286function initSearch() {
287 var searchInput = document.getElementById("search");
289 if (!searchInput) {
290 return;
291 }
293 var searchResults = document.querySelector(".search-results");
294 var searchResultsHeader = document.querySelector(".search-results__header");
295 var searchResultsItems = document.querySelector(".search-results__items");
296 var MAX_ITEMS = 200;
298 var options = {
299 bool: "AND",
300 fields: {
301 title: {boost: 2},
302 body: {boost: 1},
303 }
304 };
305 var currentTerm = "";
306 var index = elasticlunr.Index.load(window.searchIndex);
308 // toggle search window
309 var toggleSearchWindow = document.getElementById('js-search-window-toggle');
310 var bodyEl = document.body;
311 var searchOverlay = document.getElementById('search-overlay');
312 var searchWindow = document.getElementById('search-window');
313 var searchActive = bodyEl.classList.contains('has-active-search-window');
314 if (toggleSearchWindow !== null) {
315 toggleSearchWindow.onclick = function() {
316 //activate search
317 bodyEl.classList.toggle('has-active-search-window');
318 //put input in focus when activating search
319 searchInput.focus();
320 searchInput.value = "";
321 searchResultsHeader.value = "";
322 searchResults.style.display = searchInput.value.trim() === "" ? "none" : "block";
323 }
324 searchOverlay.addEventListener('click', function(e){
325 if (!searchWindow.contains(e.target)){
326 bodyEl.classList.toggle('has-active-search-window');
327 }
328 })
329 }
331 // when typing
332 searchInput.addEventListener("keyup", debounce(function() {
333 searchResultsHeader.value = "";
335 var term = searchInput.value.trim();
337 /*
338 //removed to fix: a state where there’s a valid search term, but no results
340 if (term === currentTerm || !index) {
341 return;
342 }*/
344 searchResults.style.display = term === "" ? "none" : "block";
345 searchResults.style.overflowY = term === "" ? "hidden" : "scroll";
346 searchResultsItems.innerHTML = "";
347 if (term === "") {
348 return;
349 }
351 var results = index.search(term, options).filter(function (r) {
352 return r.doc.body !== "";
353 });
354 if (results.length === 0) {
355 searchResultsHeader.innerText = `No search results for '${term}'.`;
356 return;
357 }
359 currentTerm = term;
360 searchResultsHeader.innerText = `${results.length} search results for '${term}':`;
361 for (var i = 0; i < Math.min(results.length, MAX_ITEMS); i++) {
362 if (!results[i].doc.body) {
363 continue;
364 }
365 searchResultsItems.appendChild(formatSearchResultItem(results[i], term.split(" ")));
366 }
367 }, 150));
370if (document.readyState === "complete" ||
371 (document.readyState !== "loading" && !document.documentElement.doScroll)
372) {
373 initToggleSearchWindow();
374} else {
375 document.addEventListener("DOMContentLoaded", function () {
376 initSearch();
377 initHotKeys();
378 });