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