on ffbd692 help sign in
urbit.org/static/scripts.js
354 lines 10 kB history raw
1// toggling of navigation menus
2var toggleMainNav = document.getElementById('js-main-nav-toggle');
3if (toggleMainNav !== null) {
4 toggleMainNav.onclick = function() {
5 document.body.classList.toggle('has-active-main-nav');
6 }
7}
9var toggleContentNav = document.getElementById('js-content-nav-toggle');
10if (toggleContentNav !== null) {
11 toggleContentNav.onclick = function() {
12 document.body.classList.toggle('has-active-content-nav');
13 }
16function initHotKeys() {
18 var bodyEl = document.body;
19 var searchInput = document.getElementById('search');
21 document.addEventListener('keydown', function (event) {
22 if (event.defaultPrevented) {
23 return;
24 }
26 var key = event.key || event.keyCode;
28 // ESC to close search window
29 if (key === 'Escape' || key === 'Esc' || key === 27) {
30 document.body.classList.remove('has-active-search-window');
31 }
33 // / to close toggle window
34 if (key === '/' || key === 'Period' || key === 58) {
35 event.preventDefault();
36 document.body.classList.toggle('has-active-search-window');
37 if (bodyEl.classList.contains('has-active-search-window')) {
38 searchInput.focus();
39 }
40 }
42 //when search is active TAB puts search input into focus
43 if (bodyEl.classList.contains('has-active-search-window')) {
44 if (key === 'Tab' || key === 'Tab' || key === 9) {
45 searchInput.focus();
46 }
47 }
48 });
49};
52// search functionality
53function debounce(func, wait) {
54 var timeout;
56 return function () {
57 var context = this;
58 var args = arguments;
59 clearTimeout(timeout);
61 timeout = setTimeout(function () {
62 timeout = null;
63 func.apply(context, args);
64 }, wait);
65 };
68// The strategy is as follows:
69// First, assign a value to each word in the document:
70// Words that correspond to search terms (stemmer aware): 40
71// Normal words: 2
72// First word in a sentence: 8
73// Then use a sliding window with a constant number of words and count the
74// sum of the values of the words within the window. Then use the window that got the
75// maximum sum. If there are multiple maximas, then get the last one.
76// Enclose the terms in <b>.
77function makeTeaser(body, terms) {
78 var TERM_WEIGHT = 40;
79 var NORMAL_WORD_WEIGHT = 2;
80 var FIRST_WORD_WEIGHT = 8;
81 //var TEASER_MAX_WORDS = 17;
82 var TEASER_MAX_CHARS = 63;
84 var stemmedTerms = terms.map(function (w) {
85 return elasticlunr.stemmer(w.toLowerCase());
86 });
88 var termFound = false;
89 var index = 0;
90 var weighted = []; // contains elements of ["word", weight, index_in_document]
92 // split in sentences, then words
93 var sentences = body.toLowerCase().split(". ");
95 for (var i in sentences) {
96 var words = sentences[i].split(" ");
97 var value = FIRST_WORD_WEIGHT;
99 for (var j in words) {
100 var word = words[j];
102 if (word.length > 0) {
103 for (var k in stemmedTerms) {
104 if (elasticlunr.stemmer(word).startsWith(stemmedTerms[k])) {
105 value = TERM_WEIGHT;
106 termFound = true;
107 }
108 }
109 weighted.push([word, value, index]);
110 value = NORMAL_WORD_WEIGHT;
111 }
113 index += word.length;
114 index += 1; // ' ' or '.' if last word in sentence
115 }
117 index += 1; // because we split at a two-char boundary '. '
118 }
120 if (weighted.length === 0) {
121 return body;
122 }
124 var windowWeights = [];
125 var windowSize = 0;
127 // loop over words (weighted) till max chars is reached adding a counter to windowSize every time a new word has passed
128 var sumChars = 0;
129 for (var i = 0; i < weighted.length; i++) {
130 sumChars += weighted[i][0].length;
131 if (sumChars <= TEASER_MAX_CHARS) {
132 windowSize++;
133 }
134 }
136 // We add a window with all the weights first
137 var curSum = 0;
138 for (var i = 0; i < windowSize; i++) {
139 curSum += weighted[i][1];
140 }
141 windowWeights.push(curSum);
143 for (var i = 0; i < weighted.length - windowSize; i++) {
144 curSum -= weighted[i][1];
145 curSum += weighted[i + windowSize][1];
146 windowWeights.push(curSum);
147 }
149 // If we didn't find the term, just pick the first window
150 var maxSumIndex = 0;
151 if (termFound) {
152 var maxFound = 0;
153 // backwards
154 for (var i = windowWeights.length - 1; i >= 0; i--) {
155 if (windowWeights[i] > maxFound) {
156 maxFound = windowWeights[i];
157 maxSumIndex = i;
158 }
159 }
160 }
162 var teaser = [];
163 var startIndex = weighted[maxSumIndex][2];
164 for (var i = maxSumIndex; i < maxSumIndex + windowSize; i++) {
165 var word = weighted[i];
166 if (startIndex < word[2]) {
167 // missing text from index to start of `word`
168 teaser.push(body.substring(startIndex, word[2]));
169 startIndex = word[2];
170 }
172 startIndex = word[2] + word[0].length;
173 teaser.push(body.substring(word[2], startIndex));
175 }
176 teaser.push("…");
177 return teaser.join("");
180function formatSearchResultTitle(item) {
181 var pathArray = item.ref.split( '/' );
183 // first directory is in 4th element of split path array
184 var firstPartTitle = pathArray[3];
186 // last directory is in 2nd to last element of array
187 var lastPartTitle = item.doc.title;
189 var fullTitle = firstPartTitle + '<span class="gray90 inline-block pl2">' + ' / ' + lastPartTitle + '</span>';
191 return fullTitle;
194function formatSearchResultItem(item, terms) {
195 var li = document.createElement("li");
196 var createA = document.createElement("a");
197 li.appendChild(createA);
198 var teaserTitle = formatSearchResultTitle(item);
199 li.classList.add("search-results__item");
200 li.classList.add("ph3");
201 var hrefA = item.ref;
202 createA.setAttribute('href', hrefA);
203 createA.setAttribute('class','no-underline block pl6 pv3');
204 createA.innerHTML = `<span class="fs45 capitalize">${teaserTitle}</span>`;
205 createA.innerHTML += `<span class='pr7 fs5 none float-right'>→</span>`;
206 createA.innerHTML += `<div class="fs35 truncate mr10">${makeTeaser(item.doc.body, terms)}</div>`;
207 return li;
210function initSearch() {
211 var searchInput = document.getElementById("search");
212 var searchForm = document.getElementById("search-form");
213 var inputReset = searchForm.nextElementSibling;
215 if (!searchInput) {
216 return;
217 }
219 var searchResults = document.querySelector(".search-results");
220 var searchResultsHeader = document.querySelector(".search-results__header");
221 var searchResultsItems = document.querySelector(".search-results__items");
222 var MAX_ITEMS = 200;
223 var options = {
224 bool: "AND",
225 expand: true, // turn on partial word search
226 fields: {
227 title: {boost: 2},
228 body: {boost: 1},
229 }
230 };
231 var currentTerm = "";
232 var index = elasticlunr.Index.load(window.searchIndex);
233 // toggle search window
234 var toggleSearchWindow = document.getElementById('js-search-window-toggle');
235 var bodyEl = document.body;
236 var searchOverlay = document.getElementById('search-overlay');
237 var searchWindow = document.getElementById('search-window');
238 var searchActive = bodyEl.classList.contains('has-active-search-window');
240 if (toggleSearchWindow !== null) {
241 toggleSearchWindow.onclick = function() {
242 inputReset.style.display="none";
244 //activate search
245 bodyEl.classList.toggle('has-active-search-window');
246 //put input in focus when activating search
247 searchInput.focus();
249 searchInput.value = "";
250 searchResultsHeader.value = "";
251 searchResults.style.display = searchInput.value.trim() === "" ? "none" : "block";
252 }
253 searchOverlay.addEventListener('click', function(e){
254 if (!searchWindow.contains(e.target)){
255 bodyEl.classList.toggle('has-active-search-window');
256 }
257 })
258 }
260 // Don't refresh the page on enter
261 searchInput.addEventListener('keydown', function(event){
262 var key = event.key || event.keyCode;
264 if (key === 13 || key === "Enter") {
265 event.preventDefault();
266 return false;
267 }
268 })
271 searchInput.addEventListener("keyup", debounce(function() {
272 inputReset.style.display="block";
274 searchResultsHeader.value = "";
275 var term = searchInput.value.trim();
276 /*
277 //removed to fix: a state where there’s a valid search term, but no results
279 if (term === currentTerm || !index) {
280 return;
281 }*/
283 searchResults.style.display = term === "" ? "none" : "block";
284 searchResults.style.overflowY = term === "" ? "hidden" : "scroll";
285 searchResultsItems.innerHTML = "";
286 if (term === "") {
287 inputReset.style.display="none";
288 return;
289 }
291 var results = index.search(term, options).filter(function (r) {
292 return r.doc.body !== "";
293 });
295 if (results.length === 0) {
296 searchResultsHeader.innerText = `No search results for '${term}'.`;
297 return;
298 }
300 currentTerm = term;
301 searchResultsHeader.innerText = `${results.length} search results for '${term}':`;
302 for (var i = 0; i < Math.min(results.length, MAX_ITEMS); i++) {
303 if (!results[i].doc.body) {
304 continue;
305 }
306 searchResultsItems.appendChild(formatSearchResultItem(results[i], term.split(" ")));
307 }
308 }, 150));
310 // reset input button
311 inputReset.onclick=function(){
312 document.getElementById('search-form').reset();
313 }
314 searchForm.addEventListener("reset", function(event){
315 var e = document.createEvent('KeyboardEvent');
316 e.initEvent("keyup", false, true);
317 searchInput.dispatchEvent(e);
318 });
322if (document.readyState === "complete" ||
323 (document.readyState !== "loading" && !document.documentElement.doScroll)
324) {
325 initToggleSearchWindow();
326} else {
327 document.addEventListener("DOMContentLoaded", function () {
328 initSearch();
329 initHotKeys();
330 });
333// Scroll to current document in nav list.
334let docsNavScroll = function() {
335 let docsNav = document.querySelectorAll("ul.content-nav__index a")
336 for (let link in docsNav) {
337 if (window.location.href.includes(docsNav[link].href)) {
338 docsNav[link].scrollIntoView()
339 }
340 }
343if (window.location.href.includes("docs")) {
344 docsNavScroll();
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 })