@@ -42,6 +42,7 @@ class MDBookSidebarScrollbox extends HTMLElement {
4242 }
4343 }
4444 }
45+ updateChapterNavigation(links);
4546 // Track and set sidebar scroll position
4647 this.addEventListener('click', function(e) {
4748 if (e.target.tagName === 'A') {
@@ -83,3 +84,84 @@ class MDBookSidebarScrollbox extends HTMLElement {
8384 }
8485}
8586window.customElements.define("mdbook-sidebar-scrollbox", MDBookSidebarScrollbox);
87+
88+ function normalizeChapterUrl(url) {
89+ try {
90+ var normalized = new URL(url, document.location.href);
91+ normalized.hash = "";
92+ normalized.search = "";
93+ if (normalized.pathname.endsWith("/")) {
94+ normalized.pathname += "index.html";
95+ }
96+ return normalized.href;
97+ } catch (_) {
98+ return "";
99+ }
100+ }
101+
102+ function setChapterNavigationLink(selector, chapter) {
103+ var link = document.querySelector(selector);
104+ if (!link) {
105+ return;
106+ }
107+
108+ if (!chapter) {
109+ link.hidden = true;
110+ link.removeAttribute("href");
111+ return;
112+ }
113+
114+ link.href = chapter.href;
115+ link.hidden = false;
116+
117+ var label = link.querySelector(".chapter-nav-label") || link.querySelector("span");
118+ if (label) {
119+ label.textContent = chapter.title;
120+ }
121+ }
122+
123+ function updateChapterNavigation(links) {
124+ var current = normalizeChapterUrl(document.location.href);
125+ var seen = Object.create(null);
126+ var chapters = [];
127+
128+ links.forEach(function (link) {
129+ var rawHref = link.getAttribute("href");
130+ if (!rawHref || rawHref.startsWith("#") || link.classList.contains("external-link")) {
131+ return;
132+ }
133+
134+ var url;
135+ try {
136+ url = new URL(link.href, document.location.href);
137+ } catch (_) {
138+ return;
139+ }
140+ if (url.origin !== document.location.origin && url.protocol !== "file:") {
141+ return;
142+ }
143+
144+ var normalized = normalizeChapterUrl(url.href);
145+ if (!normalized || seen[normalized]) {
146+ return;
147+ }
148+ seen[normalized] = true;
149+
150+ chapters.push({
151+ href: link.href,
152+ key: normalized,
153+ title: link.textContent.trim()
154+ });
155+ });
156+
157+ var index = chapters.findIndex(function (chapter) {
158+ return chapter.key === current;
159+ });
160+ var previous = index > 0 ? chapters[index - 1] : null;
161+ var next = index >= 0 && index < chapters.length - 1 ? chapters[index + 1] : null;
162+
163+ setChapterNavigationLink(".mobile-nav-chapters.previous", previous);
164+ setChapterNavigationLink(".nav-chapters.previous", previous);
165+ setChapterNavigationLink(".mobile-nav-chapters.next", next);
166+ setChapterNavigationLink(".nav-chapters.next", next);
167+ }
0 commit comments