on c41d59d help sign in
urbit.org/static/scripts.js
342 lines 10.0 kB history raw
1//
2 // styling of input fields
3//
5var inputElements = document.querySelectorAll('input.tlon-input');
6for (var i = 0; i < inputElements.length; i++) {
7 //listen for changes in input
8 inputElements[i].addEventListener('input', function() {
9 // if input has a value do this
10 if (this.value) {
11 var inputContainer = this.parentNode;
12 var validInputs = inputContainer.querySelectorAll('input.tlon-input:valid');
13 var inputs = inputContainer.querySelectorAll('input.tlon-input');
14 if (validInputs.length !== 0) {
15 // has valid input
16 for (var i = 0; i < validInputs.length; i++) {
17 if (this.classList.contains('is-valid') == false ) {
18 validInputs[i].parentNode.classList.add('has-valid-input');
19 }
20 }
21 } else {
22 // doesn't have valid input
23 for (var i = 0; i < inputs.length; i++) {
24 inputs[i].parentNode.classList.remove('has-valid-input');
25 }
26 }
27 } else {
28 this.parentNode.classList.remove('has-valid-input');
29 }
30 });
33//
34 // toggling of navigation menus
35//
37var toggleMainNav = document.getElementById('js-main-nav-toggle');
38if (toggleMainNav !== null) {
39 toggleMainNav.onclick = function() {
40 document.body.classList.toggle('has-active-main-nav');
41 }
44var toggleContentNav = document.getElementById('js-content-nav-toggle');
45if (toggleContentNav !== null) {
46 toggleContentNav.onclick = function() {
47 document.body.classList.toggle('has-active-content-nav');
48 }
51function initHotKeys() {
53 var bodyEl = document.body;
54 var searchInput = document.getElementById('search');
56 document.addEventListener('keydown', function (event) {
57 if (event.defaultPrevented) {
58 return;
59 }
61 var key = event.key || event.keyCode;
63 // ESC to close search window
64 if (key === 'Escape' || key === 'Esc' || key === 27) {
65 document.body.classList.remove('has-active-search-window');
66 console.log('esc');
67 }
69 // / to close toggle window
70 if (key === '/' || key === 'Period' || key === 58) {
71 event.preventDefault();
72 document.body.classList.toggle('has-active-search-window');
73 if (bodyEl.classList.contains('has-active-search-window')) {
74 searchInput.focus();
75 }
76 }
78 //when search is active TAB puts search input into focus
79 if (bodyEl.classList.contains('has-active-search-window')) {
80 if (key === 'Tab' || key === 'Tab' || key === 9) {
81 searchInput.focus();
82 }
83 }
84 });
85};
87//
88 // search functionality
89//
91function debounce(func, wait) {
92 var timeout;
94 return function () {
95 var context = this;
96 var args = arguments;
97 clearTimeout(timeout);
99 timeout = setTimeout(function () {
100 timeout = null;
101 func.apply(context, args);
102 }, wait);
103 };
106// The strategy is as follows:
107// First, assign a value to each word in the document:
108// Words that correspond to search terms (stemmer aware): 40
109// Normal words: 2
110// First word in a sentence: 8
111// Then use a sliding window with a constant number of words and count the
112// sum of the values of the words within the window. Then use the window that got the
113// maximum sum. If there are multiple maximas, then get the last one.
114// Enclose the terms in <b>.
115function makeTeaser(body, terms) {
116 var TERM_WEIGHT = 40;
117 var NORMAL_WORD_WEIGHT = 2;
118 var FIRST_WORD_WEIGHT = 8;
119 //var TEASER_MAX_WORDS = 17;
120 var TEASER_MAX_CHARS = 63;
122 var stemmedTerms = terms.map(function (w) {
123 return elasticlunr.stemmer(w.toLowerCase());
124 });
125 var termFound = false;
126 var index = 0;
127 var weighted = []; // contains elements of ["word", weight, index_in_document]
129 // split in sentences, then words
130 var sentences = body.toLowerCase().split(". ");
132 for (var i in sentences) {
133 var words = sentences[i].split(" ");
134 var value = FIRST_WORD_WEIGHT;
136 for (var j in words) {
137 var word = words[j];
139 if (word.length > 0) {
140 for (var k in stemmedTerms) {
141 if (elasticlunr.stemmer(word).startsWith(stemmedTerms[k])) {
142 value = TERM_WEIGHT;
143 termFound = true;
144 }
145 }
146 weighted.push([word, value, index]);
147 value = NORMAL_WORD_WEIGHT;
148 }
150 index += word.length;
151 index += 1; // ' ' or '.' if last word in sentence
152 }
154 index += 1; // because we split at a two-char boundary '. '
155 }
157 if (weighted.length === 0) {
158 return body;
159 }
161 var windowWeights = [];
162 var windowSize = 0;
164 // loop over words (weighted) till max chars is reached adding a counter to windowSize every time a new word has passed
165 var sumChars = 0;
166 for (var i = 0; i < weighted.length; i++) {
167 sumChars += weighted[i][0].length;
168 if (sumChars <= TEASER_MAX_CHARS) {
169 windowSize++;
170 }
171 }
173 // We add a window with all the weights first
174 var curSum = 0;
175 for (var i = 0; i < windowSize; i++) {
176 curSum += weighted[i][1];
177 }
178 windowWeights.push(curSum);
180 for (var i = 0; i < weighted.length - windowSize; i++) {
181 curSum -= weighted[i][1];
182 curSum += weighted[i + windowSize][1];
183 windowWeights.push(curSum);
184 }
186 // If we didn't find the term, just pick the first window
187 var maxSumIndex = 0;
188 if (termFound) {
189 var maxFound = 0;
190 // backwards
191 for (var i = windowWeights.length - 1; i >= 0; i--) {
192 if (windowWeights[i] > maxFound) {
193 maxFound = windowWeights[i];
194 maxSumIndex = i;
195 }
196 }
197 }
199 var teaser = [];
200 var startIndex = weighted[maxSumIndex][2];
201 for (var i = maxSumIndex; i < maxSumIndex + windowSize; i++) {
202 var word = weighted[i];
203 if (startIndex < word[2]) {
204 // missing text from index to start of `word`
205 teaser.push(body.substring(startIndex, word[2]));
206 startIndex = word[2];
207 }
209 // add <em/> around search terms
210 if (word[1] === TERM_WEIGHT) {
211 teaser.push("<b>");
212 }
213 startIndex = word[2] + word[0].length;
214 teaser.push(body.substring(word[2], startIndex));
216 if (word[1] === TERM_WEIGHT) {
217 teaser.push("</b>");
218 }
219 }
220 teaser.push("…");
221 return teaser.join("");
224function formatSearchResultTitle(path) {
225 var pathArray = path.split( 'docs/' );
226 var slug = pathArray[1];
227 var slugArray = slug.split( '/' );
228 var lastPartTitle = slugArray.splice(slugArray.length - 2, slugArray.length).join('');
229 var firstPartTitle = slugArray.join(' / ');
231 var fullTitle = firstPartTitle + ' / ' + '<span class="search-results__item__title__slug-end">' + lastPartTitle + '</span>';
233 return fullTitle;
236function formatSearchResultItem(item, terms) {
237 var li = document.createElement("li");
238 var createA = document.createElement("a");
239 li.appendChild(createA);
240 var teaserTitle = formatSearchResultTitle(item.ref);
241 li.classList.add("search-results__item");
242 var hrefA = item.ref;
243 createA.setAttribute('href', hrefA);
244 createA.innerHTML = `<span class="search-results__item__title">${teaserTitle}</span>`;
245 createA.innerHTML += `<div class="search-results__teaser">${makeTeaser(item.doc.body, terms)}</div>`;
246 return li;
249function initSearch() {
250 var searchInput = document.getElementById("search");
252 if (!searchInput) {
253 return;
254 }
256 var searchResults = document.querySelector(".search-results");
257 var searchResultsHeader = document.querySelector(".search-results__header");
258 var searchResultsItems = document.querySelector(".search-results__items");
259 var MAX_ITEMS = 200;
261 var options = {
262 bool: "AND",
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 });