removing author and cleaning js / css
This commit is contained in:
19
assets/scripts/ui/copy-buttons.js
Normal file
19
assets/scripts/ui/copy-buttons.js
Normal file
@@ -0,0 +1,19 @@
|
||||
/* Event listener function for the COPY BUTTON */
|
||||
document.addEventListener("DOMContentLoaded", function () {
|
||||
document.querySelectorAll("pre.src").forEach(function (codeBlock) {
|
||||
const button = document.createElement("button");
|
||||
button.innerText = "Copy";
|
||||
button.className = "copy-btn";
|
||||
|
||||
// Append button inside <pre>
|
||||
codeBlock.appendChild(button);
|
||||
|
||||
button.addEventListener("click", function () {
|
||||
const text = codeBlock.innerText.replace(button.innerText, ""); // exclude button text
|
||||
navigator.clipboard.writeText(text.trim()).then(() => {
|
||||
button.innerText = "Copied!";
|
||||
setTimeout(() => (button.innerText = "Copy"), 1500);
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
38
assets/scripts/ui/countdown.js
Normal file
38
assets/scripts/ui/countdown.js
Normal file
@@ -0,0 +1,38 @@
|
||||
// Simple, timezone-safe if you pass UTC (…Z) in the datetime
|
||||
document.addEventListener('DOMContentLoaded', () => {
|
||||
const els = document.querySelectorAll('time.countdown');
|
||||
if (!els.length) return;
|
||||
|
||||
const plural = (n, w) => `${n} ${w}${n === 1 ? '' : 's'}`;
|
||||
|
||||
const render = (el) => {
|
||||
const raw = el.getAttribute('datetime');
|
||||
const label = el.dataset.label || '';
|
||||
const target = new Date(raw); // Prefer ISO like 2025-12-31T00:00:00Z
|
||||
if (isNaN(target)) { el.textContent = '—'; return; }
|
||||
|
||||
const now = new Date();
|
||||
let diff = target - now;
|
||||
|
||||
if (diff <= 0) {
|
||||
el.textContent = `${label ? label + ' ' : ''}today`;
|
||||
el.classList.add('expired');
|
||||
return;
|
||||
}
|
||||
|
||||
const d = Math.floor(diff / 86400000); diff -= d * 86400000;
|
||||
const h = Math.floor(diff / 3600000); diff -= h * 3600000;
|
||||
const m = Math.floor(diff / 60000); diff -= m * 60000;
|
||||
const s = Math.floor(diff / 1000);
|
||||
|
||||
const pieces = [];
|
||||
if (d) pieces.push(plural(d, 'day'));
|
||||
pieces.push(`${h}h ${m}m ${s}s`);
|
||||
|
||||
el.textContent = `${label ? label + ' in : ' : ''}${pieces.join(' ')}`;
|
||||
};
|
||||
|
||||
const tick = () => els.forEach(render);
|
||||
tick();
|
||||
setInterval(tick, 1000); // update every second
|
||||
});
|
||||
50
assets/scripts/ui/footnote-sidenotes.js
Normal file
50
assets/scripts/ui/footnote-sidenotes.js
Normal file
@@ -0,0 +1,50 @@
|
||||
/* Event listener for footnotes and sidenotes*/
|
||||
document.addEventListener("DOMContentLoaded", () => {
|
||||
document.querySelectorAll('a.footref[href^="#fn"]').forEach(ref => {
|
||||
const sup = ref.closest("sup") || ref;
|
||||
// idempotent: don't insert twice
|
||||
if (sup.nextElementSibling && sup.nextElementSibling.classList?.contains("footnote-sidenote")) return;
|
||||
|
||||
const targetId = ref.getAttribute("href").replace(/^#/, ""); // works for fn.2 or fn2
|
||||
|
||||
const anchor = document.getElementById(targetId);
|
||||
if (!anchor) return;
|
||||
|
||||
const footdef = anchor.closest(".footdef") || anchor.parentElement;
|
||||
if (!footdef) return;
|
||||
|
||||
// 1) Prefer leaf paragraphs to avoid div+p duplication
|
||||
let paras = footdef.querySelectorAll("p.footpara");
|
||||
if (!paras.length) {
|
||||
// fallback: any .footpara elements that don't contain another .footpara
|
||||
paras = footdef.querySelectorAll(".footpara:not(:has(.footpara))");
|
||||
}
|
||||
|
||||
// 2) Build HTML, de-duplicating by text content
|
||||
let parts = [];
|
||||
if (paras.length) {
|
||||
const seen = new Set();
|
||||
parts = Array.from(paras).map(p => {
|
||||
const txt = p.textContent.trim().replace(/\s+/g, " ");
|
||||
if (seen.has(txt)) return "";
|
||||
seen.add(txt);
|
||||
return p.innerHTML.trim();
|
||||
}).filter(Boolean);
|
||||
}
|
||||
|
||||
// 3) Fallback: clean full block if no paras found
|
||||
if (!parts.length) {
|
||||
const clone = footdef.cloneNode(true);
|
||||
clone.querySelectorAll("sup.footnum, a[role='doc-backlink']").forEach(n => n.remove());
|
||||
parts = [clone.innerHTML.trim()];
|
||||
}
|
||||
|
||||
// 4) Insert the sidenote
|
||||
const sn = document.createElement("span");
|
||||
sn.className = "sidenote footnote-sidenote";
|
||||
sn.setAttribute("data-fn", (ref.textContent || "").trim());
|
||||
sn.innerHTML = parts.join(" ");
|
||||
|
||||
sup.insertAdjacentElement("afterend", sn);
|
||||
});
|
||||
});
|
||||
315
assets/scripts/ui/gallery-init.js
Normal file
315
assets/scripts/ui/gallery-init.js
Normal file
@@ -0,0 +1,315 @@
|
||||
document.addEventListener('DOMContentLoaded', () => {
|
||||
if (typeof window.BiggerPicture !== 'function') {
|
||||
console.error('[gallery-init] BiggerPicture not found. Check script path.');
|
||||
return;
|
||||
}
|
||||
const VIDEO_EXTENSIONS = ['mp4', 'webm', 'mov', 'm4v', 'ogv'];
|
||||
|
||||
const isVideo = (href) => {
|
||||
if (!href) return false;
|
||||
href = href.toLowerCase();
|
||||
return VIDEO_EXTENSIONS.some(ext => href.endsWith('.' + ext));
|
||||
};
|
||||
|
||||
// 1b) Convert MP4 links into inline <video> players
|
||||
// Convert video links into inline <video> players BUT keep the <a>
|
||||
const videoLinks = document.querySelectorAll('a[href]');
|
||||
videoLinks.forEach(a => {
|
||||
const href = a.getAttribute("href");
|
||||
if (!isVideo(href)) return;
|
||||
|
||||
const video = document.createElement("video");
|
||||
video.controls = true;
|
||||
video.preload = "metadata";
|
||||
video.style.maxWidth = "100%";
|
||||
video.style.borderRadius = "6px";
|
||||
|
||||
const source = document.createElement("source");
|
||||
source.src = href;
|
||||
source.type = "video/" + href.split('.').pop(); // guesses correct mime
|
||||
video.appendChild(source);
|
||||
|
||||
// Replace the link with the inline video
|
||||
a.parentNode.replaceChild(video, a);
|
||||
});
|
||||
|
||||
// 1) Wrap Org-exported images so they’re clickable
|
||||
const imgs = document.querySelectorAll('.figure img, img.org-svg');
|
||||
imgs.forEach((img) => {
|
||||
if (img.closest('a')) return; // already wrapped
|
||||
const a = document.createElement('a');
|
||||
const href = img.currentSrc || img.src;
|
||||
a.href = href;
|
||||
a.dataset.img = href; // lets BP pre-size/raster slides
|
||||
a.dataset.alt = img.alt || '';
|
||||
const setDims = () => {
|
||||
a.dataset.width = img.naturalWidth || img.width || 1920;
|
||||
a.dataset.height = img.naturalHeight || img.height || 1080;
|
||||
};
|
||||
if (img.complete) setDims(); else img.addEventListener('load', setDims);
|
||||
img.style.cursor = 'zoom-in';
|
||||
img.parentElement.insertBefore(a, img);
|
||||
a.appendChild(img);
|
||||
});
|
||||
|
||||
// 2) One global BP instance
|
||||
const bp = BiggerPicture({ target: document.body });
|
||||
|
||||
// SVG pan/zoom handle
|
||||
let activePanZoom = null;
|
||||
const destroyPanZoom = () => { try { activePanZoom?.destroy(); } catch(_){} activePanZoom = null; };
|
||||
|
||||
// Simple rotate state (for non-SVG images)
|
||||
let activeContainer = null;
|
||||
let currentRotation = 0;
|
||||
let rotateControls = null;
|
||||
|
||||
// 3) Build galleries per content container
|
||||
const containers = document.querySelectorAll('main, article, .content, body');
|
||||
containers.forEach((container) => {
|
||||
const links = Array.from(container.querySelectorAll(
|
||||
'.figure a, a:has(img.org-svg), a[href$=".mp4"], a[href$=".webm"], a[href$=".mov"], a[href$=".m4v"], a[href$=".ogv"]'
|
||||
));
|
||||
if (!links.length) return;
|
||||
|
||||
// Start the lightbox on click
|
||||
links.forEach((link, index) => {
|
||||
link.addEventListener('click', (e) => {
|
||||
e.preventDefault();
|
||||
document.querySelectorAll(".theme-toggle").forEach(el => {
|
||||
el.classList.add("hidden");
|
||||
});
|
||||
|
||||
bp.open({
|
||||
// IMPORTANT: pass the anchor ELEMENTS, not custom objects
|
||||
items: links,
|
||||
el: link,
|
||||
caption: (el) => el.querySelector('img')?.alt || el.title || '',
|
||||
maxZoom: 40, // for raster images (PNG/JPG); SVG handled separately
|
||||
|
||||
// Fade-out polish + cleanup
|
||||
onClose(containerEl) {
|
||||
destroyPanZoom();
|
||||
teardownRotation();
|
||||
if (containerEl) containerEl.classList.add('bp-fadeout');
|
||||
const themeToggle = document.querySelector(".theme-toggle");
|
||||
if (themeToggle) {
|
||||
themeToggle.classList.remove("hidden");
|
||||
}
|
||||
},
|
||||
|
||||
// Called once after open and on every slide change
|
||||
//onOpen(containerEl) { setupRotation(containerEl); enhanceSVG(containerEl); }
|
||||
onOpen(containerEl) {
|
||||
const linkEl = bp.currItem;
|
||||
const href = linkEl?.href || "";
|
||||
|
||||
if (href.endsWith(".mp4")) {
|
||||
// Turn off image rotation (not applicable for video)
|
||||
teardownRotation();
|
||||
|
||||
const htmlLayer = containerEl.querySelector(".bp-html");
|
||||
const imgLayer = containerEl.querySelector(".bp-img");
|
||||
|
||||
if (!htmlLayer) return;
|
||||
|
||||
// Hide the default image layer
|
||||
if (imgLayer) imgLayer.style.display = "none";
|
||||
|
||||
// Insert video player
|
||||
htmlLayer.innerHTML = `
|
||||
<video controls autoplay style="max-width:95vw; max-height:95vh">
|
||||
<source src="${href}" type="video/mp4">
|
||||
</video>
|
||||
`;
|
||||
|
||||
return; // Do not run image/SVG enhancements
|
||||
}
|
||||
|
||||
// Image behaviour
|
||||
setupRotation(containerEl);
|
||||
enhanceSVG(containerEl);
|
||||
} ,
|
||||
onUpdate(containerEl){ setupRotation(containerEl); enhanceSVG(containerEl); }
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
// 4) Simple rotate buttons for raster images
|
||||
function ensureRotateControls() {
|
||||
if (rotateControls) return rotateControls;
|
||||
|
||||
const wrapper = document.createElement('div');
|
||||
wrapper.className = 'bp-rotate-controls';
|
||||
Object.assign(wrapper.style, {
|
||||
position: 'fixed',
|
||||
bottom: '1.5rem',
|
||||
right: '1.5rem',
|
||||
display: 'flex',
|
||||
gap: '0.5rem',
|
||||
zIndex: '9999',
|
||||
pointerEvents: 'auto'
|
||||
});
|
||||
|
||||
const mkBtn = (label, title) => {
|
||||
const btn = document.createElement('button');
|
||||
btn.type = 'button';
|
||||
btn.textContent = label;
|
||||
btn.title = title;
|
||||
btn.setAttribute('aria-label', title);
|
||||
Object.assign(btn.style, {
|
||||
padding: '0.4rem 0.6rem',
|
||||
borderRadius: '999px',
|
||||
border: 'none',
|
||||
fontSize: '1.2rem',
|
||||
cursor: 'pointer',
|
||||
background: 'rgba(30,30,30,0.8)',
|
||||
color: '#fff'
|
||||
});
|
||||
return btn;
|
||||
};
|
||||
|
||||
const left = mkBtn('⟲', 'Rotate image 90° left');
|
||||
const right = mkBtn('⟳', 'Rotate image 90° right');
|
||||
|
||||
left.addEventListener('click', (e) => {
|
||||
e.stopPropagation(); // don’t close the lightbox
|
||||
if (!activeContainer) return;
|
||||
currentRotation = (currentRotation - 90 + 360) % 360;
|
||||
applyRotation();
|
||||
});
|
||||
|
||||
right.addEventListener('click', (e) => {
|
||||
e.stopPropagation();
|
||||
if (!activeContainer) return;
|
||||
currentRotation = (currentRotation + 90) % 360;
|
||||
applyRotation();
|
||||
});
|
||||
|
||||
wrapper.append(left, right);
|
||||
document.body.appendChild(wrapper);
|
||||
rotateControls = wrapper;
|
||||
return rotateControls;
|
||||
}
|
||||
|
||||
function ensureRotateWrapper() {
|
||||
if (!activeContainer) return null;
|
||||
|
||||
const imgRoot = activeContainer.querySelector('.bp-img');
|
||||
if (!imgRoot) return null;
|
||||
|
||||
let imgEl = imgRoot.querySelector('img');
|
||||
if (!imgEl) return null;
|
||||
|
||||
const src = (imgEl.currentSrc || imgEl.src || '').toLowerCase();
|
||||
// We only rotate raster images; SVGs are handled via svg-pan-zoom
|
||||
if (src.endsWith('.svg')) return null;
|
||||
|
||||
let wrapper = imgRoot.querySelector('.bp-rotate-wrapper');
|
||||
if (!wrapper) {
|
||||
wrapper = document.createElement('div');
|
||||
wrapper.className = 'bp-rotate-wrapper';
|
||||
wrapper.style.display = 'inline-block';
|
||||
wrapper.style.transformOrigin = 'center center';
|
||||
|
||||
imgRoot.appendChild(wrapper);
|
||||
wrapper.appendChild(imgEl);
|
||||
} else if (!wrapper.contains(imgEl)) {
|
||||
// Slide changed and BiggerPicture replaced the <img>
|
||||
wrapper.innerHTML = '';
|
||||
wrapper.appendChild(imgEl);
|
||||
}
|
||||
|
||||
return wrapper;
|
||||
}
|
||||
|
||||
function applyRotation() {
|
||||
const wrapper = ensureRotateWrapper();
|
||||
if (!wrapper) return;
|
||||
wrapper.style.transform = `rotate(${currentRotation}deg)`;
|
||||
}
|
||||
|
||||
function setupRotation(containerEl) {
|
||||
activeContainer = containerEl;
|
||||
currentRotation = 0;
|
||||
const controls = ensureRotateControls();
|
||||
controls.style.display = 'flex';
|
||||
applyRotation();
|
||||
}
|
||||
|
||||
function teardownRotation() {
|
||||
activeContainer = null;
|
||||
currentRotation = 0;
|
||||
if (rotateControls) {
|
||||
rotateControls.style.display = 'none';
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// 4) If current slide is an SVG, swap to inline + enable svg-pan-zoom
|
||||
async function enhanceSVG(containerEl) {
|
||||
try {
|
||||
destroyPanZoom();
|
||||
|
||||
const imgEl = containerEl.querySelector('.bp-img img');
|
||||
if (!imgEl) return;
|
||||
|
||||
const src = imgEl.currentSrc || imgEl.src || '';
|
||||
const isSVG = src.toLowerCase().endsWith('.svg');
|
||||
const htmlLayer = containerEl.querySelector('.bp-html');
|
||||
if (!isSVG || !htmlLayer) {
|
||||
// ensure any previous holder is removed and bitmap is visible
|
||||
const old = htmlLayer?.querySelector('.bp-svg-holder');
|
||||
if (old) old.remove();
|
||||
imgEl.style.visibility = '';
|
||||
return;
|
||||
}
|
||||
|
||||
// Create/clear holder
|
||||
let holder = htmlLayer.querySelector('.bp-svg-holder');
|
||||
if (!holder) {
|
||||
holder = document.createElement('div');
|
||||
holder.className = 'bp-svg-holder';
|
||||
holder.style.maxWidth = '95vw';
|
||||
holder.style.maxHeight = '95vh';
|
||||
htmlLayer.appendChild(holder);
|
||||
}
|
||||
holder.innerHTML = '';
|
||||
|
||||
// Hide the bitmap so only the inline SVG shows
|
||||
imgEl.style.visibility = 'hidden';
|
||||
|
||||
// Inline the SVG
|
||||
const res = await fetch(src, { cache: 'force-cache' });
|
||||
const text = await res.text();
|
||||
holder.innerHTML = text;
|
||||
|
||||
const svg = holder.querySelector('svg');
|
||||
if (!svg) { imgEl.style.visibility = ''; return; }
|
||||
|
||||
svg.style.maxWidth = '95vw';
|
||||
svg.style.maxHeight = '95vh';
|
||||
svg.style.display = 'block';
|
||||
|
||||
if (typeof window.svgPanZoom === 'function') {
|
||||
activePanZoom = svgPanZoom(svg, {
|
||||
zoomEnabled: true,
|
||||
controlIconsEnabled: true,
|
||||
fit: true,
|
||||
center: true,
|
||||
minZoom: 0.05,
|
||||
maxZoom: 400, // effectively "unlimited"
|
||||
zoomScaleSensitivity: 0.25,
|
||||
dblClickZoomEnabled: true
|
||||
});
|
||||
// Keep wheel inside lightbox
|
||||
holder.addEventListener('wheel', (e) => e.stopPropagation(), { passive: true });
|
||||
} else {
|
||||
console.warn('[gallery-init] svg-pan-zoom not loaded');
|
||||
}
|
||||
} catch (err) {
|
||||
console.error('[gallery-init] SVG enhance failed:', err);
|
||||
}
|
||||
}
|
||||
});
|
||||
101
assets/scripts/ui/mermaid-diagrams.js
Normal file
101
assets/scripts/ui/mermaid-diagrams.js
Normal file
@@ -0,0 +1,101 @@
|
||||
// Make Mermaid diagrams use the active site theme and zoom controls.
|
||||
(function () {
|
||||
function cssVar(name, fallback) {
|
||||
const value = getComputedStyle(document.documentElement).getPropertyValue(name).trim();
|
||||
return value || fallback;
|
||||
}
|
||||
|
||||
function mermaidConfig() {
|
||||
return {
|
||||
startOnLoad: false,
|
||||
theme: "base",
|
||||
themeVariables: {
|
||||
background: cssVar("--bg", "#faf9f6"),
|
||||
mainBkg: cssVar("--surface", "#ffffff"),
|
||||
primaryColor: cssVar("--surface", "#ffffff"),
|
||||
primaryTextColor: cssVar("--fg", "#000000"),
|
||||
primaryBorderColor: cssVar("--accent", "#2563eb"),
|
||||
secondaryColor: cssVar("--surface-soft", "#f3f1eb"),
|
||||
tertiaryColor: cssVar("--bg", "#faf9f6"),
|
||||
clusterBkg: cssVar("--surface-soft", "#f3f1eb"),
|
||||
clusterBorder: cssVar("--border", "#d7d7d7"),
|
||||
lineColor: cssVar("--border", "#d7d7d7"),
|
||||
textColor: cssVar("--fg", "#000000"),
|
||||
edgeLabelBackground: cssVar("--surface", "#ffffff"),
|
||||
fontFamily: cssVar("--font-body", "Noto, system-ui, sans-serif")
|
||||
},
|
||||
flowchart: {
|
||||
htmlLabels: true,
|
||||
curve: "basis"
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
function decodeMermaidSource(source) {
|
||||
const textarea = document.createElement("textarea");
|
||||
textarea.innerHTML = source;
|
||||
return textarea.value.trim();
|
||||
}
|
||||
|
||||
async function renderMermaid() {
|
||||
if (!window.mermaid) return;
|
||||
const diagrams = document.querySelectorAll(".mermaid");
|
||||
if (!diagrams.length) return;
|
||||
|
||||
diagrams.forEach((el) => {
|
||||
if (!el.dataset.source) {
|
||||
el.dataset.source = decodeMermaidSource(el.textContent || el.innerHTML);
|
||||
}
|
||||
el.removeAttribute("data-processed");
|
||||
el.innerHTML = el.dataset.source;
|
||||
});
|
||||
|
||||
mermaid.initialize(mermaidConfig());
|
||||
await mermaid.run({ querySelector: ".mermaid" });
|
||||
wrapMermaidDiagrams();
|
||||
}
|
||||
|
||||
function wrapMermaidDiagrams() {
|
||||
document.querySelectorAll(".mermaid").forEach((el) => {
|
||||
if (el.closest(".mermaid-container")) return;
|
||||
|
||||
const container = document.createElement("div");
|
||||
container.className = "mermaid-container";
|
||||
if ((el.dataset.source || "").includes('root(["zxh"])')) {
|
||||
container.classList.add("mermaid-container--site-map");
|
||||
}
|
||||
const controls = document.createElement("div");
|
||||
controls.className = "mermaid-zoom-controls";
|
||||
controls.innerHTML = `
|
||||
<button class="zoom-in" type="button" aria-label="Zoom in">+</button>
|
||||
<button class="zoom-out" type="button" aria-label="Zoom out">-</button>
|
||||
`;
|
||||
|
||||
el.replaceWith(container);
|
||||
container.appendChild(controls);
|
||||
container.appendChild(el);
|
||||
|
||||
let scale = 1;
|
||||
const setScale = (next) => {
|
||||
const svg = container.querySelector(".mermaid svg");
|
||||
if (!svg) return;
|
||||
scale = Math.max(0.2, Math.min(3, next));
|
||||
svg.style.transform = `scale(${scale})`;
|
||||
};
|
||||
|
||||
controls.querySelector(".zoom-in").addEventListener("click", () => setScale(scale + 0.1));
|
||||
controls.querySelector(".zoom-out").addEventListener("click", () => setScale(scale - 0.1));
|
||||
container.addEventListener("wheel", (e) => {
|
||||
if (!e.ctrlKey) return;
|
||||
e.preventDefault();
|
||||
setScale(scale + (e.deltaY < 0 ? 0.05 : -0.05));
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
if (document.readyState === "loading") {
|
||||
document.addEventListener("DOMContentLoaded", renderMermaid);
|
||||
} else {
|
||||
renderMermaid();
|
||||
}
|
||||
})();
|
||||
88
assets/scripts/ui/toc-active-link.js
Normal file
88
assets/scripts/ui/toc-active-link.js
Normal file
@@ -0,0 +1,88 @@
|
||||
/* Event listener for scrolling and changing the active label on the TOC */
|
||||
document.addEventListener("DOMContentLoaded", () => {
|
||||
const toc = document.querySelector("#text-table-of-contents");
|
||||
if (!toc) { console.warn("No #text-table-of-contents found"); return; }
|
||||
|
||||
const links = toc.querySelectorAll('a[href^="#"]'); // '^=' is a starts with operator.
|
||||
// <a href="#introduction">Intro</a> matches
|
||||
if (!links.length) { console.warn("No ToC links found"); return; }
|
||||
|
||||
// Map: id -> link
|
||||
const linkById = new Map();
|
||||
links.forEach(a => {
|
||||
const id = decodeURIComponent(a.getAttribute("href").slice(1));
|
||||
const el = document.getElementById(id);
|
||||
if (el) linkById.set(id, a);
|
||||
});
|
||||
if (!linkById.size) { console.warn("No matching headings with IDs"); return; }
|
||||
|
||||
// Headings to observe (h2–h4 usually)
|
||||
const headings = [...document.querySelectorAll("h2[id], h3[id], h4[id]")]
|
||||
.filter(h => linkById.has(h.id));
|
||||
|
||||
// Helper to mark active
|
||||
const setActive = (id) => {
|
||||
links.forEach(a => {
|
||||
const active = a.getAttribute("href") === `#${id}`;
|
||||
a.classList.toggle("is-active", active);
|
||||
if (active) a.setAttribute("aria-current", "true");
|
||||
else a.removeAttribute("aria-current");
|
||||
});
|
||||
};
|
||||
|
||||
// Calculate sticky header offset in px
|
||||
const headerOffsetPx = 6.5 * parseFloat(getComputedStyle(document.documentElement).fontSize);
|
||||
|
||||
// Track visible headings (id -> distance from top)
|
||||
const visible = new Map();
|
||||
|
||||
const observer = new IntersectionObserver((entries) => {
|
||||
entries.forEach(entry => {
|
||||
const id = entry.target.id;
|
||||
if (entry.isIntersecting) {
|
||||
// How far from the top (after header offset)
|
||||
const dist = entry.target.getBoundingClientRect().top - headerOffsetPx;
|
||||
visible.set(id, dist);
|
||||
} else {
|
||||
visible.delete(id);
|
||||
}
|
||||
});
|
||||
|
||||
if (visible.size) {
|
||||
// Choose the heading closest to the top (>= -headerOffset)
|
||||
const topMost = [...visible.entries()]
|
||||
.sort((a,b) => Math.abs(a[1]) - Math.abs(b[1]))[0][0];
|
||||
setActive(topMost);
|
||||
// console.log("Active:", topMost, visible);
|
||||
}
|
||||
}, {
|
||||
root: null, // track relative to viewport
|
||||
rootMargin: `-${headerOffsetPx}px 0px -70% 0px`,
|
||||
threshold: [0, 0.01, 0.1] // fire as soon as it enters
|
||||
});
|
||||
|
||||
headings.forEach(h => observer.observe(h));
|
||||
|
||||
// Initial highlight (in case load mid‑page)
|
||||
let bestId = null, bestDist = Infinity;
|
||||
headings.forEach(h => {
|
||||
const top = h.getBoundingClientRect().top - headerOffsetPx;
|
||||
const dist = top < 0 ? Math.abs(top) : top + 1e6;
|
||||
if (dist < bestDist) { bestDist = dist; bestId = h.id; }
|
||||
});
|
||||
if (bestId) setActive(bestId);
|
||||
|
||||
// smooth-scroll ToC clicks
|
||||
toc.addEventListener("click", (e) => {
|
||||
const a = e.target.closest('a[href^="#"]');
|
||||
if (!a) return;
|
||||
const id = decodeURIComponent(a.hash.slice(1));
|
||||
const el = document.getElementById(id);
|
||||
if (!el) return;
|
||||
e.preventDefault();
|
||||
el.scrollIntoView({ behavior: "smooth", block: "start" });
|
||||
el.setAttribute("tabindex", "-1");
|
||||
el.focus({ preventScroll: true });
|
||||
history.pushState(null, "", `#${id}`);
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user