on d14b9ba help sign in
urbit.org/static/scripts.js
465 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 (window.location.href.includes("docs")) {
348 // tooltip behaviour for standard library page
349 tippy('.tooltip', {
350 content(reference) {
351 const title = reference.getAttribute('title')
352 reference.removeAttribute('title')
353 return title
354 },
355 animateFill: false,
356 animation: 'fade'
357 })
359 // on mobile, dropdown selections go to the option
361 let docsSelect = document.getElementById('docsSelect');
362 let goTo = function () {
363 let url = docsSelect.options[docsSelect.selectedIndex].value;
364 if (url.startsWith("http")) {
365 document.location.assign(url);
366 }
367 }
369 docsSelect.addEventListener('change', goTo);
370 // docs autoscroll to current page
371 docsNavScroll();
374var getParents = function (elem, selector) {
376 // Element.matches() polyfill
377 if (!Element.prototype.matches) {
378 Element.prototype.matches =
379 Element.prototype.matchesSelector ||
380 Element.prototype.mozMatchesSelector ||
381 Element.prototype.msMatchesSelector ||
382 Element.prototype.oMatchesSelector ||
383 Element.prototype.webkitMatchesSelector ||
384 function(s) {
385 var matches = (this.document || this.ownerDocument).querySelectorAll(s),
386 i = matches.length;
387 while (--i >= 0 && matches.item(i) !== this) {}
388 return i > -1;
389 };
390 }
392 // Set up a parent array
393 var parents = [];
395 // Push each parent element to the array
396 for ( ; elem && elem !== document; elem = elem.parentNode ) {
397 if (selector) {
398 if (elem.matches(selector)) {
399 parents.push(elem);
400 }
401 continue;
402 }
403 parents.push(elem);
404 }
406 // Return our parent array
407 return parents;
409};
414// same-page navigation on-scroll behaviour
416if (document.body.classList.contains("page-indiced") || document.getElementById("event_months")) {
417 let all = document.querySelectorAll("nav.fixed-xl li a");
419 // smooth scrolling on click
420 all.forEach(link => {
421 link.addEventListener("click", event => {
422 event.preventDefault();
423 let target = document.querySelector(event.target.hash);
424 target.scrollIntoView({
425 behavior: "smooth",
426 block: "start"
427 });
428 });
429 });
431 window.addEventListener("scroll", event => {
432 let fromTop = window.scrollY;
433 let current;
434 all.forEach(link => {
435 if (!link.hash) return;
436 let section = document.querySelector(link.hash);
437 let sectionChildren = document.querySelector(link.hash).nextElementSibling;
438 if (!sectionChildren) sectionChildren = section;
440 if (
441 ((section.offsetTop <= fromTop) ||
442 (sectionChildren.offsetTop <= fromTop)) &&
443 (section.offsetTop + section.offsetHeight + sectionChildren.offsetHeight > fromTop)
444 && !current
445 ) {
446 current = link;
447 }
448 });
449 if (current) {
450 Array.from(document.querySelectorAll('.current')).forEach(current => current.classList.remove('current'));
451 const parents = getParents(current, 'ol');
452 current.classList.add('current');
453 parents.forEach(current => current.classList.add('current'));
454 }
455 })
456};
458let oceanvid = document.getElementById("ocean");
460if ((oceanvid !== null) && (window.innerWidth > window.innerHeight)) {
461 oceanvid.innerHTML = `<source
462 src="https://media.urbit.org/site/sea30-1440.mp4"
463 type="video/mp4"/>
464 Your browser does not support the video tag.`