on 12f20fb help sign in
urbit.org/static/scripts.js
330 lines 9.7 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 console.log('esc');
32 }
34 // / to close toggle window
35 if (key === '/' || key === 'Period' || key === 58) {
36 event.preventDefault();
37 document.body.classList.toggle('has-active-search-window');
38 if (bodyEl.classList.contains('has-active-search-window')) {
39 searchInput.focus();
40 }
41 }
43 //when search is active TAB puts search input into focus
44 if (bodyEl.classList.contains('has-active-search-window')) {
45 if (key === 'Tab' || key === 'Tab' || key === 9) {
46 searchInput.focus();
47 }
48 }
49 });
50};
53// search functionality
54function debounce(func, wait) {
55 var timeout;
57 return function () {
58 var context = this;
59 var args = arguments;
60 clearTimeout(timeout);
62 timeout = setTimeout(function () {
63 timeout = null;
64 func.apply(context, args);
65 }, wait);
66 };
69// Taken from mdbook
70// The strategy is as follows:
71// First, assign a value to each word in the document:
72// Words that correspond to search terms (stemmer aware): 40
73// Normal words: 2
74// First word in a sentence: 8
75// Then use a sliding window with a constant number of words and count the
76// sum of the values of the words within the window. Then use the window that got the
77// maximum sum. If there are multiple maximas, then get the last one.
78// Enclose the terms in <b>.
79function makeTeaser(body, terms) {
80 var TERM_WEIGHT = 40;
81 var NORMAL_WORD_WEIGHT = 2;
82 var FIRST_WORD_WEIGHT = 8;
83 //var TEASER_MAX_WORDS = 17;
84 var TEASER_MAX_CHARS = 63;
86 var stemmedTerms = terms.map(function (w) {
87 return elasticlunr.stemmer(w.toLowerCase());
88 });
90 var termFound = false;
91 var index = 0;
92 var weighted = []; // contains elements of ["word", weight, index_in_document]
94 // split in sentences, then words
95 var sentences = body.toLowerCase().split(". ");
97 for (var i in sentences) {
98 var words = sentences[i].split(" ");
99 var value = FIRST_WORD_WEIGHT;
101 for (var j in words) {
102 var word = words[j];
104 if (word.length > 0) {
105 for (var k in stemmedTerms) {
106 if (elasticlunr.stemmer(word).startsWith(stemmedTerms[k])) {
107 value = TERM_WEIGHT;
108 termFound = true;
109 }
110 }
111 weighted.push([word, value, index]);
112 value = NORMAL_WORD_WEIGHT;
113 }
115 index += word.length;
116 index += 1; // ' ' or '.' if last word in sentence
117 }
119 index += 1; // because we split at a two-char boundary '. '
120 }
122 if (weighted.length === 0) {
123 return body;
124 }
126 var windowWeights = [];
127 var windowSize = 0;
129 // loop over words (weighted) till max chars is reached adding a counter to windowSize every time a new word has passed
130 var sumChars = 0;
131 for (var i = 0; i < weighted.length; i++) {
132 sumChars += weighted[i][0].length;
133 if (sumChars <= TEASER_MAX_CHARS) {
134 windowSize++;
135 }
136 }
138 // We add a window with all the weights first
139 var curSum = 0;
140 for (var i = 0; i < windowSize; i++) {
141 curSum += weighted[i][1];
142 }
143 windowWeights.push(curSum);
145 for (var i = 0; i < weighted.length - windowSize; i++) {
146 curSum -= weighted[i][1];
147 curSum += weighted[i + windowSize][1];
148 windowWeights.push(curSum);
149 }
151 // If we didn't find the term, just pick the first window
152 var maxSumIndex = 0;
153 if (termFound) {
154 var maxFound = 0;
155 // backwards
156 for (var i = windowWeights.length - 1; i >= 0; i--) {
157 if (windowWeights[i] > maxFound) {
158 maxFound = windowWeights[i];
159 maxSumIndex = i;
160 }
161 }
162 }
164 var teaser = [];
165 var startIndex = weighted[maxSumIndex][2];
166 for (var i = maxSumIndex; i < maxSumIndex + windowSize; i++) {
167 var word = weighted[i];
168 if (startIndex < word[2]) {
169 // missing text from index to start of `word`
170 teaser.push(body.substring(startIndex, word[2]));
171 startIndex = word[2];
172 }
174 // add dark color around search terms
175 if (word[1] === TERM_WEIGHT) {
176 teaser.push("<span>");
177 }
178 startIndex = word[2] + word[0].length;
179 teaser.push(body.substring(word[2], startIndex));
181 if (word[1] === TERM_WEIGHT) {
182 teaser.push("</span>");
183 }
184 }
185 teaser.push("…");
186 return teaser.join("");
189function formatSearchResultTitle(path) {
190 var pathArray = path.split( '/' );
192 // first directory is in 4th element of split path array
193 var firstPartTitle = pathArray[3];
195 // last directory is in 2nd to last element of array
196 var lastPartTitle = pathArray[pathArray.length-2].replace(/-/g,' ');
198 var fullTitle = firstPartTitle + '<span class="gray90 inline-block pl2">' + ' / ' + lastPartTitle + '</span>';
200 return fullTitle;
203function formatSearchResultItem(item, terms) {
204 var li = document.createElement("li");
205 var createA = document.createElement("a");
206 li.appendChild(createA);
207 var teaserTitle = formatSearchResultTitle(item.ref);
208 li.classList.add("search-results__item");
209 li.classList.add("ph3");
210 var hrefA = item.ref;
211 createA.setAttribute('href', hrefA);
212 createA.setAttribute('class','no-underline block pl6 pv3');
213 createA.innerHTML = `<span class="fs45 capitalize">${teaserTitle}</span>`;
214 createA.innerHTML += `<span class='pr7 fs5 none float-right'>→</span>`;
215 createA.innerHTML += `<div class="fs35 truncate mr10">${makeTeaser(item.doc.body, terms)}</div>`;
216 return li;
219function initSearch() {
220 var searchInput = document.getElementById("search");
221 var searchForm = document.getElementById("search-form");
222 var inputReset = searchForm.nextElementSibling;
224 if (!searchInput) {
225 return;
226 }
228 var searchResults = document.querySelector(".search-results");
229 var searchResultsHeader = document.querySelector(".search-results__header");
230 var searchResultsItems = document.querySelector(".search-results__items");
231 var MAX_ITEMS = 200;
232 var options = {
233 bool: "AND",
234 expand: true, // turn on partial word search
235 fields: {
236 title: {boost: 2},
237 body: {boost: 1},
238 }
239 };
240 var currentTerm = "";
241 var index = elasticlunr.Index.load(window.searchIndex);
242 // toggle search window
243 var toggleSearchWindow = document.getElementById('js-search-window-toggle');
244 var bodyEl = document.body;
245 var searchOverlay = document.getElementById('search-overlay');
246 var searchWindow = document.getElementById('search-window');
247 var searchActive = bodyEl.classList.contains('has-active-search-window');
249 if (toggleSearchWindow !== null) {
250 toggleSearchWindow.onclick = function() {
251 inputReset.style.display="none";
253 //activate search
254 bodyEl.classList.toggle('has-active-search-window');
255 //put input in focus when activating search
256 searchInput.focus();
258 searchInput.value = "";
259 searchResultsHeader.value = "";
260 searchResults.style.display = searchInput.value.trim() === "" ? "none" : "block";
261 }
262 searchOverlay.addEventListener('click', function(e){
263 if (!searchWindow.contains(e.target)){
264 bodyEl.classList.toggle('has-active-search-window');
265 }
266 })
267 }
270 searchInput.addEventListener("keyup", debounce(function() {
271 inputReset.style.display="block";
273 searchResultsHeader.value = "";
274 var term = searchInput.value.trim();
275 /*
276 //removed to fix: a state where there’s a valid search term, but no results
278 if (term === currentTerm || !index) {
279 return;
280 }*/
282 searchResults.style.display = term === "" ? "none" : "block";
283 searchResults.style.overflowY = term === "" ? "hidden" : "scroll";
284 searchResultsItems.innerHTML = "";
285 if (term === "") {
286 inputReset.style.display="none";
287 return;
288 }
290 var results = index.search(term, options).filter(function (r) {
291 return r.doc.body !== "";
292 });
294 if (results.length === 0) {
295 searchResultsHeader.innerText = `No search results for '${term}'.`;
296 return;
297 }
299 currentTerm = term;
300 searchResultsHeader.innerText = `${results.length} search results for '${term}':`;
301 for (var i = 0; i < Math.min(results.length, MAX_ITEMS); i++) {
302 if (!results[i].doc.body) {
303 continue;
304 }
305 searchResultsItems.appendChild(formatSearchResultItem(results[i], term.split(" ")));
306 }
307 }, 150));
309 // reset input button
310 inputReset.onclick=function(){
311 document.getElementById('search-form').reset();
312 }
313 searchForm.addEventListener("reset", function(event){
314 var e = document.createEvent('KeyboardEvent');
315 e.initEvent("keyup", false, true);
316 searchInput.dispatchEvent(e);
317 });
321if (document.readyState === "complete" ||
322 (document.readyState !== "loading" && !document.documentElement.doScroll)
323) {
324 initToggleSearchWindow();
325} else {
326 document.addEventListener("DOMContentLoaded", function () {
327 initSearch();
328 initHotKeys();
329 });