on 3c7e908 help sign in
urbit.org/static/scripts.js
411 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 // first directory is in 4th element of split path array
169 var firstPartTitle = pathArray[3];
170 let firstTitleCapitals = firstPartTitle.charAt(0).toUpperCase() + firstPartTitle.slice(1);
172 // last directory is in 2nd to last element of array
173 var lastPartTitle = item.doc.title;
175 var fullTitle = firstTitleCapitals + '<span class="gray1 dib pl2">' + ' / ' + lastPartTitle + '</span>';
177 return fullTitle;
180function formatSearchResultItem(item, terms) {
181 var li = document.createElement("li");
182 var createA = document.createElement("a");
183 li.appendChild(createA);
184 var teaserTitle = formatSearchResultTitle(item);
185 li.classList.add("search-results__item");
186 var hrefA = item.ref;
187 createA.setAttribute('href', hrefA);
188 createA.setAttribute('class','no-underline db pl1 pv2');
189 createA.innerHTML = `<span class="capitalize ph3">${teaserTitle}</span>`;
190 createA.innerHTML += `<span class='dn arrow fr'>↩</span>`;
191 createA.innerHTML += `<div class="truncate pr2 ph3">${makeTeaser(item.doc.body, terms)}</div>`;
192 return li;
195function initSearch() {
196 var searchInput = document.getElementById("search");
197 var searchForm = document.getElementById("search-form");
198 var inputReset = searchForm.nextElementSibling;
200 if (!searchInput) {
201 return;
202 }
203 var glossaryResults = document.querySelector(".glossary-results");
204 var glossaryResultsHeader = document.querySelector(".glossary-results__header");
205 var glossaryResultsItem = document.querySelector(".glossary-results__item");
206 var searchResults = document.querySelector(".search-results");
207 var searchResultsHeader = document.querySelector(".search-results__header");
208 var searchResultsItems = document.querySelector(".search-results__items");
209 var MAX_ITEMS = 200;
210 var options = {
211 bool: "AND",
212 expand: true, // turn on partial word search
213 fields: {
214 title: {boost: 2},
215 body: {boost: 1},
216 }
217 };
218 var currentTerm = "";
219 var index = elasticlunr.Index.load(window.searchIndex);
220 // toggle search window
221 var toggleSearchWindow = document.getElementById('js-search-window-toggle');
222 var bodyEl = document.body;
223 var searchOverlay = document.getElementById('search-overlay');
224 var searchWindow = document.getElementById('search-window');
225 var searchActive = bodyEl.classList.contains('has-active-search-window');
227 if (toggleSearchWindow !== null) {
228 toggleSearchWindow.onclick = function() {
229 inputReset.style.display="none";
231 //activate search
232 bodyEl.classList.toggle('has-active-search-window');
233 //put input in focus when activating search
234 searchInput.focus();
236 searchInput.value = "";
237 searchResultsHeader.value = "";
238 searchResults.style.display = searchInput.value.trim() === "" ? "none" : "block";
239 }
240 searchOverlay.addEventListener('click', function(e){
241 if (!searchWindow.contains(e.target)){
242 bodyEl.classList.toggle('has-active-search-window');
243 }
244 })
245 }
247 // Don't refresh the page on enter
248 searchInput.addEventListener('keydown', function(event){
249 var key = event.key || event.keyCode;
251 if (key === 13 || key === "Enter") {
252 event.preventDefault();
253 return false;
254 }
255 })
258 searchInput.addEventListener("keyup", debounce(function() {
259 inputReset.style.display="block";
260 glossaryResults.style.display="none";
261 searchResultsHeader.value = "";
262 var term = searchInput.value.trim();
263 /*
264 //removed to fix: a state where there’s a valid search term, but no results
266 if (term === currentTerm || !index) {
267 return;
268 }*/
270 searchResults.style.display = term === "" ? "none" : "block";
271 searchResults.style.overflowY = term === "" ? "hidden" : "scroll";
272 searchResultsItems.innerHTML = "";
273 if (term === "") {
274 inputReset.style.display="none";
275 return;
276 }
278 for (let rune of runes) {
279 if (rune.symbol === term) {
280 glossaryResults.style.display="block";
281 glossaryResultsItem.innerHTML = `
282 <h3 class="black"><code class="red3 mr1">${rune.symbol}</code> ${rune.name}</h3>
283 <p class="black">${rune.desc}</p>
284 <a href="${rune.link}" class="db tr black fw5" style="font-family: 'Inter UI', sans-serif;">Read more in Documentation -></a>
285 `
286 }
287 }
289 var results = index.search(term, options).filter(function (r) {
290 return r.doc.body !== "";
291 });
293 if (results.length === 0) {
294 searchResultsHeader.innerText = `No search results for '${term}'.`;
295 return;
296 }
298 currentTerm = term;
299 searchResultsHeader.innerText = `${results.length} search results for '${term}':`;
300 for (var i = 0; i < Math.min(results.length, MAX_ITEMS); i++) {
301 if (!results[i].doc.body) {
302 continue;
303 }
304 searchResultsItems.appendChild(formatSearchResultItem(results[i], term.split(" ")));
305 }
306 }, 150));
308 // reset input button
309 inputReset.onclick=function(){
310 document.getElementById('search-form').reset();
311 }
312 searchForm.addEventListener("reset", function(event){
313 var e = document.createEvent('KeyboardEvent');
314 e.initEvent("keyup", false, true);
315 searchInput.dispatchEvent(e);
316 });
320if (document.readyState === "complete" ||
321 (document.readyState !== "loading" && !document.documentElement.doScroll)
322) {
323 initToggleSearchWindow();
324} else {
325 document.addEventListener("DOMContentLoaded", function () {
326 initSearch();
327 initHotKeys();
328 });
331if (window.location.href.includes("docs")) {
332 tippy('.tooltip', {
333 content(reference) {
334 const title = reference.getAttribute('title')
335 reference.removeAttribute('title')
336 return title
337 },
338 animateFill: false,
339 animation: 'fade'
340 })
342 let docsSelect = document.getElementById('docsSelect');
343 let goTo = function() {
344 let url = docsSelect.options[docsSelect.selectedIndex].value;
345 if (url.startsWith("http")) {
346 document.location.assign(url);
347 }
348 }
350 docsSelect.addEventListener('change', goTo);
353// same-page navigation on-scroll behaviour
355if (document.body.classList.contains("page-indiced")) {
356let h2 = document.getElementsByTagName("h2");
357let h3 = document.getElementsByTagName("h3");
358let all = document.querySelectorAll("nav li a");
359let headers = document.querySelectorAll("details summary");
361// smooth scrolling on click
362all.forEach(link => {
363 link.addEventListener("click", event => {
364 event.preventDefault();
365 let target = document.querySelector(event.target.hash);
366 target.scrollIntoView({
367 behavior: "smooth",
368 block: "start"
369 });
370 });
371});
373let lastId;
374let cur = [];
376window.addEventListener("scroll", event => {
377 let fromTop = window.scrollY;
379 all.forEach(link => {
380 let section = document.querySelector(link.hash);
381 let sectionChildren = document.querySelector(link.hash).nextElementSibling;
383 if (
384 ((section.offsetTop <= fromTop) ||
385 (sectionChildren.offsetTop <= fromTop)) &&
386 (section.offsetTop + section.offsetHeight + sectionChildren.offsetHeight > fromTop)
387 ) {
388 link.classList.add("current");
389 } else {
390 link.classList.remove("current");
391 }
392 });
394 // this is honestly weird UX when selecting a link,
395 // as every header flies open as you scroll.
396 // for later discussion and experimentation --
397 // may just need debouncing.
398 // Also still working out the logic for closing other summary
399 // headers as you scroll.
401// headers.forEach(summary => {
402// let thisH2 = document.querySelector("h2#" + CSS.escape(summary.id));
403// if (
404// (thisH2.offsetTop <= fromTop) &&
405// (thisH2.offsetTop + thisH2.offsetHeight > fromTop)
406// ) {
407// summary.parentElement.open = true;
408// }
409// })
410//
411})};