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