scroll and highlight selected line

added line numbers to source view, fixed css selectors
This commit is contained in:
Firehose Bot
2026-05-18 21:31:01 +01:00
parent 790d2f0e1d
commit a9e746d520
4 changed files with 217 additions and 93 deletions
+29 -6
View File
@@ -4,7 +4,7 @@
* Attached to the `#source-viewer` div via `phx-hook="SourceViewer"`.
* Reads `data-highlighted-line` to find the target line element and
* scrolls it into view with a smooth animation.
* Also applies highlight.js syntax highlighting to code blocks.
* Applies highlight.js syntax highlighting to individual line content elements.
*/
import hljs from "highlight.js/lib/core"
@@ -20,10 +20,33 @@ export const SourceViewer = {
},
applySyntaxHighlighting() {
const codeEl = this.el.querySelector("code")
if (codeEl && !codeEl.querySelector(".hljs")) {
hljs.highlightElement(codeEl)
}
const container = this.el.querySelector(".sv-lines")
if (!container || container.querySelector(".hljs-on")) return;
// Collect the raw text from all line content spans
const lineContentEls = container.querySelectorAll(".sv-line-content")
if (lineContentEls.length === 0) return;
const rawText = Array.from(lineContentEls).map(el => el.textContent).join("\n")
// Create a temp element for highlight.js to process
const temp = document.createElement("code")
temp.textContent = rawText
hljs.highlightElement(temp)
// Split the highlighted HTML back into lines
// highlight.js innerHTML uses actual newlines between lines of code
const highlightedLines = temp.innerHTML.split("\n")
// Apply each highlighted line to the corresponding .sv-line-content
lineContentEls.forEach((el, i) => {
if (highlightedLines[i]) {
el.innerHTML = highlightedLines[i]
}
})
// Mark as highlighted so we don't re-apply on subsequent updates
container.classList.add("hljs", "hljs-on")
},
scrollToHighlighted() {
@@ -35,4 +58,4 @@ export const SourceViewer = {
}
}
}
}
}