-
Notifications
You must be signed in to change notification settings - Fork 167
Expand file tree
/
Copy pathscript.js
More file actions
411 lines (344 loc) · 12.4 KB
/
script.js
File metadata and controls
411 lines (344 loc) · 12.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
"use strict";
/* Tags menu filter */
// Get a dictionary of tag name -> tag link from HTML
function getTags() {
const tags = {};
const list = document.querySelectorAll('.versions a');
for (const el of list) {
tags[el.innerText.trim()] = el.href;
}
return tags;
}
// Generate tag search results based on input
// filter: current filter input text
// tags: dictionary of tag name -> tag link
function generateResults(filter, tags) {
const searchResults = document.createDocumentFragment();
const filterRegex = new RegExp(filter, 'i');
for (let key in tags) {
if (tags.hasOwnProperty(key)) {
let tagFound = false;
const tagHighlight = key.replace(filterRegex, result => {
if (result) tagFound = true;
return '<strong>' + result + '</strong>';
})
if (tagFound) {
const tagLink = document.createElement('a');
tagLink.href = tags[key];
tagLink.innerHTML = tagHighlight;
searchResults.appendChild(tagLink);
}
}
}
return searchResults;
}
// Setup tags filter input
function setupVersionsFilter() {
const input = document.querySelector('.filter-input');
const results = document.querySelector('.filter-results');
const versions = document.querySelector('.versions');
const tags = getTags();
input.addEventListener('input', e => {
if (e.target.value === '') {
versions.classList.remove('hide');
results.innerHTML = '';
} else {
versions.classList.add('hide');
results.innerHTML = '';
results.appendChild(generateResults(e.target.value, tags));
}
});
}
// Setup expanding/collapsing versions tree on click
function setupVersionsTree() {
const versions = document.querySelector('.versions');
versions.addEventListener('click', e => {
if (e.target && e.target.nodeName == 'SPAN') {
e.target.classList.toggle('active')
}
});
}
function isWidescreen() {
return getComputedStyle(document.documentElement).getPropertyValue('--is-widescreen') === 'true';
}
// Toggles sidebar visibility, handles widescreen and mobile layouts
function toggleMenu() {
const isWidescreen = getComputedStyle(document.documentElement).getPropertyValue('--is-widescreen') === 'true';
if(isWidescreen) {
const hasShowMenu = document.documentElement.classList.contains('show-menu');
window.localStorage.setItem('show-sidebar', !hasShowMenu);
document.documentElement.classList.toggle('show-menu');
} else {
document.documentElement.classList.toggle('show-menu-mobile');
}
}
// Setup sidebar hamburger menu button, close button and mobile sidebar backdrop events
function setupSidebarSwitch() {
const tag = document.querySelector('.version em');
const openMenu = document.querySelector('.open-menu');
const sidebar = document.querySelector('.sidebar');
// toggle on hamburger menu click
openMenu.addEventListener('click', e => {
e.preventDefault();
toggleMenu();
});
// toggle on footer tag icon click
tag.addEventListener('click', e => {
e.preventDefault();
toggleMenu();
});
// close on close-menu/backdrop click
sidebar.addEventListener('click', e => {
if (e.target === sidebar && isWidescreen()) {
document.documentElement.classList.remove('show-menu');
window.localStorage.setItem('show-sidebar', false);
} else if (e.target === sidebar || e.target.classList.contains('close-menu')) {
document.documentElement.classList.remove('show-menu-mobile');
}
});
}
// Parse and validate line identifier in format L${number}
function parseLineId(lineId) {
if (lineId[0] != "L") {
return;
}
let lineIdNum = parseInt(lineId.substring(1));
console.assert(!isNaN(lineIdNum), "Invalid line id");
let lineElement = document.getElementById(lineId);
if (lineElement === null || lineElement.tagName !== "A") {
return;
}
return lineIdNum;
}
// Parse and validate line range anchor in format #L${lineRangeStart}-L${lineRangeEnd}
function parseLineRangeAnchor(hashStr) {
const hash = hashStr.substring(1).split("-");
if (hash.length < 1 || hash.length > 2) {
return;
}
let firstLine = parseLineId(hash[0]);
let lastLine = hash.length === 2 ? parseLineId(hash[1]) : firstLine;
if (firstLine === undefined || lastLine === undefined) {
return;
}
// Swap line numbers to support "#L2-L1" format. Postel's law.
if (firstLine > lastLine) {
const lineTmp = lastLine;
lastLine = firstLine;
firstLine = lineTmp;
}
return [firstLine, lastLine];
}
// Highlights line number elements from firstLine to lastLine
function highlightFromTo(firstLine, lastLine) {
const firstLineElement = document.getElementById(`L${ firstLine }`);
const lastLineElement = document.getElementById(`L${ lastLine }`);
const firstCodeLine = document.getElementById(`codeline-${ firstLine }`);
const lastCodeLine = document.getElementById(`codeline-${ lastLine }`);
addClassToRangeOfElements(firstLineElement.parentNode, lastLineElement.parentNode, "line-highlight");
addClassToRangeOfElements(firstCodeLine, lastCodeLine, "line-highlight");
}
function clearRangeHighlight() {
const highlightElements = Array.from(document.getElementsByClassName("line-highlight"));
for (let el of highlightElements) {
el.classList.remove("line-highlight");
}
}
function addClassToRangeOfElements(first, last, class_name) {
let element = first;
const elementAfterLast = last !== null ? last.nextElementSibling : null;
while (element !== null && element != elementAfterLast) {
element.classList.add(class_name);
element = element.nextElementSibling;
}
}
// Sets up listeners on element that contains line numbers to handle
// shift-clicks for range highlighting
function setupLineRangeHandlers() {
// Check if page contains the element with line numbers
// If not, then likely script is not executed in context of the source page
const linenodiv = document.querySelector(".linenodiv");
if (linenodiv === null) {
return;
}
let rangeStartLine, rangeEndLine;
const parseFromHash = () => {
const highlightedRange = parseLineRangeAnchor(window.location.hash);
// Set range start/end to elements from hash
if (highlightedRange !== undefined) {
rangeStartLine = highlightedRange[0];
rangeEndLine = highlightedRange[1];
highlightFromTo(rangeStartLine, rangeEndLine);
document.getElementById(`L${rangeStartLine}`).scrollIntoView();
} else if (location.hash !== "" && location.hash[1] === "L") {
rangeStartLine = parseLineId(location.hash.substring(1));
}
}
window.addEventListener("hashchange", _ => {
clearRangeHighlight();
parseFromHash();
});
parseFromHash();
linenodiv.addEventListener("click", ev => {
if (ev.ctrlKey || ev.metaKey) {
return;
}
ev.preventDefault();
// Handler is set on the element that contains all line numbers, check if the
// event is directed at an actual line number element
const el = ev.target;
if (typeof(el.id) !== "string" || el.id[0] !== "L" || el.tagName !== "A") {
return;
}
clearRangeHighlight();
if (rangeStartLine === undefined || !ev.shiftKey) {
rangeStartLine = parseLineId(el.id);
rangeEndLine = undefined;
highlightFromTo(rangeStartLine, rangeStartLine);
window.location.hash = el.id;
} else if (ev.shiftKey) {
if (rangeEndLine === undefined) {
rangeEndLine = parseLineId(el.id);
}
const newLine = parseLineId(el.id);
console.assert(newLine !== undefined, "parseLineId for clicked line is undefined");
// Swap range elements if range end that was previously undefined is now
// before range start
if (rangeStartLine > rangeEndLine) {
const lineTmp = rangeStartLine;
rangeStartLine = rangeEndLine;
rangeEndLine = lineTmp;
}
if (newLine < rangeStartLine) {
// Expand if element above range
rangeStartLine = newLine;
} else if (newLine > rangeEndLine) {
// Expand if element below range
rangeEndLine = newLine;
} else {
// Shrink moving the edge that's closest to the selection.
// Move end if center was selected.
const distanceFromStart = Math.abs(rangeStartLine-newLine);
const distanceFromEnd = Math.abs(rangeEndLine-newLine);
if (distanceFromStart < distanceFromEnd) {
rangeStartLine = newLine;
} else {
rangeEndLine = newLine;
}
}
highlightFromTo(rangeStartLine, rangeEndLine);
window.location.hash = `L${rangeStartLine}-L${rangeEndLine}`;
}
});
}
/* Other fixes */
// prevent chrome from auto-scrolling to input elements
function setupAutoscrollingPrevention() {
const wrapper = document.querySelector('.wrapper');
Array.prototype.forEach.call(document.querySelectorAll('input'), el => {
el.addEventListener('keydown', _ => {
const before = wrapper.scrollTop;
const reset = () => wrapper.scrollTop = before;
window.requestAnimationFrame(reset);
setTimeout(reset, 0);
});
});
}
// Scrolls the page after each anchor change to prevent selected line from
// hiding under the topbar after a line number click.
function setupAnchorOffsetHandler() {
const wrapper = document.querySelector('.wrapper');
const anchorChangeHandler = e => {
if (e && e.preventDefault) e.preventDefault();
if (location.hash.length !== 0) {
const el = document.querySelector(location.hash);
if (el) {
const offsetTop = el.offsetTop;
wrapper.scrollTop = offsetTop < 100 ? 200 : offsetTop + 100;
}
}
};
window.requestAnimationFrame(anchorChangeHandler);
window.addEventListener('hashchange', anchorChangeHandler);
}
function setupGoToTop() {
const wrapper = document.querySelector('.wrapper');
const goToTop = document.querySelector('.go-top');
goToTop.addEventListener('click', e => {
wrapper.scrollTop = 0;
wrapper.scrollLeft = 0;
});
}
function randomChoice(arr) {
return arr[Math.floor(Math.random() * arr.length)];
}
function addBannerContents(bannerElement, msg) {
bannerElement.innerHTML = '';
const containerElement = document.createElement('div');
containerElement.classList.add('container');
const titleElement = document.createElement('p');
titleElement.classList.add('title');
titleElement.innerText = msg.title;
containerElement.appendChild(titleElement);
for (const line of msg.body.split('\n')) {
const subtitleElement = document.createElement('div');
subtitleElement.classList.add('subtitle');
subtitleElement.innerHTML = line;
containerElement.appendChild(subtitleElement);
}
if (msg.action !== undefined) {
const actionElement = document.createElement('div');
actionElement.classList.add('action');
const actionInner = document.createElement('div');
actionInner.classList.add('action-inner');
actionInner.innerHTML = msg.action;
actionElement.appendChild(actionInner);
containerElement.appendChild(actionElement);
}
bannerElement.appendChild(containerElement);
const messageLinkElement = document.createElement('a');
messageLinkElement.classList.add('message-link');
messageLinkElement.href = msg.link;
messageLinkElement.setAttribute('target', '_blank');
bannerElement.appendChild(messageLinkElement);
}
function updateMessageBanner() {
fetch('/static/messages.json?v=1')
.then(r => r.json())
.then(messages => {
const msg = randomChoice(messages);
const desktopBanner = document.querySelector('.message-banner-desktop');
addBannerContents(desktopBanner, msg.desktop);
});
}
function cycleBanner(delay=500) {
fetch('/static/messages.json?v=1')
.then(r => r.json())
.then(messages => {
cycleBannerWithData(messages, delay);
});
}
function sleep(duration) {
return new Promise(resolve => setTimeout(resolve, duration));
}
async function cycleBannerWithData(data, delay=500) {
for (const msg of data) {
const desktopBanner = document.querySelector('.message-banner-desktop');
addBannerContents(desktopBanner, msg.desktop);
await sleep(delay);
}
console.log("cycle finished");
}
document.addEventListener('DOMContentLoaded', _ => {
updateMessageBanner();
setupVersionsFilter();
setupVersionsTree();
setupSidebarSwitch();
setupLineRangeHandlers();
setupAutoscrollingPrevention();
setupAnchorOffsetHandler();
setupGoToTop();
document.getElementById('clear-search').addEventListener('click',
_ => document.getElementById('search-input').value = ''
);
});