on c36eab8 help sign in
urbit.org/static/scripts.js
342 lines 10 kB history raw
1// styling of input fields
2var inputElements = document.querySelectorAll('input.tlon-input');
3for (var i = 0; i < inputElements.length; i++) {
4 //listen for changes in input
5 inputElements[i].addEventListener('input', function() {
6 // if input has a value do this
7 if (this.value) {
8 var inputContainer = this.parentNode;
9 var validInputs = inputContainer.querySelectorAll('input.tlon-input:valid');
10 var inputs = inputContainer.querySelectorAll('input.tlon-input');
11 if (validInputs.length !== 0) {
12 // has valid input
13 for (var i = 0; i < validInputs.length; i++) {
14 if (this.classList.contains('is-valid') == false ) {
15 validInputs[i].parentNode.classList.add('has-valid-input');
16 }
17 }
18 } else {
19 // doesn't have valid input
20 for (var i = 0; i < inputs.length; i++) {
21 inputs[i].parentNode.classList.remove('has-valid-input');
22 }
23 }
24 } else {
25 this.parentNode.classList.remove('has-valid-input');
26 }
27 });
30// toggling of navigation menus
31var toggleMainNav = document.getElementById('js-main-nav-toggle');
32if (toggleMainNav !== null) {
33 toggleMainNav.onclick = function() {
34 document.body.classList.toggle('has-active-main-nav');
35 }
38var toggleContentNav = document.getElementById('js-content-nav-toggle');
39if (toggleContentNav !== null) {
40 toggleContentNav.onclick = function() {
41 document.body.classList.toggle('has-active-content-nav');
42 }
45function initHotKeys() {
47 var bodyEl = document.body;
48 var searchInput = document.getElementById('search');
50 document.addEventListener('keydown', function (event) {
51 if (event.defaultPrevented) {
52 return;
53 }
55 var key = event.key || event.keyCode;
57 // ESC to close search window
58 if (key === 'Escape' || key === 'Esc' || key === 27) {
59 document.body.classList.remove('has-active-search-window');
60 console.log('esc');
61 }
63 // / to close toggle window
64 if (key === '/' || key === 'Period' || key === 58) {
65 event.preventDefault();
66 document.body.classList.toggle('has-active-search-window');
67 if (bodyEl.classList.contains('has-active-search-window')) {
68 searchInput.focus();
69 }
70 }
72 //when search is active TAB puts search input into focus
73 if (bodyEl.classList.contains('has-active-search-window')) {
74 if (key === 'Tab' || key === 'Tab' || key === 9) {
75 searchInput.focus();
76 }
77 }
78 });
79};
82// search functionality
83function debounce(func, wait) {
84 var timeout;
86 return function () {
87 var context = this;
88 var args = arguments;
89 clearTimeout(timeout);
91 timeout = setTimeout(function () {
92 timeout = null;
93 func.apply(context, args);
94 }, wait);
95 };
98// Taken from mdbook
99// The strategy is as follows:
100// First, assign a value to each word in the document:
101// Words that correspond to search terms (stemmer aware): 40
102// Normal words: 2
103// First word in a sentence: 8
104// Then use a sliding window with a constant number of words and count the
105// sum of the values of the words within the window. Then use the window that got the
106// maximum sum. If there are multiple maximas, then get the last one.
107// Enclose the terms in <b>.
108function makeTeaser(body, terms) {
109 console.log("make teaser");
110 var TERM_WEIGHT = 40;
111 var NORMAL_WORD_WEIGHT = 2;
112 var FIRST_WORD_WEIGHT = 8;
113 //var TEASER_MAX_WORDS = 17;
114 var TEASER_MAX_CHARS = 63;
116 var stemmedTerms = terms.map(function (w) {
117 return elasticlunr.stemmer(w.toLowerCase());
118 });
120 var termFound = false;
121 var index = 0;
122 var weighted = []; // contains elements of ["word", weight, index_in_document]
124 // split in sentences, then words
125 var sentences = body.toLowerCase().split(". ");
127 for (var i in sentences) {
128 var words = sentences[i].split(" ");
129 var value = FIRST_WORD_WEIGHT;
131 for (var j in words) {
132 var word = words[j];
134 if (word.length > 0) {
135 for (var k in stemmedTerms) {
136 if (elasticlunr.stemmer(word).startsWith(stemmedTerms[k])) {
137 value = TERM_WEIGHT;
138 termFound = true;
139 }
140 }
141 weighted.push([word, value, index]);
142 value = NORMAL_WORD_WEIGHT;
143 }
145 index += word.length;
146 index += 1; // ' ' or '.' if last word in sentence
147 }
149 index += 1; // because we split at a two-char boundary '. '
150 }
152 if (weighted.length === 0) {
153 return body;
154 }
156 var windowWeights = [];
157 var windowSize = 0;
159 // loop over words (weighted) till max chars is reached adding a counter to windowSize every time a new word has passed
160 var sumChars = 0;
161 for (var i = 0; i < weighted.length; i++) {
162 sumChars += weighted[i][0].length;
163 if (sumChars <= TEASER_MAX_CHARS) {
164 windowSize++;
165 }
166 }
168 // We add a window with all the weights first
169 var curSum = 0;
170 for (var i = 0; i < windowSize; i++) {
171 curSum += weighted[i][1];
172 }
173 windowWeights.push(curSum);
175 for (var i = 0; i < weighted.length - windowSize; i++) {
176 curSum -= weighted[i][1];
177 curSum += weighted[i + windowSize][1];
178 windowWeights.push(curSum);
179 }
181 // If we didn't find the term, just pick the first window
182 var maxSumIndex = 0;
183 if (termFound) {
184 var maxFound = 0;
185 // backwards
186 for (var i = windowWeights.length - 1; i >= 0; i--) {
187 if (windowWeights[i] > maxFound) {
188 maxFound = windowWeights[i];
189 maxSumIndex = i;
190 }
191 }
192 }
194 var teaser = [];
195 var startIndex = weighted[maxSumIndex][2];
196 for (var i = maxSumIndex; i < maxSumIndex + windowSize; i++) {
197 var word = weighted[i];
198 if (startIndex < word[2]) {
199 // missing text from index to start of `word`
200 teaser.push(body.substring(startIndex, word[2]));
201 startIndex = word[2];
202 }
204 // add dark color around search terms
205 if (word[1] === TERM_WEIGHT) {
206 teaser.push("<span class='gray70'>");
207 }
208 startIndex = word[2] + word[0].length;
209 teaser.push(body.substring(word[2], startIndex));
211 if (word[1] === TERM_WEIGHT) {
212 teaser.push("</span>");
213 }
214 }
215 teaser.push("…");
216 return teaser.join("");
219function formatSearchResultTitle(path) {
220 var pathArray = path.split( '/' );
222 // first directory is in 4th element of split path array
223 var firstPartTitle = pathArray[3];
225 // last directory is in 2nd to last element of array
226 var lastPartTitle = pathArray[pathArray.length-2].replace(/-/g,' ');
228 var fullTitle = firstPartTitle + '<span class="gray90">' + ' / ' + lastPartTitle + '</span>';
230 return fullTitle;
233function formatSearchResultItem(item, terms) {
234 var li = document.createElement("li");
235 var createA = document.createElement("a");
236 li.appendChild(createA);
237 var teaserTitle = formatSearchResultTitle(item.ref);
238 li.classList.add("search-results__item");
239 var hrefA = item.ref;
240 createA.setAttribute('href', hrefA);
241 createA.setAttribute('class','no-underline block pl6 pv2');
242 createA.innerHTML = `<span class="fs45 capitalize gray30">${teaserTitle}</span>`;
243 createA.innerHTML += `<div class="fs35 gray30">${makeTeaser(item.doc.body, terms)}</div>`;
244 return li;
247function initSearch() {
248 console.log("init search");
249 var searchInput = document.getElementById("search");
251 if (!searchInput) {
252 return;
253 }
255 var searchResults = document.querySelector(".search-results");
256 var searchResultsHeader = document.querySelector(".search-results__header");
257 var searchResultsItems = document.querySelector(".search-results__items");
258 var MAX_ITEMS = 200;
260 var options = {
261 bool: "AND",
262 expand: true, // turn on partial word search
263 fields: {
264 title: {boost: 2},
265 body: {boost: 1},
266 }
267 };
268 var currentTerm = "";
269 var index = elasticlunr.Index.load(window.searchIndex);
271 // toggle search window
272 var toggleSearchWindow = document.getElementById('js-search-window-toggle');
273 var bodyEl = document.body;
274 var searchOverlay = document.getElementById('search-overlay');
275 var searchWindow = document.getElementById('search-window');
276 var searchActive = bodyEl.classList.contains('has-active-search-window');
277 if (toggleSearchWindow !== null) {
278 toggleSearchWindow.onclick = function() {
279 //activate search
280 bodyEl.classList.toggle('has-active-search-window');
281 //put input in focus when activating search
282 searchInput.focus();
283 searchInput.value = "";
284 searchResultsHeader.value = "";
285 searchResults.style.display = searchInput.value.trim() === "" ? "none" : "block";
286 }
287 searchOverlay.addEventListener('click', function(e){
288 if (!searchWindow.contains(e.target)){
289 bodyEl.classList.toggle('has-active-search-window');
290 }
291 })
292 }
294 // when typing
295 searchInput.addEventListener("keyup", debounce(function() {
296 searchResultsHeader.value = "";
298 var term = searchInput.value.trim();
300 /*
301 //removed to fix: a state where there’s a valid search term, but no results
303 if (term === currentTerm || !index) {
304 return;
305 }*/
307 searchResults.style.display = term === "" ? "none" : "block";
308 searchResults.style.overflowY = term === "" ? "hidden" : "scroll";
309 searchResultsItems.innerHTML = "";
310 if (term === "") {
311 return;
312 }
314 var results = index.search(term, options).filter(function (r) {
315 return r.doc.body !== "";
316 });
317 if (results.length === 0) {
318 searchResultsHeader.innerText = `No search results for '${term}'.`;
319 return;
320 }
322 currentTerm = term;
323 searchResultsHeader.innerText = `${results.length} search results for '${term}':`;
324 for (var i = 0; i < Math.min(results.length, MAX_ITEMS); i++) {
325 if (!results[i].doc.body) {
326 continue;
327 }
328 searchResultsItems.appendChild(formatSearchResultItem(results[i], term.split(" ")));
329 }
330 }, 150));
333if (document.readyState === "complete" ||
334 (document.readyState !== "loading" && !document.documentElement.doScroll)
335) {
336 initToggleSearchWindow();
337} else {
338 document.addEventListener("DOMContentLoaded", function () {
339 initSearch();
340 initHotKeys();
341 });