on bde6c7e help sign in
urbit.org/static/scripts.js
339 lines 9.8 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="gray90 inline-block 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 li.classList.add("ph3");
186 var hrefA = item.ref;
187 createA.setAttribute('href', hrefA);
188 createA.setAttribute('class','no-underline block pl6 pv3');
189 createA.innerHTML = `<span class="fs45 capitalize">${teaserTitle}</span>`;
190 createA.innerHTML += `<span class='pr7 fs5 none float-right'>→</span>`;
191 createA.innerHTML += `<div class="fs35 truncate mr10">${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 }
204 var searchResults = document.querySelector(".search-results");
205 var searchResultsHeader = document.querySelector(".search-results__header");
206 var searchResultsItems = document.querySelector(".search-results__items");
207 var MAX_ITEMS = 200;
208 var options = {
209 bool: "AND",
210 expand: true, // turn on partial word search
211 fields: {
212 title: {boost: 2},
213 body: {boost: 1},
214 }
215 };
216 var currentTerm = "";
217 var index = elasticlunr.Index.load(window.searchIndex);
218 // toggle search window
219 var toggleSearchWindow = document.getElementById('js-search-window-toggle');
220 var bodyEl = document.body;
221 var searchOverlay = document.getElementById('search-overlay');
222 var searchWindow = document.getElementById('search-window');
223 var searchActive = bodyEl.classList.contains('has-active-search-window');
225 if (toggleSearchWindow !== null) {
226 toggleSearchWindow.onclick = function() {
227 inputReset.style.display="none";
229 //activate search
230 bodyEl.classList.toggle('has-active-search-window');
231 //put input in focus when activating search
232 searchInput.focus();
234 searchInput.value = "";
235 searchResultsHeader.value = "";
236 searchResults.style.display = searchInput.value.trim() === "" ? "none" : "block";
237 }
238 searchOverlay.addEventListener('click', function(e){
239 if (!searchWindow.contains(e.target)){
240 bodyEl.classList.toggle('has-active-search-window');
241 }
242 })
243 }
245 // Don't refresh the page on enter
246 searchInput.addEventListener('keydown', function(event){
247 var key = event.key || event.keyCode;
249 if (key === 13 || key === "Enter") {
250 event.preventDefault();
251 return false;
252 }
253 })
256 searchInput.addEventListener("keyup", debounce(function() {
257 inputReset.style.display="block";
259 searchResultsHeader.value = "";
260 var term = searchInput.value.trim();
261 /*
262 //removed to fix: a state where there’s a valid search term, but no results
264 if (term === currentTerm || !index) {
265 return;
266 }*/
268 searchResults.style.display = term === "" ? "none" : "block";
269 searchResults.style.overflowY = term === "" ? "hidden" : "scroll";
270 searchResultsItems.innerHTML = "";
271 if (term === "") {
272 inputReset.style.display="none";
273 return;
274 }
276 var results = index.search(term, options).filter(function (r) {
277 return r.doc.body !== "";
278 });
280 if (results.length === 0) {
281 searchResultsHeader.innerText = `No search results for '${term}'.`;
282 return;
283 }
285 currentTerm = term;
286 searchResultsHeader.innerText = `${results.length} search results for '${term}':`;
287 for (var i = 0; i < Math.min(results.length, MAX_ITEMS); i++) {
288 if (!results[i].doc.body) {
289 continue;
290 }
291 searchResultsItems.appendChild(formatSearchResultItem(results[i], term.split(" ")));
292 }
293 }, 150));
295 // reset input button
296 inputReset.onclick=function(){
297 document.getElementById('search-form').reset();
298 }
299 searchForm.addEventListener("reset", function(event){
300 var e = document.createEvent('KeyboardEvent');
301 e.initEvent("keyup", false, true);
302 searchInput.dispatchEvent(e);
303 });
307if (document.readyState === "complete" ||
308 (document.readyState !== "loading" && !document.documentElement.doScroll)
309) {
310 initToggleSearchWindow();
311} else {
312 document.addEventListener("DOMContentLoaded", function () {
313 initSearch();
314 initHotKeys();
315 });
318// Scroll to current document in nav list.
319// let docsNavScroll = function() {
320// let docsNav = document.querySelectorAll("ul.content-nav__index a")
321// for (let link in docsNav) {
322// if (window.location.href.includes(docsNav[link].href)) {
323// docsNav[link].scrollIntoView()
324// }
325// }
326//}
328if (window.location.href.includes("docs")) {
329// docsNavScroll();
330 tippy('.tooltip', {
331 content(reference) {
332 const title = reference.getAttribute('title')
333 reference.removeAttribute('title')
334 return title
335 },
336 animateFill: false,
337 animation: 'fade'
338 })