|
| 1 | +(() => { |
| 2 | + const initCollapsibleToc = () => { |
| 3 | + const tocNavs = document.querySelectorAll( |
| 4 | + '[data-md-component="toc"], .md-nav--secondary', |
| 5 | + ); |
| 6 | + if (!tocNavs.length) return; |
| 7 | + |
| 8 | + tocNavs.forEach((tocNav) => { |
| 9 | + tocNav.querySelectorAll(".toc-toggle").forEach((btn) => btn.remove()); |
| 10 | + tocNav |
| 11 | + .querySelectorAll(".toc-collapsible, .toc-open") |
| 12 | + .forEach((item) => |
| 13 | + item.classList.remove("toc-collapsible", "toc-open"), |
| 14 | + ); |
| 15 | + |
| 16 | + const list = tocNav.matches(".md-nav__list") |
| 17 | + ? tocNav |
| 18 | + : tocNav.querySelector(":scope > .md-nav__list"); |
| 19 | + if (!list) return; |
| 20 | + |
| 21 | + const topItems = list.querySelectorAll(":scope > .md-nav__item"); |
| 22 | + |
| 23 | + topItems.forEach((item) => { |
| 24 | + const subnav = item.querySelector( |
| 25 | + ":scope > nav.md-nav, :scope > ul.md-nav__list", |
| 26 | + ); |
| 27 | + if (!subnav) return; |
| 28 | + |
| 29 | + item.classList.add("toc-collapsible"); |
| 30 | + |
| 31 | + const link = item.querySelector(":scope > .md-nav__link"); |
| 32 | + if (!link) return; |
| 33 | + |
| 34 | + const button = document.createElement("button"); |
| 35 | + button.type = "button"; |
| 36 | + button.className = "toc-toggle"; |
| 37 | + button.setAttribute("aria-label", "Toggle section"); |
| 38 | + |
| 39 | + const setExpanded = (expanded) => { |
| 40 | + item.classList.toggle("toc-open", expanded); |
| 41 | + button.setAttribute("aria-expanded", expanded ? "true" : "false"); |
| 42 | + }; |
| 43 | + |
| 44 | + link.after(button); |
| 45 | + |
| 46 | + if (item.querySelector(".md-nav__link--active")) { |
| 47 | + setExpanded(true); |
| 48 | + } else { |
| 49 | + setExpanded(false); |
| 50 | + } |
| 51 | + |
| 52 | + button.addEventListener("click", (event) => { |
| 53 | + event.preventDefault(); |
| 54 | + event.stopPropagation(); |
| 55 | + setExpanded(!item.classList.contains("toc-open")); |
| 56 | + }); |
| 57 | + }); |
| 58 | + }); |
| 59 | + }; |
| 60 | + |
| 61 | + if (window.document$ && typeof window.document$.subscribe === "function") { |
| 62 | + window.document$.subscribe(initCollapsibleToc); |
| 63 | + } else { |
| 64 | + document.addEventListener("DOMContentLoaded", initCollapsibleToc); |
| 65 | + } |
| 66 | +})(); |
0 commit comments