on dcea09b help sign in
urbit.org/static/scripts.js
469 lines 14 kB history raw
1function initHotKeys() {
3 var bodyEl = document.body;
4 var searchInput = document.getElementById('search');
6 document.addEventListener('keydown', function (event) {
7 if (event.defaultPrevented) {
8 return;
9 }
11 var key = event.key || event.keyCode;
13 // ESC to close search window
14 if (key === 'Escape' || key === 'Esc' || key === 27) {
15 document.body.classList.remove('has-active-search-window');
16 }
18 // Ctrl or Meta + / to open toggle window
19 if (
20 (event.getModifierState("Control") || event.getModifierState("Meta")) &&
21 (key === '/' || key === 'Period' || key === 58)
22 ) {
23 if (bodyEl.classList.contains('has-active-search-window')) {
24 // if it's already open don't do anything!
25 } else {
26 event.preventDefault();
27 document.body.classList.add('has-active-search-window');
28 searchInput.focus();
29 }
30 }
32 //when search is active TAB puts search input into focus
33 if (bodyEl.classList.contains('has-active-search-window')) {
34 if (key === 'Tab' || key === 'Tab' || key === 9) {
35 searchInput.focus();
36 }
37 }
39 if (bodyEl.classList.contains('has-active-search-window')) {
40 if (key === 'Enter' || key === 'Return' || key === 13) {
41 event.preventDefault();
42 let firstresult = document.querySelectorAll("div#full-results a")[0];
43 firstresult.click();
44 }
45 }
46 });
47};
50// search functionality
51function debounce(func, wait) {
52 var timeout;
54 return function () {
55 var context = this;
56 var args = arguments;
57 clearTimeout(timeout);
59 timeout = setTimeout(function () {
60 timeout = null;
61 func.apply(context, args);
62 }, wait);
63 };
66// The strategy is as follows:
67// First, assign a value to each word in the document:
68// Words that correspond to search terms (stemmer aware): 40
69// Normal words: 2
70// First word in a sentence: 8
71// Then use a sliding window with a constant number of words and count the
72// sum of the values of the words within the window. Then use the window that got the
73// maximum sum. If there are multiple maximas, then get the last one.
74// Enclose the terms in <b>.
75function makeTeaser(body, terms) {
76 var TERM_WEIGHT = 40;
77 var NORMAL_WORD_WEIGHT = 2;
78 var FIRST_WORD_WEIGHT = 8;
79 //var TEASER_MAX_WORDS = 17;
80 var TEASER_MAX_CHARS = 63;
82 var stemmedTerms = terms.map(function (w) {
83 return elasticlunr.stemmer(w.toLowerCase());
84 });
86 var termFound = false;
87 var index = 0;
88 var weighted = []; // contains elements of ["word", weight, index_in_document]
90 // split in sentences, then words
91 var sentences = body.toLowerCase().split(". ");
93 for (var i in sentences) {
94 var words = sentences[i].split(" ");
95 var value = FIRST_WORD_WEIGHT;
97 for (var j in words) {
98 var word = words[j];
100 if (word.length > 0) {
101 for (var k in stemmedTerms) {
102 if (elasticlunr.stemmer(word).startsWith(stemmedTerms[k])) {
103 value = TERM_WEIGHT;
104 termFound = true;
105 }
106 }
107 weighted.push([word, value, index]);
108 value = NORMAL_WORD_WEIGHT;
109 }
111 index += word.length;
112 index += 1; // ' ' or '.' if last word in sentence
113 }
115 index += 1; // because we split at a two-char boundary '. '
116 }
118 if (weighted.length === 0) {
119 return body;
120 }
122 var windowWeights = [];
123 var windowSize = 0;
125 // loop over words (weighted) till max chars is reached adding a counter to windowSize every time a new word has passed
126 var sumChars = 0;
127 for (var i = 0; i < weighted.length; i++) {
128 sumChars += weighted[i][0].length;
129 if (sumChars <= TEASER_MAX_CHARS) {
130 windowSize++;
131 }
132 }
134 // We add a window with all the weights first
135 var curSum = 0;
136 for (var i = 0; i < windowSize; i++) {
137 curSum += weighted[i][1];
138 }
139 windowWeights.push(curSum);
141 for (var i = 0; i < weighted.length - windowSize; i++) {
142 curSum -= weighted[i][1];
143 curSum += weighted[i + windowSize][1];
144 windowWeights.push(curSum);
145 }
147 // If we didn't find the term, just pick the first window
148 var maxSumIndex = 0;
149 if (termFound) {
150 var maxFound = 0;
151 // backwards
152 for (var i = windowWeights.length - 1; i >= 0; i--) {
153 if (windowWeights[i] > maxFound) {
154 maxFound = windowWeights[i];
155 maxSumIndex = i;
156 }
157 }
158 }
160 var teaser = [];
161 var startIndex = weighted[maxSumIndex][2];
162 for (var i = maxSumIndex; i < maxSumIndex + windowSize; i++) {
163 var word = weighted[i];
164 if (startIndex < word[2]) {
165 // missing text from index to start of `word`
166 teaser.push(body.substring(startIndex, word[2]));
167 startIndex = word[2];
168 }
170 startIndex = word[2] + word[0].length;
171 teaser.push(body.substring(word[2], startIndex));
173 }
174 teaser.push("…");
175 return teaser.join("");
178function formatSearchResultTitle(item) {
179 var pathArray = item.ref.split('/');
181 var firstPartTitle = pathArray[3];
182 let firstTitleCapitals = firstPartTitle.charAt(0).toUpperCase() + firstPartTitle.slice(1);
184 var lastPartTitle = item.doc.title;
186 var fullTitle = firstTitleCapitals + '<span class="gray1 dib pl2">' + ' / ' + lastPartTitle + '</span>';
188 return fullTitle;
191function formatSearchResultItem(item, terms) {
192 var li = document.createElement("li");
193 var createA = document.createElement("a");
194 li.appendChild(createA);
195 var teaserTitle = formatSearchResultTitle(item);
196 li.classList.add("search-results__item");
197 var hrefA = item.ref;
198 createA.setAttribute('href', hrefA);
199 createA.setAttribute('class', 'no-underline db pl1 pv2');
200 createA.innerHTML = `<span class="capitalize ph3">${teaserTitle}</span>`;
201 createA.innerHTML += `<span class='dn arrow fr'>↩</span>`;
202 createA.innerHTML += `<div class="truncate pr2 ph3">${makeTeaser(item.doc.body, terms)}</div>`;
203 return li;
206function initSearch() {
207 var searchInput = document.getElementById("search");
208 var searchForm = document.getElementById("search-form");
209 var inputReset = searchForm.nextElementSibling;
211 if (!searchInput) {
212 return;
213 }
214 var glossaryResults = document.querySelector(".glossary-results");
215 var glossaryResultsHeader = document.querySelector(".glossary-results__header");
216 var glossaryResultsItem = document.querySelector(".glossary-results__item");
217 var searchResults = document.querySelector(".search-results");
218 var searchResultsHeader = document.querySelector(".search-results__header");
219 var searchResultsItems = document.querySelector(".search-results__items");
220 var MAX_ITEMS = 200;
221 var options = {
222 bool: "AND",
223 expand: true, // turn on partial word search
224 fields: {
225 title: { boost: 2 },
226 body: { boost: 1 },
227 }
228 };
229 var currentTerm = "";
230 var index = elasticlunr.Index.load(window.searchIndex);
231 // toggle search window
232 var toggleSearchWindow = document.getElementById('js-search-window-toggle');
233 var bodyEl = document.body;
234 var searchOverlay = document.getElementById('search-overlay');
235 var searchWindow = document.getElementById('search-window');
236 var searchActive = bodyEl.classList.contains('has-active-search-window');
239 if (toggleSearchWindow !== null) {
240 toggleSearchWindow.onclick = function () {
241 inputReset.style.display = "none";
243 //activate search
244 bodyEl.classList.toggle('has-active-search-window');
245 //put input in focus when activating search
246 searchInput.focus();
248 searchInput.value = "";
249 searchResultsHeader.value = "";
250 searchResults.style.display = searchInput.value.trim() === "" ? "none" : "block";
251 }
252 searchOverlay.addEventListener('click', function (e) {
253 if (!searchWindow.contains(e.target)) {
254 bodyEl.classList.toggle('has-active-search-window');
255 }
256 })
257 }
259 searchInput.addEventListener("keyup", debounce(function () {
260 inputReset.style.display = "block";
261 glossaryResults.style.display = "none";
262 searchResultsHeader.value = "";
263 var term = searchInput.value.trim();
264 /*
265 //removed to fix: a state where there’s a valid search term, but no results
267 if (term === currentTerm || !index) {
268 return;
269 }*/
271 searchResults.style.display = term === "" ? "none" : "block";
272 searchResults.style.overflowY = term === "" ? "hidden" : "scroll";
273 searchResultsItems.innerHTML = "";
274 if (term === "") {
275 inputReset.style.display = "none";
276 return;
277 }
279 for (let entry of glossary) {
280 if (entry.name === term.toLowerCase()) {
281 glossaryResults.style.display = "block";
282 glossaryResultsItem.innerHTML = `
283 <a href="${entry.link}"><h3 class="black">${entry.name}</h3>
284 <p class="black">${entry.desc}</p>
285 <span class="db tr black fw5 mb3" style="font-family: 'Inter UI', sans-serif;">Read more in Glossary -></span></a>
286 `
287 break;
288 } else if (entry.symbol === term) {
289 glossaryResults.style.display = "block";
290 glossaryResultsItem.innerHTML = `
291 <a href="${entry.link}"><h3 class="black"><code class="pa0 red3 mr1">${entry.symbol}</code>${entry.name}</h3>
292 <p class="black">${entry.desc}</p>
293 <span class="db tr black fw5 mb3" style="font-family: 'Inter UI', sans-serif;">Read more in Documentation -></span></a>
294 `
295 }
296 }
298 var results = index.search(term, options).filter(function (r) {
299 return r.doc.body !== "";
300 });
302 if (results.length === 0) {
303 searchResultsHeader.innerText = `No search results for '${term}'.`;
304 return;
305 }
307 currentTerm = term;
308 searchResultsHeader.innerText = `${results.length} search results for '${term}':`;
309 for (var i = 0; i < Math.min(results.length, MAX_ITEMS); i++) {
310 if (!results[i].doc.body) {
311 continue;
312 }
313 searchResultsItems.appendChild(formatSearchResultItem(results[i], term.split(" ")));
314 }
315 }, 150));
317 // reset input button
318 inputReset.onclick = function () {
319 document.getElementById('search-form').reset();
320 }
321 searchForm.addEventListener("reset", function (event) {
322 var e = document.createEvent('KeyboardEvent');
323 e.initEvent("keyup", false, true);
324 searchInput.dispatchEvent(e);
325 });
329if (document.readyState === "complete" ||
330 (document.readyState !== "loading" && !document.documentElement.doScroll)
331) {
332} else {
333 document.addEventListener("DOMContentLoaded", function () {
334 initSearch();
335 initHotKeys();
336 });
339// Scroll to current document in nav list.
340let docsNavScroll = function () {
341 let docsDetails = document.querySelectorAll("nav ul details")
342 for (let details in docsDetails) {
343 if (docsDetails[details].open) docsDetails[details].scrollIntoView()
344 }
347if (document.body.classList.contains("index")) {
348 tippy('.tooltip', {
349 content(reference) {
350 const title = reference.getAttribute('title')
351 reference.removeAttribute('title')
352 return title
353 },
354 animateFill: false,
355 animation: 'fade',
356 placement: 'bottom'
357 })
360if (window.location.href.includes("docs")) {
361 // tooltip behaviour for standard library page
362 tippy('.tooltip', {
363 content(reference) {
364 const title = reference.getAttribute('title')
365 reference.removeAttribute('title')
366 return title
367 },
368 animateFill: false,
369 animation: 'fade'
370 })
372 // on mobile, dropdown selections go to the option
374 let docsSelect = document.getElementById('docsSelect');
375 let goTo = function () {
376 let url = docsSelect.options[docsSelect.selectedIndex].value;
377 if (url.startsWith("http")) {
378 document.location.assign(url);
379 }
380 }
382 docsSelect.addEventListener('change', goTo);
383 // docs autoscroll to current page
384 docsNavScroll();
387var getParents = function (elem, selector) {
389 // Element.matches() polyfill
390 if (!Element.prototype.matches) {
391 Element.prototype.matches =
392 Element.prototype.matchesSelector ||
393 Element.prototype.mozMatchesSelector ||
394 Element.prototype.msMatchesSelector ||
395 Element.prototype.oMatchesSelector ||
396 Element.prototype.webkitMatchesSelector ||
397 function(s) {
398 var matches = (this.document || this.ownerDocument).querySelectorAll(s),
399 i = matches.length;
400 while (--i >= 0 && matches.item(i) !== this) {}
401 return i > -1;
402 };
403 }
405 // Set up a parent array
406 var parents = [];
408 // Push each parent element to the array
409 for ( ; elem && elem !== document; elem = elem.parentNode ) {
410 if (selector) {
411 if (elem.matches(selector)) {
412 parents.push(elem);
413 }
414 continue;
415 }
416 parents.push(elem);
417 }
419 // Return our parent array
420 return parents;
422};
427// same-page navigation on-scroll behaviour
429if (document.body.classList.contains("page-indiced") || document.getElementById("event_months")) {
430 let all = document.querySelectorAll("nav.fixed-xl li a");
432 // smooth scrolling on click
433 all.forEach(link => {
434 link.addEventListener("click", event => {
435 event.preventDefault();
436 let target = document.querySelector(event.target.hash);
437 target.scrollIntoView({
438 behavior: "smooth",
439 block: "start"
440 });
441 });
442 });
444 window.addEventListener("scroll", event => {
445 let fromTop = window.scrollY;
446 let current;
447 all.forEach(link => {
448 if (!link.hash) return;
449 let section = document.querySelector(link.hash);
450 let sectionChildren = document.querySelector(link.hash).nextElementSibling;
451 if (!sectionChildren) sectionChildren = section;
453 if (
454 ((section.offsetTop <= fromTop) ||
455 (sectionChildren.offsetTop <= fromTop)) &&
456 (section.offsetTop + section.offsetHeight + sectionChildren.offsetHeight > fromTop)
457 && !current
458 ) {
459 current = link;
460 }
461 });
462 if (current) {
463 Array.from(document.querySelectorAll('.current')).forEach(current => current.classList.remove('current'));
464 const parents = getParents(current, 'ol');
465 current.classList.add('current');
466 parents.forEach(current => current.classList.add('current'));
467 }
468 })
469};