on 0070a9c help sign in
urbit.org/static/scripts.js
419 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.symbol === term) {
277 glossaryResults.style.display="block";
278 glossaryResultsItem.innerHTML = `
279 <a href="${entry.link}"><h3 class="black"><code class="pa0 red3 mr1">${entry.symbol}</code>${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 Documentation -></span></a>
282 `
283 } else if (entry.name === term.toLowerCase()) {
284 glossaryResults.style.display="block";
285 glossaryResultsItem.innerHTML = `
286 <a href="${entry.link}"><h3 class="black">${entry.name}</h3>
287 <p class="black">${entry.desc}</p>
288 <span class="db tr black fw5 mb3" style="font-family: 'Inter UI', sans-serif;">Read more in Glossary -></span></a>
289 `
290 }
291 }
293 var results = index.search(term, options).filter(function (r) {
294 return r.doc.body !== "";
295 });
297 if (results.length === 0) {
298 searchResultsHeader.innerText = `No search results for '${term}'.`;
299 return;
300 }
302 currentTerm = term;
303 searchResultsHeader.innerText = `${results.length} search results for '${term}':`;
304 for (var i = 0; i < Math.min(results.length, MAX_ITEMS); i++) {
305 if (!results[i].doc.body) {
306 continue;
307 }
308 searchResultsItems.appendChild(formatSearchResultItem(results[i], term.split(" ")));
309 }
310 }, 150));
312 // reset input button
313 inputReset.onclick=function(){
314 document.getElementById('search-form').reset();
315 }
316 searchForm.addEventListener("reset", function(event){
317 var e = document.createEvent('KeyboardEvent');
318 e.initEvent("keyup", false, true);
319 searchInput.dispatchEvent(e);
320 });
324if (document.readyState === "complete" ||
325 (document.readyState !== "loading" && !document.documentElement.doScroll)
326) {
327 initToggleSearchWindow();
328} else {
329 document.addEventListener("DOMContentLoaded", function () {
330 initSearch();
331 initHotKeys();
332 });
335// Scroll to current document in nav list.
336let docsNavScroll = function() {
337 let docsDetails = document.querySelectorAll("nav ul details")
338 for (let details in docsDetails) {
339 if (docsDetails[details].open) docsDetails[details].scrollIntoView()
340 }
343if (window.location.href.includes("docs")) {
344 // tooltip behaviour for standard library page
345 tippy('.tooltip', {
346 content(reference) {
347 const title = reference.getAttribute('title')
348 reference.removeAttribute('title')
349 return title
350 },
351 animateFill: false,
352 animation: 'fade'
353 })
355 // on mobile, dropdown selections go to the option
357 let docsSelect = document.getElementById('docsSelect');
358 let goTo = function() {
359 let url = docsSelect.options[docsSelect.selectedIndex].value;
360 if (url.startsWith("http")) {
361 document.location.assign(url);
362 }
363 }
365 docsSelect.addEventListener('change', goTo);
366 // docs autoscroll to current page
367 docsNavScroll();
370// same-page navigation on-scroll behaviour
372if (document.body.classList.contains("page-indiced")) {
373let h2 = document.getElementsByTagName("h2");
374let h3 = document.getElementsByTagName("h3");
375let all = document.querySelectorAll("nav li a");
376let headers = document.querySelectorAll("details summary");
378// smooth scrolling on click
379all.forEach(link => {
380 link.addEventListener("click", event => {
381 event.preventDefault();
382 let target = document.querySelector(event.target.hash);
383 target.scrollIntoView({
384 behavior: "smooth",
385 block: "start"
386 });
387 });
388});
390let lastId;
391let cur = [];
393window.addEventListener("scroll", event => {
394 let fromTop = window.scrollY;
396 all.forEach(link => {
397 let section = document.querySelector(link.hash);
398 let sectionChildren = document.querySelector(link.hash).nextElementSibling;
400 if (
401 ((section.offsetTop <= fromTop) ||
402 (sectionChildren.offsetTop <= fromTop)) &&
403 (section.offsetTop + section.offsetHeight + sectionChildren.offsetHeight > fromTop)
404 ) {
405 link.classList.add("current");
406 } else {
407 link.classList.remove("current");
408 }
409 });
410})};
412let oceanvid = document.getElementById("ocean");
414if ((oceanvid !== null) && (window.innerWidth > window.innerHeight)) {
415 oceanvid.innerHTML = `<source
416 src="https://storage.googleapis.com/media.urbit.org/site/sea30-1440.mp4"
417 type="video/mp4"/>
418 Your browser does not support the video tag.`