on 8cb1066 help sign in
urbit.org/static/scripts.js
421 lines 13 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 // / to open toggle window
19 if (key === '/' || key === 'Period' || key === 58) {
20 if (bodyEl.classList.contains('has-active-search-window')) {
21 // if it's already open don't do anything!
22 } else {
23 event.preventDefault();
24 document.body.classList.add('has-active-search-window');
25 searchInput.focus();
26 }
27 }
29 //when search is active TAB puts search input into focus
30 if (bodyEl.classList.contains('has-active-search-window')) {
31 if (key === 'Tab' || key === 'Tab' || key === 9) {
32 searchInput.focus();
33 }
34 }
36 if (bodyEl.classList.contains('has-active-search-window')) {
37 if (key === 'Enter' || key === 'Return' || key === 13) {
38 event.preventDefault();
39 let firstresult = document.querySelectorAll("div#full-results a")[0];
40 firstresult.click();
41 }
42 }
43 });
44};
47// search functionality
48function debounce(func, wait) {
49 var timeout;
51 return function () {
52 var context = this;
53 var args = arguments;
54 clearTimeout(timeout);
56 timeout = setTimeout(function () {
57 timeout = null;
58 func.apply(context, args);
59 }, wait);
60 };
63// The strategy is as follows:
64// First, assign a value to each word in the document:
65// Words that correspond to search terms (stemmer aware): 40
66// Normal words: 2
67// First word in a sentence: 8
68// Then use a sliding window with a constant number of words and count the
69// sum of the values of the words within the window. Then use the window that got the
70// maximum sum. If there are multiple maximas, then get the last one.
71// Enclose the terms in <b>.
72function makeTeaser(body, terms) {
73 var TERM_WEIGHT = 40;
74 var NORMAL_WORD_WEIGHT = 2;
75 var FIRST_WORD_WEIGHT = 8;
76 //var TEASER_MAX_WORDS = 17;
77 var TEASER_MAX_CHARS = 63;
79 var stemmedTerms = terms.map(function (w) {
80 return elasticlunr.stemmer(w.toLowerCase());
81 });
83 var termFound = false;
84 var index = 0;
85 var weighted = []; // contains elements of ["word", weight, index_in_document]
87 // split in sentences, then words
88 var sentences = body.toLowerCase().split(". ");
90 for (var i in sentences) {
91 var words = sentences[i].split(" ");
92 var value = FIRST_WORD_WEIGHT;
94 for (var j in words) {
95 var word = words[j];
97 if (word.length > 0) {
98 for (var k in stemmedTerms) {
99 if (elasticlunr.stemmer(word).startsWith(stemmedTerms[k])) {
100 value = TERM_WEIGHT;
101 termFound = true;
102 }
103 }
104 weighted.push([word, value, index]);
105 value = NORMAL_WORD_WEIGHT;
106 }
108 index += word.length;
109 index += 1; // ' ' or '.' if last word in sentence
110 }
112 index += 1; // because we split at a two-char boundary '. '
113 }
115 if (weighted.length === 0) {
116 return body;
117 }
119 var windowWeights = [];
120 var windowSize = 0;
122 // loop over words (weighted) till max chars is reached adding a counter to windowSize every time a new word has passed
123 var sumChars = 0;
124 for (var i = 0; i < weighted.length; i++) {
125 sumChars += weighted[i][0].length;
126 if (sumChars <= TEASER_MAX_CHARS) {
127 windowSize++;
128 }
129 }
131 // We add a window with all the weights first
132 var curSum = 0;
133 for (var i = 0; i < windowSize; i++) {
134 curSum += weighted[i][1];
135 }
136 windowWeights.push(curSum);
138 for (var i = 0; i < weighted.length - windowSize; i++) {
139 curSum -= weighted[i][1];
140 curSum += weighted[i + windowSize][1];
141 windowWeights.push(curSum);
142 }
144 // If we didn't find the term, just pick the first window
145 var maxSumIndex = 0;
146 if (termFound) {
147 var maxFound = 0;
148 // backwards
149 for (var i = windowWeights.length - 1; i >= 0; i--) {
150 if (windowWeights[i] > maxFound) {
151 maxFound = windowWeights[i];
152 maxSumIndex = i;
153 }
154 }
155 }
157 var teaser = [];
158 var startIndex = weighted[maxSumIndex][2];
159 for (var i = maxSumIndex; i < maxSumIndex + windowSize; i++) {
160 var word = weighted[i];
161 if (startIndex < word[2]) {
162 // missing text from index to start of `word`
163 teaser.push(body.substring(startIndex, word[2]));
164 startIndex = word[2];
165 }
167 startIndex = word[2] + word[0].length;
168 teaser.push(body.substring(word[2], startIndex));
170 }
171 teaser.push("…");
172 return teaser.join("");
175function formatSearchResultTitle(item) {
176 var pathArray = item.ref.split('/');
178 var firstPartTitle = pathArray[3];
179 let firstTitleCapitals = firstPartTitle.charAt(0).toUpperCase() + firstPartTitle.slice(1);
181 var lastPartTitle = item.doc.title;
183 var fullTitle = firstTitleCapitals + '<span class="gray1 dib pl2">' + ' / ' + lastPartTitle + '</span>';
185 return fullTitle;
188function formatSearchResultItem(item, terms) {
189 var li = document.createElement("li");
190 var createA = document.createElement("a");
191 li.appendChild(createA);
192 var teaserTitle = formatSearchResultTitle(item);
193 li.classList.add("search-results__item");
194 var hrefA = item.ref;
195 createA.setAttribute('href', hrefA);
196 createA.setAttribute('class', 'no-underline db pl1 pv2');
197 createA.innerHTML = `<span class="capitalize ph3">${teaserTitle}</span>`;
198 createA.innerHTML += `<span class='dn arrow fr'>↩</span>`;
199 createA.innerHTML += `<div class="truncate pr2 ph3">${makeTeaser(item.doc.body, terms)}</div>`;
200 return li;
203function initSearch() {
204 var searchInput = document.getElementById("search");
205 var searchForm = document.getElementById("search-form");
206 var inputReset = searchForm.nextElementSibling;
208 if (!searchInput) {
209 return;
210 }
211 var glossaryResults = document.querySelector(".glossary-results");
212 var glossaryResultsHeader = document.querySelector(".glossary-results__header");
213 var glossaryResultsItem = document.querySelector(".glossary-results__item");
214 var searchResults = document.querySelector(".search-results");
215 var searchResultsHeader = document.querySelector(".search-results__header");
216 var searchResultsItems = document.querySelector(".search-results__items");
217 var MAX_ITEMS = 200;
218 var options = {
219 bool: "AND",
220 expand: true, // turn on partial word search
221 fields: {
222 title: { boost: 2 },
223 body: { boost: 1 },
224 }
225 };
226 var currentTerm = "";
227 var index = elasticlunr.Index.load(window.searchIndex);
228 // toggle search window
229 var toggleSearchWindow = document.getElementById('js-search-window-toggle');
230 var bodyEl = document.body;
231 var searchOverlay = document.getElementById('search-overlay');
232 var searchWindow = document.getElementById('search-window');
233 var searchActive = bodyEl.classList.contains('has-active-search-window');
235 if (toggleSearchWindow !== null) {
236 toggleSearchWindow.onclick = function () {
237 inputReset.style.display = "none";
239 //activate search
240 bodyEl.classList.toggle('has-active-search-window');
241 //put input in focus when activating search
242 searchInput.focus();
244 searchInput.value = "";
245 searchResultsHeader.value = "";
246 searchResults.style.display = searchInput.value.trim() === "" ? "none" : "block";
247 }
248 searchOverlay.addEventListener('click', function (e) {
249 if (!searchWindow.contains(e.target)) {
250 bodyEl.classList.toggle('has-active-search-window');
251 }
252 })
253 }
255 searchInput.addEventListener("keyup", debounce(function () {
256 inputReset.style.display = "block";
257 glossaryResults.style.display = "none";
258 searchResultsHeader.value = "";
259 var term = searchInput.value.trim();
260 /*
261 //removed to fix: a state where there’s a valid search term, but no results
263 if (term === currentTerm || !index) {
264 return;
265 }*/
267 searchResults.style.display = term === "" ? "none" : "block";
268 searchResults.style.overflowY = term === "" ? "hidden" : "scroll";
269 searchResultsItems.innerHTML = "";
270 if (term === "") {
271 inputReset.style.display = "none";
272 return;
273 }
275 for (let entry of glossary) {
276 if (entry.name === term.toLowerCase()) {
277 glossaryResults.style.display = "block";
278 glossaryResultsItem.innerHTML = `
279 <a href="${entry.link}"><h3 class="black">${entry.name}</h3>
280 <p class="black">${entry.desc}</p>
281 <span class="db tr black fw5 mb3" style="font-family: 'Inter UI', sans-serif;">Read more in Glossary -></span></a>
282 `
283 break;
284 } else if (entry.symbol === term) {
285 glossaryResults.style.display = "block";
286 glossaryResultsItem.innerHTML = `
287 <a href="${entry.link}"><h3 class="black"><code class="pa0 red3 mr1">${entry.symbol}</code>${entry.name}</h3>
288 <p class="black">${entry.desc}</p>
289 <span class="db tr black fw5 mb3" style="font-family: 'Inter UI', sans-serif;">Read more in Documentation -></span></a>
290 `
291 }
292 }
294 var results = index.search(term, options).filter(function (r) {
295 return r.doc.body !== "";
296 });
298 if (results.length === 0) {
299 searchResultsHeader.innerText = `No search results for '${term}'.`;
300 return;
301 }
303 currentTerm = term;
304 searchResultsHeader.innerText = `${results.length} search results for '${term}':`;
305 for (var i = 0; i < Math.min(results.length, MAX_ITEMS); i++) {
306 if (!results[i].doc.body) {
307 continue;
308 }
309 searchResultsItems.appendChild(formatSearchResultItem(results[i], term.split(" ")));
310 }
311 }, 150));
313 // reset input button
314 inputReset.onclick = function () {
315 document.getElementById('search-form').reset();
316 }
317 searchForm.addEventListener("reset", function (event) {
318 var e = document.createEvent('KeyboardEvent');
319 e.initEvent("keyup", false, true);
320 searchInput.dispatchEvent(e);
321 });
325if (document.readyState === "complete" ||
326 (document.readyState !== "loading" && !document.documentElement.doScroll)
327) {
328 initToggleSearchWindow();
329} else {
330 document.addEventListener("DOMContentLoaded", function () {
331 initSearch();
332 initHotKeys();
333 });
336// Scroll to current document in nav list.
337let docsNavScroll = function () {
338 let docsDetails = document.querySelectorAll("nav ul details")
339 for (let details in docsDetails) {
340 if (docsDetails[details].open) docsDetails[details].scrollIntoView()
341 }
344if (window.location.href.includes("docs")) {
345 // tooltip behaviour for standard library page
346 tippy('.tooltip', {
347 content(reference) {
348 const title = reference.getAttribute('title')
349 reference.removeAttribute('title')
350 return title
351 },
352 animateFill: false,
353 animation: 'fade'
354 })
356 // on mobile, dropdown selections go to the option
358 let docsSelect = document.getElementById('docsSelect');
359 let goTo = function () {
360 let url = docsSelect.options[docsSelect.selectedIndex].value;
361 if (url.startsWith("http")) {
362 document.location.assign(url);
363 }
364 }
366 docsSelect.addEventListener('change', goTo);
367 // docs autoscroll to current page
368 docsNavScroll();
371// same-page navigation on-scroll behaviour
373if (document.body.classList.contains("page-indiced")) {
374 let h2 = document.getElementsByTagName("h2");
375 let h3 = document.getElementsByTagName("h3");
376 let all = document.querySelectorAll("nav li a");
377 let headers = document.querySelectorAll("details summary");
379 // smooth scrolling on click
380 all.forEach(link => {
381 link.addEventListener("click", event => {
382 event.preventDefault();
383 let target = document.querySelector(event.target.hash);
384 target.scrollIntoView({
385 behavior: "smooth",
386 block: "start"
387 });
388 });
389 });
391 let lastId;
392 let cur = [];
394 window.addEventListener("scroll", event => {
395 let fromTop = window.scrollY;
397 all.forEach(link => {
398 let section = document.querySelector(link.hash);
399 let sectionChildren = document.querySelector(link.hash).nextElementSibling;
401 if (
402 ((section.offsetTop <= fromTop) ||
403 (sectionChildren.offsetTop <= fromTop)) &&
404 (section.offsetTop + section.offsetHeight + sectionChildren.offsetHeight > fromTop)
405 ) {
406 link.classList.add("current");
407 } else {
408 link.classList.remove("current");
409 }
410 });
411 })
412};
414let oceanvid = document.getElementById("ocean");
416if ((oceanvid !== null) && (window.innerWidth > window.innerHeight)) {
417 oceanvid.innerHTML = `<source
418 src="https://storage.googleapis.com/media.urbit.org/site/sea30-1440.mp4"
419 type="video/mp4"/>
420 Your browser does not support the video tag.`