on 4f2cb08 help sign in
urbit.org/static/scripts.js
388 lines 11 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];
171 // last directory is in 2nd to last element of array
172 var lastPartTitle = item.doc.title;
174 var fullTitle = firstPartTitle + '<span class="gray1 dib pl2">' + ' / ' + lastPartTitle + '</span>';
176 return fullTitle;
179function formatSearchResultItem(item, terms) {
180 var li = document.createElement("li");
181 var createA = document.createElement("a");
182 li.appendChild(createA);
183 var teaserTitle = formatSearchResultTitle(item);
184 li.classList.add("search-results__item");
185 var hrefA = item.ref;
186 createA.setAttribute('href', hrefA);
187 createA.setAttribute('class','no-underline db pl1 pv2');
188 createA.innerHTML = `<span class="capitalize ph3">${teaserTitle}</span>`;
189 createA.innerHTML += `<span class='dn arrow fr'>↩</span>`;
190 createA.innerHTML += `<div class="truncate pr2 ph3">${makeTeaser(item.doc.body, terms)}</div>`;
191 return li;
194function initSearch() {
195 var searchInput = document.getElementById("search");
196 var searchForm = document.getElementById("search-form");
197 var inputReset = searchForm.nextElementSibling;
199 if (!searchInput) {
200 return;
201 }
203 var searchResults = document.querySelector(".search-results");
204 var searchResultsHeader = document.querySelector(".search-results__header");
205 var searchResultsItems = document.querySelector(".search-results__items");
206 var MAX_ITEMS = 200;
207 var options = {
208 bool: "AND",
209 expand: true, // turn on partial word search
210 fields: {
211 title: {boost: 2},
212 body: {boost: 1},
213 }
214 };
215 var currentTerm = "";
216 var index = elasticlunr.Index.load(window.searchIndex);
217 // toggle search window
218 var toggleSearchWindow = document.getElementById('js-search-window-toggle');
219 var bodyEl = document.body;
220 var searchOverlay = document.getElementById('search-overlay');
221 var searchWindow = document.getElementById('search-window');
222 var searchActive = bodyEl.classList.contains('has-active-search-window');
224 if (toggleSearchWindow !== null) {
225 toggleSearchWindow.onclick = function() {
226 inputReset.style.display="none";
228 //activate search
229 bodyEl.classList.toggle('has-active-search-window');
230 //put input in focus when activating search
231 searchInput.focus();
233 searchInput.value = "";
234 searchResultsHeader.value = "";
235 searchResults.style.display = searchInput.value.trim() === "" ? "none" : "block";
236 }
237 searchOverlay.addEventListener('click', function(e){
238 if (!searchWindow.contains(e.target)){
239 bodyEl.classList.toggle('has-active-search-window');
240 }
241 })
242 }
244 // Don't refresh the page on enter
245 searchInput.addEventListener('keydown', function(event){
246 var key = event.key || event.keyCode;
248 if (key === 13 || key === "Enter") {
249 event.preventDefault();
250 return false;
251 }
252 })
255 searchInput.addEventListener("keyup", debounce(function() {
256 inputReset.style.display="block";
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 var results = index.search(term, options).filter(function (r) {
276 return r.doc.body !== "";
277 });
279 if (results.length === 0) {
280 searchResultsHeader.innerText = `No search results for '${term}'.`;
281 return;
282 }
284 currentTerm = term;
285 searchResultsHeader.innerText = `${results.length} search results for '${term}':`;
286 for (var i = 0; i < Math.min(results.length, MAX_ITEMS); i++) {
287 if (!results[i].doc.body) {
288 continue;
289 }
290 searchResultsItems.appendChild(formatSearchResultItem(results[i], term.split(" ")));
291 }
292 }, 150));
294 // reset input button
295 inputReset.onclick=function(){
296 document.getElementById('search-form').reset();
297 }
298 searchForm.addEventListener("reset", function(event){
299 var e = document.createEvent('KeyboardEvent');
300 e.initEvent("keyup", false, true);
301 searchInput.dispatchEvent(e);
302 });
306if (document.readyState === "complete" ||
307 (document.readyState !== "loading" && !document.documentElement.doScroll)
308) {
309 initToggleSearchWindow();
310} else {
311 document.addEventListener("DOMContentLoaded", function () {
312 initSearch();
313 initHotKeys();
314 });
317if (window.location.href.includes("docs")) {
318 tippy('.tooltip', {
319 content(reference) {
320 const title = reference.getAttribute('title')
321 reference.removeAttribute('title')
322 return title
323 },
324 animateFill: false,
325 animation: 'fade'
326 })
329// same-page navigation on-scroll behaviour
331if (document.body.classList.contains("page-indiced")) {
332let h2 = document.getElementsByTagName("h2");
333let h3 = document.getElementsByTagName("h3");
334let all = document.querySelectorAll("nav details li a");
335let headers = document.querySelectorAll("details summary");
337// smooth scrolling on click
338all.forEach(link => {
339 link.addEventListener("click", event => {
340 event.preventDefault();
341 let target = document.querySelector(event.target.hash);
342 target.scrollIntoView({
343 behavior: "smooth",
344 block: "start"
345 });
346 });
347});
349let lastId;
350let cur = [];
352window.addEventListener("scroll", event => {
353 let fromTop = window.scrollY;
355 all.forEach(link => {
356 let section = document.querySelector(link.hash);
357 let sectionChildren = document.querySelector(link.hash).nextElementSibling;
359 if (
360 ((section.offsetTop <= fromTop) ||
361 (sectionChildren.offsetTop <= fromTop)) &&
362 (section.offsetTop + section.offsetHeight + sectionChildren.offsetHeight > fromTop)
363 ) {
364 link.classList.add("current");
365 } else {
366 link.classList.remove("current");
367 }
368 });
370 // this is honestly weird UX when selecting a link,
371 // as every header flies open as you scroll.
372 // for later discussion and experimentation --
373 // may just need debouncing.
374 // Also still working out the logic for closing other summary
375 // headers as you scroll.
377// headers.forEach(summary => {
378// let thisH2 = document.querySelector("h2#" + CSS.escape(summary.id));
379// if (
380// (thisH2.offsetTop <= fromTop) &&
381// (thisH2.offsetTop + thisH2.offsetHeight > fromTop)
382// ) {
383// summary.parentElement.open = true;
384// }
385// })
386//});