Debian Codegraph @

crates/mdbook-html/front-end/templates/toc.js.hbs

raw
1 // Populate the sidebar
2 //
3 // This is a script, and not included directly in the page, to control the total size of the book.
4 // The TOC contains an entry for each page, so if each page includes a copy of the TOC,
5 // the total size of the page becomes O(n**2).
6 class MDBookSidebarScrollbox extends HTMLElement {
7 constructor() {
8 super();
9 }
10 connectedCallback() {
11 this.innerHTML = '{{#toc}}{{/toc}}';
12 // Set the current, active page, and reveal it if it's hidden
13 let current_page = document.location.href.toString().split('#')[0].split('?')[0];
14 if (current_page.endsWith('/')) {
15 current_page += 'index.html';
16 }
17 const links = Array.prototype.slice.call(this.querySelectorAll('a'));
18 const l = links.length;
19 for (let i = 0; i < l; ++i) {
20 const link = links[i];
21 const href = link.getAttribute('href');
22 if (href && !href.startsWith('#') && !/^(?:[a-z+]+:)?\/\//.test(href)) {
23 link.href = path_to_root + href;
24 }
25 // The 'index' page is supposed to alias the first chapter in the book.
26 // Check both with and without the '.html' suffix to be robust against pretty URLs
27 if (link.href.replace(/\.html$/, '') === current_page.replace(/\.html$/, '')
28 || i === 0
29 && path_to_root === ''
30 && current_page.endsWith('/index.html')) {
31 link.classList.add('active');
32 let parent = link.parentElement;
33 while (parent) {
34 if (parent.tagName === 'LI' && parent.classList.contains('chapter-item')) {
35 parent.classList.add('expanded');
36 }
37 parent = parent.parentElement;
38 }
39 }
40 }
41 // Track and set sidebar scroll position
42 this.addEventListener('click', e => {
43 if (e.target.tagName === 'A') {
44 const clientRect = e.target.getBoundingClientRect();
45 const sidebarRect = this.getBoundingClientRect();
46 sessionStorage.setItem('sidebar-scroll-offset', clientRect.top - sidebarRect.top);
47 }
48 }, { passive: true });
49 const sidebarScrollOffset = sessionStorage.getItem('sidebar-scroll-offset');
50 sessionStorage.removeItem('sidebar-scroll-offset');
51 if (sidebarScrollOffset !== null) {
52 // preserve sidebar scroll position when navigating via links within sidebar
53 const activeSection = this.querySelector('.active');
54 if (activeSection) {
55 const clientRect = activeSection.getBoundingClientRect();
56 const sidebarRect = this.getBoundingClientRect();
57 const currentOffset = clientRect.top - sidebarRect.top;
58 this.scrollTop += currentOffset - parseFloat(sidebarScrollOffset);
59 }
60 } else {
61 // scroll sidebar to current active section when navigating via
62 // 'next/previous chapter' buttons
63 const activeSection = document.querySelector('#mdbook-sidebar .active');
64 if (activeSection) {
65 activeSection.scrollIntoView({ block: 'center' });
66 }
67 }
68 // Toggle buttons
69 const sidebarAnchorToggles = document.querySelectorAll('.chapter-fold-toggle');
70 function toggleSection(ev) {
71 ev.currentTarget.parentElement.parentElement.classList.toggle('expanded');
72 }
73 Array.from(sidebarAnchorToggles).forEach(el => {
74 el.addEventListener('click', toggleSection);
75 });
76 }
77 }
78 window.customElements.define('mdbook-sidebar-scrollbox', MDBookSidebarScrollbox);
79
80 {{#if sidebar_header_nav}}
81
82 // ---------------------------------------------------------------------------
83 // Support for dynamically adding headers to the sidebar.
84
85 (function() {
86 // This is used to detect which direction the page has scrolled since the
87 // last scroll event.
88 let lastKnownScrollPosition = 0;
89 // This is the threshold in px from the top of the screen where it will
90 // consider a header the "current" header when scrolling down.
91 const defaultDownThreshold = 150;
92 // Same as defaultDownThreshold, except when scrolling up.
93 const defaultUpThreshold = 300;
94 // The threshold is a virtual horizontal line on the screen where it
95 // considers the "current" header to be above the line. The threshold is
96 // modified dynamically to handle headers that are near the bottom of the
97 // screen, and to slightly offset the behavior when scrolling up vs down.
98 let threshold = defaultDownThreshold;
99 // This is used to disable updates while scrolling. This is needed when
100 // clicking the header in the sidebar, which triggers a scroll event. It
101 // is somewhat finicky to detect when the scroll has finished, so this
102 // uses a relatively dumb system of disabling scroll updates for a short
103 // time after the click.
104 let disableScroll = false;
105 // Array of header elements on the page.
106 let headers;
107 // Array of li elements that are initially collapsed headers in the sidebar.
108 // I'm not sure why eslint seems to have a false positive here.
109 // eslint-disable-next-line prefer-const
110 let headerToggles = [];
111 // This is a debugging tool for the threshold which you can enable in the console.
112 let thresholdDebug = false;
113
114 // Updates the threshold based on the scroll position.
115 function updateThreshold() {
116 const scrollTop = window.pageYOffset || document.documentElement.scrollTop;
117 const windowHeight = window.innerHeight;
118 const documentHeight = document.documentElement.scrollHeight;
119
120 // The number of pixels below the viewport, at most documentHeight.
121 // This is used to push the threshold down to the bottom of the page
122 // as the user scrolls towards the bottom.
123 const pixelsBelow = Math.max(0, documentHeight - (scrollTop + windowHeight));
124 // The number of pixels above the viewport, at least defaultDownThreshold.
125 // Similar to pixelsBelow, this is used to push the threshold back towards
126 // the top when reaching the top of the page.
127 const pixelsAbove = Math.max(0, defaultDownThreshold - scrollTop);
128 // How much the threshold should be offset once it gets close to the
129 // bottom of the page.
130 const bottomAdd = Math.max(0, windowHeight - pixelsBelow - defaultDownThreshold);
131 let adjustedBottomAdd = bottomAdd;
132
133 // Adjusts bottomAdd for a small document. The calculation above
134 // assumes the document is at least twice the windowheight in size. If
135 // it is less than that, then bottomAdd needs to be shrunk
136 // proportional to the difference in size.
137 if (documentHeight < windowHeight * 2) {
138 const maxPixelsBelow = documentHeight - windowHeight;
139 const t = 1 - pixelsBelow / Math.max(1, maxPixelsBelow);
140 const clamp = Math.max(0, Math.min(1, t));
141 adjustedBottomAdd *= clamp;
142 }
143
144 let scrollingDown = true;
145 if (scrollTop < lastKnownScrollPosition) {
146 scrollingDown = false;
147 }
148
149 if (scrollingDown) {
150 // When scrolling down, move the threshold up towards the default
151 // downwards threshold position. If near the bottom of the page,
152 // adjustedBottomAdd will offset the threshold towards the bottom
153 // of the page.
154 const amountScrolledDown = scrollTop - lastKnownScrollPosition;
155 const adjustedDefault = defaultDownThreshold + adjustedBottomAdd;
156 threshold = Math.max(adjustedDefault, threshold - amountScrolledDown);
157 } else {
158 // When scrolling up, move the threshold down towards the default
159 // upwards threshold position. If near the bottom of the page,
160 // quickly transition the threshold back up where it normally
161 // belongs.
162 const amountScrolledUp = lastKnownScrollPosition - scrollTop;
163 const adjustedDefault = defaultUpThreshold - pixelsAbove
164 + Math.max(0, adjustedBottomAdd - defaultDownThreshold);
165 threshold = Math.min(adjustedDefault, threshold + amountScrolledUp);
166 }
167
168 if (documentHeight <= windowHeight) {
169 threshold = 0;
170 }
171
172 if (thresholdDebug) {
173 const id = 'mdbook-threshold-debug-data';
174 let data = document.getElementById(id);
175 if (data === null) {
176 data = document.createElement('div');
177 data.id = id;
178 data.style.cssText = `
179 position: fixed;
180 top: 50px;
181 right: 10px;
182 background-color: 0xeeeeee;
183 z-index: 9999;
184 pointer-events: none;
185 `;
186 document.body.appendChild(data);
187 }
188 data.innerHTML = `
189 <table>
190 <tr><td>documentHeight</td><td>${documentHeight.toFixed(1)}</td></tr>
191 <tr><td>windowHeight</td><td>${windowHeight.toFixed(1)}</td></tr>
192 <tr><td>scrollTop</td><td>${scrollTop.toFixed(1)}</td></tr>
193 <tr><td>pixelsAbove</td><td>${pixelsAbove.toFixed(1)}</td></tr>
194 <tr><td>pixelsBelow</td><td>${pixelsBelow.toFixed(1)}</td></tr>
195 <tr><td>bottomAdd</td><td>${bottomAdd.toFixed(1)}</td></tr>
196 <tr><td>adjustedBottomAdd</td><td>${adjustedBottomAdd.toFixed(1)}</td></tr>
197 <tr><td>scrollingDown</td><td>${scrollingDown}</td></tr>
198 <tr><td>threshold</td><td>${threshold.toFixed(1)}</td></tr>
199 </table>
200 `;
201 drawDebugLine();
202 }
203
204 lastKnownScrollPosition = scrollTop;
205 }
206
207 function drawDebugLine() {
208 if (!document.body) {
209 return;
210 }
211 const id = 'mdbook-threshold-debug-line';
212 const existingLine = document.getElementById(id);
213 if (existingLine) {
214 existingLine.remove();
215 }
216 const line = document.createElement('div');
217 line.id = id;
218 line.style.cssText = `
219 position: fixed;
220 top: ${threshold}px;
221 left: 0;
222 width: 100vw;
223 height: 2px;
224 background-color: red;
225 z-index: 9999;
226 pointer-events: none;
227 `;
228 document.body.appendChild(line);
229 }
230
231 function mdbookEnableThresholdDebug() {
232 thresholdDebug = true;
233 updateThreshold();
234 drawDebugLine();
235 }
236
237 window.mdbookEnableThresholdDebug = mdbookEnableThresholdDebug;
238
239 // Updates which headers in the sidebar should be expanded. If the current
240 // header is inside a collapsed group, then it, and all its parents should
241 // be expanded.
242 function updateHeaderExpanded(currentA) {
243 // Add expanded to all header-item li ancestors.
244 let current = currentA.parentElement;
245 while (current) {
246 if (current.tagName === 'LI' && current.classList.contains('header-item')) {
247 current.classList.add('expanded');
248 }
249 current = current.parentElement;
250 }
251 }
252
253 // Updates which header is marked as the "current" header in the sidebar.
254 // This is done with a virtual Y threshold, where headers at or below
255 // that line will be considered the current one.
256 function updateCurrentHeader() {
257 if (!headers || !headers.length) {
258 return;
259 }
260
261 // Reset the classes, which will be rebuilt below.
262 const els = document.getElementsByClassName('current-header');
263 for (const el of els) {
264 el.classList.remove('current-header');
265 }
266 for (const toggle of headerToggles) {
267 toggle.classList.remove('expanded');
268 }
269
270 // Find the last header that is above the threshold.
271 let lastHeader = null;
272 for (const header of headers) {
273 const rect = header.getBoundingClientRect();
274 if (rect.top <= threshold) {
275 lastHeader = header;
276 } else {
277 break;
278 }
279 }
280 if (lastHeader === null) {
281 lastHeader = headers[0];
282 const rect = lastHeader.getBoundingClientRect();
283 const windowHeight = window.innerHeight;
284 if (rect.top >= windowHeight) {
285 return;
286 }
287 }
288
289 // Get the anchor in the summary.
290 const href = '#' + lastHeader.id;
291 const a = [...document.querySelectorAll('.header-in-summary')]
292 .find(element => element.getAttribute('href') === href);
293 if (!a) {
294 return;
295 }
296
297 a.classList.add('current-header');
298
299 updateHeaderExpanded(a);
300 }
301
302 // Updates which header is "current" based on the threshold line.
303 function reloadCurrentHeader() {
304 if (disableScroll) {
305 return;
306 }
307 updateThreshold();
308 updateCurrentHeader();
309 }
310
311
312 // When clicking on a header in the sidebar, this adjusts the threshold so
313 // that it is located next to the header. This is so that header becomes
314 // "current".
315 function headerThresholdClick(event) {
316 // See disableScroll description why this is done.
317 disableScroll = true;
318 setTimeout(() => {
319 disableScroll = false;
320 }, 100);
321 // requestAnimationFrame is used to delay the update of the "current"
322 // header until after the scroll is done, and the header is in the new
323 // position.
324 requestAnimationFrame(() => {
325 requestAnimationFrame(() => {
326 // Closest is needed because if it has child elements like <code>.
327 const a = event.target.closest('a');
328 const href = a.getAttribute('href');
329 const targetId = href.substring(1);
330 const targetElement = document.getElementById(targetId);
331 if (targetElement) {
332 threshold = targetElement.getBoundingClientRect().bottom;
333 updateCurrentHeader();
334 }
335 });
336 });
337 }
338
339 // Takes the nodes from the given head and copies them over to the
340 // destination, along with some filtering.
341 function filterHeader(source, dest) {
342 const clone = source.cloneNode(true);
343 clone.querySelectorAll('mark').forEach(mark => {
344 mark.replaceWith(...mark.childNodes);
345 });
346 dest.append(...clone.childNodes);
347 }
348
349 // Scans page for headers and adds them to the sidebar.
350 document.addEventListener('DOMContentLoaded', function() {
351 const activeSection = document.querySelector('#mdbook-sidebar .active');
352 if (activeSection === null) {
353 return;
354 }
355
356 const main = document.getElementsByTagName('main')[0];
357 headers = Array.from(main.querySelectorAll('h2, h3, h4, h5, h6'))
358 .filter(h => h.id !== '' && h.children.length && h.children[0].tagName === 'A');
359
360 if (headers.length === 0) {
361 return;
362 }
363
364 // Build a tree of headers in the sidebar.
365
366 const stack = [];
367
368 const firstLevel = parseInt(headers[0].tagName.charAt(1));
369 for (let i = 1; i < firstLevel; i++) {
370 const ol = document.createElement('ol');
371 ol.classList.add('section');
372 if (stack.length > 0) {
373 stack[stack.length - 1].ol.appendChild(ol);
374 }
375 stack.push({level: i + 1, ol: ol});
376 }
377
378 // The level where it will start folding deeply nested headers.
379 const foldLevel = 3;
380
381 for (let i = 0; i < headers.length; i++) {
382 const header = headers[i];
383 const level = parseInt(header.tagName.charAt(1));
384
385 const currentLevel = stack[stack.length - 1].level;
386 if (level > currentLevel) {
387 // Begin nesting to this level.
388 for (let nextLevel = currentLevel + 1; nextLevel <= level; nextLevel++) {
389 const ol = document.createElement('ol');
390 ol.classList.add('section');
391 const last = stack[stack.length - 1];
392 const lastChild = last.ol.lastChild;
393 // Handle the case where jumping more than one nesting
394 // level, which doesn't have a list item to place this new
395 // list inside of.
396 if (lastChild) {
397 lastChild.appendChild(ol);
398 } else {
399 last.ol.appendChild(ol);
400 }
401 stack.push({level: nextLevel, ol: ol});
402 }
403 } else if (level < currentLevel) {
404 while (stack.length > 1 && stack[stack.length - 1].level > level) {
405 stack.pop();
406 }
407 }
408
409 const li = document.createElement('li');
410 li.classList.add('header-item');
411 li.classList.add('expanded');
412 if (level < foldLevel) {
413 li.classList.add('expanded');
414 }
415 const span = document.createElement('span');
416 span.classList.add('chapter-link-wrapper');
417 const a = document.createElement('a');
418 span.appendChild(a);
419 a.href = '#' + header.id;
420 a.classList.add('header-in-summary');
421 filterHeader(header.children[0], a);
422 a.addEventListener('click', headerThresholdClick);
423 const nextHeader = headers[i + 1];
424 if (nextHeader !== undefined) {
425 const nextLevel = parseInt(nextHeader.tagName.charAt(1));
426 if (nextLevel > level && level >= foldLevel) {
427 const toggle = document.createElement('a');
428 toggle.classList.add('chapter-fold-toggle');
429 toggle.classList.add('header-toggle');
430 toggle.addEventListener('click', () => {
431 li.classList.toggle('expanded');
432 });
433 const toggleDiv = document.createElement('div');
434 toggleDiv.textContent = '❱';
435 toggle.appendChild(toggleDiv);
436 span.appendChild(toggle);
437 headerToggles.push(li);
438 }
439 }
440 li.appendChild(span);
441
442 const currentParent = stack[stack.length - 1];
443 currentParent.ol.appendChild(li);
444 }
445
446 const onThisPage = document.createElement('div');
447 onThisPage.classList.add('on-this-page');
448 onThisPage.append(stack[0].ol);
449 const activeItemSpan = activeSection.parentElement;
450 activeItemSpan.after(onThisPage);
451 });
452
453 document.addEventListener('DOMContentLoaded', reloadCurrentHeader);
454 document.addEventListener('scroll', reloadCurrentHeader, { passive: true });
455 })();
456
457 {{/if}}