on c64690c help sign in
urbit.org/static/scripts.js
351 lines 10 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 }
51/*function initToggleMenu() {
52 var menu = document.querySelector(".menu");
53 var menuIcon = document.querySelector(".menu-icon");
54 var page = document.querySelector(".page");
55 menuIcon.addEventListener("click", function() {
56 menu.classList.toggle("menu-hidden");
57 page.classList.toggle("page-without-menu");
58 });
59}*/
61function initToggleSearchWindow() {
62 var toggleSearchWindow = document.getElementById('js-search-window-toggle');
63 var bodyEl = document.body;
64 var searchOverlay = document.getElementById('search-overlay');
65 var searchWindow = document.getElementById('search-window');
66 var searchActive = bodyEl.classList.contains('has-active-search-window');
67 var searchInput = document.getElementById('search');
68 if (toggleSearchWindow !== null) {
69 toggleSearchWindow.onclick = function() {
70 //activate search
71 bodyEl.classList.toggle('has-active-search-window');
72 //put input in focus when activating search
73 searchInput.focus();
74 }
75 searchOverlay.addEventListener('click', function(e){
76 if (!searchWindow.contains(e.target)){
77 bodyEl.classList.toggle('has-active-search-window');
78 }
79 })
80 }
83//
84 // hotkeys
85//
86function initHotKeys() {
87 /*document.onkeydown = function(evt) {
88 evt = evt || window.event;
89 if (evt.keyCode == 27) {
90 }
92 //when search is active TAB puts search input into focus
93 if (evt.keyCode == 27) {
94 document.body.classList.remove('has-active-search-window');
95 }
96 };*/
98 var bodyEl = document.body;
99 var searchInput = document.getElementById('search');
101 document.addEventListener('keyup', function (event) {
102 if (event.defaultPrevented) {
103 return;
104 }
106 var key = event.key || event.keyCode;
108 // ESC to close search window
109 if (key === 'Escape' || key === 'Esc' || key === 27) {
110 document.body.classList.remove('has-active-search-window');
111 }
113 //when search is active TAB puts search input into focus
114 if (bodyEl.classList.contains('has-active-search-window')) {
115 if (key === 'Tab' || key === 'Tab' || key === 9) {
116 searchInput.focus();
117 console.log('focus');
118 }
119 console.log('got here');
120 }
121 });
122};
126//
127 // search functionality
128//
130function debounce(func, wait) {
131 var timeout;
133 return function () {
134 var context = this;
135 var args = arguments;
136 clearTimeout(timeout);
138 timeout = setTimeout(function () {
139 timeout = null;
140 func.apply(context, args);
141 }, wait);
142 };
145// Taken from mdbook
146// The strategy is as follows:
147// First, assign a value to each word in the document:
148// Words that correspond to search terms (stemmer aware): 40
149// Normal words: 2
150// First word in a sentence: 8
151// Then use a sliding window with a constant number of words and count the
152// sum of the values of the words within the window. Then use the window that got the
153// maximum sum. If there are multiple maximas, then get the last one.
154// Enclose the terms in <b>.
155function makeTeaser(body, terms) {
156 var TERM_WEIGHT = 40;
157 var NORMAL_WORD_WEIGHT = 2;
158 var FIRST_WORD_WEIGHT = 8;
159 //var TEASER_MAX_WORDS = 17;
160 var TEASER_MAX_CHARS = 63;
162 var stemmedTerms = terms.map(function (w) {
163 return elasticlunr.stemmer(w.toLowerCase());
164 });
165 var termFound = false;
166 var index = 0;
167 var weighted = []; // contains elements of ["word", weight, index_in_document]
169 // split in sentences, then words
170 var sentences = body.toLowerCase().split(". ");
172 for (var i in sentences) {
173 var words = sentences[i].split(" ");
174 var value = FIRST_WORD_WEIGHT;
176 for (var j in words) {
177 var word = words[j];
179 if (word.length > 0) {
180 for (var k in stemmedTerms) {
181 if (elasticlunr.stemmer(word).startsWith(stemmedTerms[k])) {
182 value = TERM_WEIGHT;
183 termFound = true;
184 }
185 }
186 weighted.push([word, value, index]);
187 value = NORMAL_WORD_WEIGHT;
188 }
190 index += word.length;
191 index += 1; // ' ' or '.' if last word in sentence
192 }
194 index += 1; // because we split at a two-char boundary '. '
195 }
197 if (weighted.length === 0) {
198 return body;
199 }
201 var windowWeights = [];
202 var windowSize = 0;
204 // loop over words (weighted) till max chars is reached adding a counter to windowSize every time a new word has passed
205 var sumChars = 0;
206 for (var i = 0; i < weighted.length; i++) {
207 sumChars += weighted[i][0].length;
208 if (sumChars <= TEASER_MAX_CHARS) {
209 windowSize++;
210 }
211 }
213 // We add a window with all the weights first
214 var curSum = 0;
215 for (var i = 0; i < windowSize; i++) {
216 curSum += weighted[i][1];
217 }
218 windowWeights.push(curSum);
220 for (var i = 0; i < weighted.length - windowSize; i++) {
221 curSum -= weighted[i][1];
222 curSum += weighted[i + windowSize][1];
223 windowWeights.push(curSum);
224 }
226 // If we didn't find the term, just pick the first window
227 var maxSumIndex = 0;
228 if (termFound) {
229 var maxFound = 0;
230 // backwards
231 for (var i = windowWeights.length - 1; i >= 0; i--) {
232 if (windowWeights[i] > maxFound) {
233 maxFound = windowWeights[i];
234 maxSumIndex = i;
235 }
236 }
237 }
239 var teaser = [];
240 var startIndex = weighted[maxSumIndex][2];
241 for (var i = maxSumIndex; i < maxSumIndex + windowSize; i++) {
242 var word = weighted[i];
243 if (startIndex < word[2]) {
244 // missing text from index to start of `word`
245 teaser.push(body.substring(startIndex, word[2]));
246 startIndex = word[2];
247 }
249 // add <em/> around search terms
250 if (word[1] === TERM_WEIGHT) {
251 teaser.push("<b>");
252 }
253 startIndex = word[2] + word[0].length;
254 teaser.push(body.substring(word[2], startIndex));
256 if (word[1] === TERM_WEIGHT) {
257 teaser.push("</b>");
258 }
259 }
260 teaser.push("…");
261 return teaser.join("");
264function formatSearchResultTitle(path) {
265 var pathArray = path.split( 'docs/' );
266 var slug = pathArray[1];
267 var slugArray = slug.split( '/' );
268 var lastPartTitle = slugArray.splice(slugArray.length - 2, slugArray.length).join('');
269 var firstPartTitle = slugArray.join(' / ');
271 var fullTitle = firstPartTitle + ' / ' + '<span class="search-results__item__title__slug-end">' + lastPartTitle + '</span>';
273 return fullTitle;
276function formatSearchResultItem(item, terms) {
277 var li = document.createElement("li");
278 var createA = document.createElement("a");
279 li.appendChild(createA);
280 var teaserTitle = formatSearchResultTitle(item.ref);
281 li.classList.add("search-results__item");
282 var hrefA = item.ref;
283 createA.setAttribute('href', hrefA);
284 createA.innerHTML = `<span class="search-results__item__title">${teaserTitle}</span>`;
285 createA.innerHTML += `<div class="search-results__teaser">${makeTeaser(item.doc.body, terms)}</div>`;
286 return li;
289function initSearch() {
290 var searchInput = document.getElementById("search");
291 if (!searchInput) {
292 return;
293 }
295 var searchResults = document.querySelector(".search-results");
296 var searchResultsHeader = document.querySelector(".search-results__header");
297 var searchResultsItems = document.querySelector(".search-results__items");
298 var MAX_ITEMS = 200;
300 var options = {
301 bool: "AND",
302 fields: {
303 title: {boost: 2},
304 body: {boost: 1},
305 }
306 };
307 var currentTerm = "";
308 var index = elasticlunr.Index.load(window.searchIndex);
310 searchInput.addEventListener("keyup", debounce(function() {
311 var term = searchInput.value.trim();
312 if (term === currentTerm || !index) {
313 return;
314 }
315 searchResults.style.display = term === "" ? "none" : "block";
316 searchResults.style.overflowY = term === "" ? "hidden" : "scroll";
317 searchResultsItems.innerHTML = "";
318 if (term === "") {
319 return;
320 }
322 var results = index.search(term, options).filter(function (r) {
323 return r.doc.body !== "";
324 });
325 if (results.length === 0) {
326 searchResultsHeader.innerText = `No search results for '${term}'.`;
327 return;
328 }
330 currentTerm = term;
331 searchResultsHeader.innerText = `${results.length} search results for '${term}':`;
332 for (var i = 0; i < Math.min(results.length, MAX_ITEMS); i++) {
333 if (!results[i].doc.body) {
334 continue;
335 }
336 searchResultsItems.appendChild(formatSearchResultItem(results[i], term.split(" ")));
337 }
338 }, 150));
341if (document.readyState === "complete" ||
342 (document.readyState !== "loading" && !document.documentElement.doScroll)
343) {
344 initToggleSearchWindow();
345} else {
346 document.addEventListener("DOMContentLoaded", function () {
347 initToggleSearchWindow();
348 initSearch();
349 initHotKeys();
350 });