on 530f30e help sign in
urbit.org/static/scripts.js
337 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 var TERM_WEIGHT = 40;
110 var NORMAL_WORD_WEIGHT = 2;
111 var FIRST_WORD_WEIGHT = 8;
112 //var TEASER_MAX_WORDS = 17;
113 var TEASER_MAX_CHARS = 63;
115 var stemmedTerms = terms.map(function (w) {
116 return elasticlunr.stemmer(w.toLowerCase());
117 });
119 var termFound = false;
120 var index = 0;
121 var weighted = []; // contains elements of ["word", weight, index_in_document]
123 // split in sentences, then words
124 var sentences = body.toLowerCase().split(". ");
126 for (var i in sentences) {
127 var words = sentences[i].split(" ");
128 var value = FIRST_WORD_WEIGHT;
130 for (var j in words) {
131 var word = words[j];
133 if (word.length > 0) {
134 for (var k in stemmedTerms) {
135 if (elasticlunr.stemmer(word).startsWith(stemmedTerms[k])) {
136 value = TERM_WEIGHT;
137 termFound = true;
138 }
139 }
140 weighted.push([word, value, index]);
141 value = NORMAL_WORD_WEIGHT;
142 }
144 index += word.length;
145 index += 1; // ' ' or '.' if last word in sentence
146 }
148 index += 1; // because we split at a two-char boundary '. '
149 }
151 if (weighted.length === 0) {
152 return body;
153 }
155 var windowWeights = [];
156 var windowSize = 0;
158 // loop over words (weighted) till max chars is reached adding a counter to windowSize every time a new word has passed
159 var sumChars = 0;
160 for (var i = 0; i < weighted.length; i++) {
161 sumChars += weighted[i][0].length;
162 if (sumChars <= TEASER_MAX_CHARS) {
163 windowSize++;
164 }
165 }
167 // We add a window with all the weights first
168 var curSum = 0;
169 for (var i = 0; i < windowSize; i++) {
170 curSum += weighted[i][1];
171 }
172 windowWeights.push(curSum);
174 for (var i = 0; i < weighted.length - windowSize; i++) {
175 curSum -= weighted[i][1];
176 curSum += weighted[i + windowSize][1];
177 windowWeights.push(curSum);
178 }
180 // If we didn't find the term, just pick the first window
181 var maxSumIndex = 0;
182 if (termFound) {
183 var maxFound = 0;
184 // backwards
185 for (var i = windowWeights.length - 1; i >= 0; i--) {
186 if (windowWeights[i] > maxFound) {
187 maxFound = windowWeights[i];
188 maxSumIndex = i;
189 }
190 }
191 }
193 var teaser = [];
194 var startIndex = weighted[maxSumIndex][2];
195 for (var i = maxSumIndex; i < maxSumIndex + windowSize; i++) {
196 var word = weighted[i];
197 if (startIndex < word[2]) {
198 // missing text from index to start of `word`
199 teaser.push(body.substring(startIndex, word[2]));
200 startIndex = word[2];
201 }
203 // add dark color around search terms
204 if (word[1] === TERM_WEIGHT) {
205 teaser.push("<span class='gray70'>");
206 }
207 startIndex = word[2] + word[0].length;
208 teaser.push(body.substring(word[2], startIndex));
210 if (word[1] === TERM_WEIGHT) {
211 teaser.push("</span>");
212 }
213 }
214 teaser.push("…");
215 return teaser.join("");
218function formatSearchResultTitle(path) {
219 var pathArray = path.split( '/' );
221 // first directory is in 4th element of split path array
222 var firstPartTitle = pathArray[3];
224 // last directory is in 2nd to last element of array
225 var lastPartTitle = pathArray[pathArray.length-2].replace(/-/g,' ');
227 var fullTitle = firstPartTitle + '<span class="gray90 inline-block pl2">' + ' / ' + lastPartTitle + '</span>';
229 return fullTitle;
232function formatSearchResultItem(item, terms) {
233 var li = document.createElement("li");
234 var createA = document.createElement("a");
235 li.appendChild(createA);
236 var teaserTitle = formatSearchResultTitle(item.ref);
237 li.classList.add("search-results__item");
238 li.classList.add("ph3");
239 var hrefA = item.ref;
240 createA.setAttribute('href', hrefA);
241 createA.setAttribute('class','no-underline block pl6 pv3');
242 createA.innerHTML = `<span class="fs45 capitalize gray30">${teaserTitle}</span>`;
243 createA.innerHTML += `<span class='pr7 fs5 none float-right'>→</span>`;
244 createA.innerHTML += `<div class="fs35 gray30 truncate mr10">${makeTeaser(item.doc.body, terms)}</div>`;
245 return li;
248function initSearch() {
249 var searchInput = document.getElementById("search");
250 if (!searchInput) {
251 return;
252 }
254 var searchResults = document.querySelector(".search-results");
255 var searchResultsHeader = document.querySelector(".search-results__header");
256 var searchResultsItems = document.querySelector(".search-results__items");
257 var MAX_ITEMS = 200;
258 var options = {
259 bool: "AND",
260 expand: true, // turn on partial word search
261 fields: {
262 title: {boost: 2},
263 body: {boost: 1},
264 }
265 };
266 var currentTerm = "";
267 var index = elasticlunr.Index.load(window.searchIndex);
268 // toggle search window
269 var toggleSearchWindow = document.getElementById('js-search-window-toggle');
270 var bodyEl = document.body;
271 var searchOverlay = document.getElementById('search-overlay');
272 var searchWindow = document.getElementById('search-window');
273 var searchActive = bodyEl.classList.contains('has-active-search-window');
274 if (toggleSearchWindow !== null) {
275 toggleSearchWindow.onclick = function() {
276 //activate search
277 bodyEl.classList.toggle('has-active-search-window');
278 //put input in focus when activating search
279 searchInput.focus();
280 searchInput.value = "";
281 searchResultsHeader.value = "";
282 searchResults.style.display = searchInput.value.trim() === "" ? "none" : "block";
283 }
284 searchOverlay.addEventListener('click', function(e){
285 if (!searchWindow.contains(e.target)){
286 bodyEl.classList.toggle('has-active-search-window');
287 }
288 })
289 }
290 // when typing
291 searchInput.addEventListener("keyup", debounce(function() {
292 searchResultsHeader.value = "";
293 var term = searchInput.value.trim();
295 /*
296 //removed to fix: a state where there’s a valid search term, but no results
298 if (term === currentTerm || !index) {
299 return;
300 }*/
302 searchResults.style.display = term === "" ? "none" : "block";
303 searchResults.style.overflowY = term === "" ? "hidden" : "scroll";
304 searchResultsItems.innerHTML = "";
305 if (term === "") {
306 return;
307 }
309 var results = index.search(term, options).filter(function (r) {
310 return r.doc.body !== "";
311 });
312 if (results.length === 0) {
313 searchResultsHeader.innerText = `No search results for '${term}'.`;
314 return;
315 }
317 currentTerm = term;
318 searchResultsHeader.innerText = `${results.length} search results for '${term}':`;
319 for (var i = 0; i < Math.min(results.length, MAX_ITEMS); i++) {
320 if (!results[i].doc.body) {
321 continue;
322 }
323 searchResultsItems.appendChild(formatSearchResultItem(results[i], term.split(" ")));
324 }
325 }, 150));
328if (document.readyState === "complete" ||
329 (document.readyState !== "loading" && !document.documentElement.doScroll)
330) {
331 initToggleSearchWindow();
332} else {
333 document.addEventListener("DOMContentLoaded", function () {
334 initSearch();
335 initHotKeys();
336 });