Skip to content

Commit 5b850ae

Browse files
committed
refactor(js): improve robustness of line numbering and TOC anchoring
1 parent 587f817 commit 5b850ae

File tree

2 files changed

+11
-26
lines changed

2 files changed

+11
-26
lines changed

assets/js/code-block.js

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -16,14 +16,16 @@ document.addEventListener('DOMContentLoaded', () => {
1616
codeContainer.appendChild(copyButton);
1717

1818
copyButton.addEventListener('click', () => {
19-
const codeText = code.innerText;
19+
const codeText = code.textContent;
2020
navigator.clipboard.writeText(codeText).then(() => {
2121
copyButton.classList.add('copied');
2222
setTimeout(() => { copyButton.classList.remove('copied'); }, 2000);
23+
}).catch(err => {
24+
console.error('无法复制到剪贴板:', err);
2325
});
2426
});
2527

26-
const codeLines = code.innerHTML.split(/\r?\n/);
28+
const codeLines = code.textContent.split(/\r?\n/);
2729
const hasTrailingEmptyLine = codeLines.length > 0 && codeLines[codeLines.length - 1].trim() === '';
2830
if (hasTrailingEmptyLine) {
2931
codeLines.pop();

assets/js/toc.js

Lines changed: 7 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -5,27 +5,12 @@ document.addEventListener('DOMContentLoaded', () => {
55
// We query all headings first, then filter/map to find the actual anchor ID
66
const rawHeadings = document.querySelectorAll('.main-content h1, .main-content h2, .main-content h3, .main-content h4, .main-content h5, .main-content h6');
77

8-
const headings = [];
9-
rawHeadings.forEach(h => {
10-
let id = h.getAttribute('id');
11-
// If the heading itself doesn't have an ID, check if it contains an element with an ID (e.g. <a id="...">)
12-
// or if the Zine renderer placed the ID on a wrapper.
13-
if (!id) {
14-
// Check if the parent element has an ID (SuperMD section wrapper)
15-
if (h.parentElement && h.parentElement.getAttribute('id')) {
16-
id = h.parentElement.getAttribute('id');
17-
} else {
18-
const childWithId = h.querySelector('[id]');
19-
if (childWithId) {
20-
id = childWithId.getAttribute('id');
21-
}
22-
}
23-
}
24-
25-
if (id) {
26-
headings.push({ element: h, id: id });
27-
}
28-
});
8+
const headings = Array.from(rawHeadings)
9+
.map(h => ({
10+
element: h,
11+
id: h.id || h.parentElement?.id || h.querySelector('[id]')?.id,
12+
}))
13+
.filter(h => h.id);
2914

3015
if (tocLinks.length === 0 || headings.length === 0) return;
3116

@@ -45,9 +30,7 @@ document.addEventListener('DOMContentLoaded', () => {
4530
if (currentId) {
4631
tocLinks.forEach(link => {
4732
link.classList.remove('active');
48-
// Decode URI component to handle non-ASCII IDs if any
49-
const href = link.getAttribute('href');
50-
if (href === `#${currentId}`) {
33+
if (link.hash === `#${currentId}`) {
5134
link.classList.add('active');
5235
}
5336
});

0 commit comments

Comments
 (0)