on d14ebf2 help sign in
urbit.org/static/scripts.js
341 lines 9.8 kB history raw
3function initHotKeys() {
5 var bodyEl = document.body;
6 var searchInput = document.getElementById('search');
8 document.addEventListener('keydown', function (event) {
9 if (event.defaultPrevented) {
10 return;
11 }
13 var key = event.key || event.keyCode;
15 // ESC to close search window
16 if (key === 'Escape' || key === 'Esc' || key === 27) {
17 document.body.classList.remove('has-active-search-window');
18 }
20 // / to close toggle window
21 if (key === '/' || key === 'Period' || key === 58) {
22 event.preventDefault();
23 document.body.classList.toggle('has-active-search-window');
24 if (bodyEl.classList.contains('has-active-search-window')) {
25 searchInput.focus();
26 }
27 }
29 //when search is active TAB puts search input into focus
30 if (bodyEl.classList.contains('has-active-search-window')) {
31 if (key === 'Tab' || key === 'Tab' || key === 9) {
32 searchInput.focus();
33 }
34 }
35 });
36};
39// search functionality
40function debounce(func, wait) {
41 var timeout;
43 return function () {
44 var context = this;
45 var args = arguments;
46 clearTimeout(timeout);
48 timeout = setTimeout(function () {
49 timeout = null;
50 func.apply(context, args);
51 }, wait);
52 };
55// The strategy is as follows:
56// First, assign a value to each word in the document:
57// Words that correspond to search terms (stemmer aware): 40
58// Normal words: 2
59// First word in a sentence: 8
60// Then use a sliding window with a constant number of words and count the
61// sum of the values of the words within the window. Then use the window that got the
62// maximum sum. If there are multiple maximas, then get the last one.
63// Enclose the terms in <b>.
64function makeTeaser(body, terms) {
65 var TERM_WEIGHT = 40;
66 var NORMAL_WORD_WEIGHT = 2;
67 var FIRST_WORD_WEIGHT = 8;
68 //var TEASER_MAX_WORDS = 17;
69 var TEASER_MAX_CHARS = 63;
71 var stemmedTerms = terms.map(function (w) {
72 return elasticlunr.stemmer(w.toLowerCase());
73 });
75 var termFound = false;
76 var index = 0;
77 var weighted = []; // contains elements of ["word", weight, index_in_document]
79 // split in sentences, then words
80 var sentences = body.toLowerCase().split(". ");
82 for (var i in sentences) {
83 var words = sentences[i].split(" ");
84 var value = FIRST_WORD_WEIGHT;
86 for (var j in words) {
87 var word = words[j];
89 if (word.length > 0) {
90 for (var k in stemmedTerms) {
91 if (elasticlunr.stemmer(word).startsWith(stemmedTerms[k])) {
92 value = TERM_WEIGHT;
93 termFound = true;
94 }
95 }
96 weighted.push([word, value, index]);
97 value = NORMAL_WORD_WEIGHT;
98 }
100 index += word.length;
101 index += 1; // ' ' or '.' if last word in sentence
102 }
104 index += 1; // because we split at a two-char boundary '. '
105 }
107 if (weighted.length === 0) {
108 return body;
109 }
111 var windowWeights = [];
112 var windowSize = 0;
114 // loop over words (weighted) till max chars is reached adding a counter to windowSize every time a new word has passed
115 var sumChars = 0;
116 for (var i = 0; i < weighted.length; i++) {
117 sumChars += weighted[i][0].length;
118 if (sumChars <= TEASER_MAX_CHARS) {
119 windowSize++;
120 }
121 }
123 // We add a window with all the weights first
124 var curSum = 0;
125 for (var i = 0; i < windowSize; i++) {
126 curSum += weighted[i][1];
127 }
128 windowWeights.push(curSum);
130 for (var i = 0; i < weighted.length - windowSize; i++) {
131 curSum -= weighted[i][1];
132 curSum += weighted[i + windowSize][1];
133 windowWeights.push(curSum);
134 }
136 // If we didn't find the term, just pick the first window
137 var maxSumIndex = 0;
138 if (termFound) {
139 var maxFound = 0;
140 // backwards
141 for (var i = windowWeights.length - 1; i >= 0; i--) {
142 if (windowWeights[i] > maxFound) {
143 maxFound = windowWeights[i];
144 maxSumIndex = i;
145 }
146 }
147 }
149 var teaser = [];
150 var startIndex = weighted[maxSumIndex][2];
151 for (var i = maxSumIndex; i < maxSumIndex + windowSize; i++) {
152 var word = weighted[i];
153 if (startIndex < word[2]) {
154 // missing text from index to start of `word`
155 teaser.push(body.substring(startIndex, word[2]));
156 startIndex = word[2];
157 }
159 startIndex = word[2] + word[0].length;
160 teaser.push(body.substring(word[2], startIndex));
162 }
163 teaser.push("…");
164 return teaser.join("");
167function formatSearchResultTitle(item) {
168 var pathArray = item.ref.split( '/' );
170 // first directory is in 4th element of split path array
171 var firstPartTitle = pathArray[3];
173 // last directory is in 2nd to last element of array
174 var lastPartTitle = item.doc.title;
176 var fullTitle = firstPartTitle + '<span class="gray90 inline-block pl2">' + ' / ' + lastPartTitle + '</span>';
178 return fullTitle;
181function formatSearchResultItem(item, terms) {
182 var li = document.createElement("li");
183 var createA = document.createElement("a");
184 li.appendChild(createA);
185 var teaserTitle = formatSearchResultTitle(item);
186 li.classList.add("search-results__item");
187 li.classList.add("ph3");
188 var hrefA = item.ref;
189 createA.setAttribute('href', hrefA);
190 createA.setAttribute('class','no-underline block pl6 pv3');
191 createA.innerHTML = `<span class="fs45 capitalize">${teaserTitle}</span>`;
192 createA.innerHTML += `<span class='pr7 fs5 none float-right'>→</span>`;
193 createA.innerHTML += `<div class="fs35 truncate mr10">${makeTeaser(item.doc.body, terms)}</div>`;
194 return li;
197function initSearch() {
198 var searchInput = document.getElementById("search");
199 var searchForm = document.getElementById("search-form");
200 var inputReset = searchForm.nextElementSibling;
202 if (!searchInput) {
203 return;
204 }
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";
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 var results = index.search(term, options).filter(function (r) {
279 return r.doc.body !== "";
280 });
282 if (results.length === 0) {
283 searchResultsHeader.innerText = `No search results for '${term}'.`;
284 return;
285 }
287 currentTerm = term;
288 searchResultsHeader.innerText = `${results.length} search results for '${term}':`;
289 for (var i = 0; i < Math.min(results.length, MAX_ITEMS); i++) {
290 if (!results[i].doc.body) {
291 continue;
292 }
293 searchResultsItems.appendChild(formatSearchResultItem(results[i], term.split(" ")));
294 }
295 }, 150));
297 // reset input button
298 inputReset.onclick=function(){
299 document.getElementById('search-form').reset();
300 }
301 searchForm.addEventListener("reset", function(event){
302 var e = document.createEvent('KeyboardEvent');
303 e.initEvent("keyup", false, true);
304 searchInput.dispatchEvent(e);
305 });
309if (document.readyState === "complete" ||
310 (document.readyState !== "loading" && !document.documentElement.doScroll)
311) {
312 initToggleSearchWindow();
313} else {
314 document.addEventListener("DOMContentLoaded", function () {
315 initSearch();
316 initHotKeys();
317 });
320// Scroll to current document in nav list.
321// let docsNavScroll = function() {
322// let docsNav = document.querySelectorAll("ul.content-nav__index a")
323// for (let link in docsNav) {
324// if (window.location.href.includes(docsNav[link].href)) {
325// docsNav[link].scrollIntoView()
326// }
327// }
328//}
330if (window.location.href.includes("docs")) {
331 docsNavScroll();
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 })