on 22526f1 help sign in
urbit.org/static/scripts.js
399 lines 12 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 rune of runes) {
276 if (rune.symbol === term) {
277 glossaryResults.style.display="block";
278 glossaryResultsItem.innerHTML = `
279 <a href="${rune.link}"><h3 class="black"><code class="red3 mr1">${rune.symbol}</code> ${rune.name}</h3>
280 <p class="black">${rune.desc}</p>
281 <span class="db tr black fw5" style="font-family: 'Inter UI', sans-serif;">Read more in Documentation -></span></a>
282 `
283 }
284 }
286 var results = index.search(term, options).filter(function (r) {
287 return r.doc.body !== "";
288 });
290 if (results.length === 0) {
291 searchResultsHeader.innerText = `No search results for '${term}'.`;
292 return;
293 }
295 currentTerm = term;
296 searchResultsHeader.innerText = `${results.length} search results for '${term}':`;
297 for (var i = 0; i < Math.min(results.length, MAX_ITEMS); i++) {
298 if (!results[i].doc.body) {
299 continue;
300 }
301 searchResultsItems.appendChild(formatSearchResultItem(results[i], term.split(" ")));
302 }
303 }, 150));
305 // reset input button
306 inputReset.onclick=function(){
307 document.getElementById('search-form').reset();
308 }
309 searchForm.addEventListener("reset", function(event){
310 var e = document.createEvent('KeyboardEvent');
311 e.initEvent("keyup", false, true);
312 searchInput.dispatchEvent(e);
313 });
317if (document.readyState === "complete" ||
318 (document.readyState !== "loading" && !document.documentElement.doScroll)
319) {
320 initToggleSearchWindow();
321} else {
322 document.addEventListener("DOMContentLoaded", function () {
323 initSearch();
324 initHotKeys();
325 });
328if (window.location.href.includes("docs")) {
329 tippy('.tooltip', {
330 content(reference) {
331 const title = reference.getAttribute('title')
332 reference.removeAttribute('title')
333 return title
334 },
335 animateFill: false,
336 animation: 'fade'
337 })
339 let docsSelect = document.getElementById('docsSelect');
340 let goTo = function() {
341 let url = docsSelect.options[docsSelect.selectedIndex].value;
342 if (url.startsWith("http")) {
343 document.location.assign(url);
344 }
345 }
347 docsSelect.addEventListener('change', goTo);
350// same-page navigation on-scroll behaviour
352if (document.body.classList.contains("page-indiced")) {
353let h2 = document.getElementsByTagName("h2");
354let h3 = document.getElementsByTagName("h3");
355let all = document.querySelectorAll("nav li a");
356let headers = document.querySelectorAll("details summary");
358// smooth scrolling on click
359all.forEach(link => {
360 link.addEventListener("click", event => {
361 event.preventDefault();
362 let target = document.querySelector(event.target.hash);
363 target.scrollIntoView({
364 behavior: "smooth",
365 block: "start"
366 });
367 });
368});
370let lastId;
371let cur = [];
373window.addEventListener("scroll", event => {
374 let fromTop = window.scrollY;
376 all.forEach(link => {
377 let section = document.querySelector(link.hash);
378 let sectionChildren = document.querySelector(link.hash).nextElementSibling;
380 if (
381 ((section.offsetTop <= fromTop) ||
382 (sectionChildren.offsetTop <= fromTop)) &&
383 (section.offsetTop + section.offsetHeight + sectionChildren.offsetHeight > fromTop)
384 ) {
385 link.classList.add("current");
386 } else {
387 link.classList.remove("current");
388 }
389 });
390})};
392let oceanvid = document.getElementById("ocean");
394if ((oceanvid !== null) && (window.innerWidth > window.innerHeight)) {
395 oceanvid.innerHTML = `<source
396 src="https://storage.googleapis.com/media.urbit.org/site/sea30-1440.mp4"
397 type="video/mp4"/>
398 Your browser does not support the video tag.`