Skip to content

Commit

Permalink
web: Parse range state from URL
Browse files Browse the repository at this point in the history
  • Loading branch information
fstachura committed Sep 27, 2024
1 parent 4c0f2cf commit e90f8f0
Showing 1 changed file with 32 additions and 3 deletions.
35 changes: 32 additions & 3 deletions static/script.js
Original file line number Diff line number Diff line change
Expand Up @@ -122,14 +122,21 @@ function handleLineRange(hashStr) {
return;
}

const firstLineElement = document.getElementById(hash[0]);
const lastLineElement = document.getElementById(hash[1]);
// Check if hash format is valid
if (hash[0][0] != "L" || hash[1][0] != "L") {
return;
}

let firstLineElement = document.getElementById(hash[0]);
let lastLineElement = document.getElementById(hash[1]);
if (firstLineElement === undefined || lastLineElement === undefined) {
return;
}

highlightFromTo(firstLineElement, lastLineElement);
firstLineElement.scrollIntoView();

return [firstLineElement, lastLineElement];
}

// Highlights line number elements from firstLineElement to lastLineElement
Expand All @@ -139,7 +146,15 @@ function highlightFromTo(firstLineElement, lastLineElement) {
console.assert(!isNaN(firstLine) && !isNaN(lastLine),
"Elements to highlight have invalid numbers in ids");

console.assert(firstLine < lastLine, "first highlight line is after last highlight line");
if (firstLine > lastLine) {
const elementTmp = firstLineElement;
firstLineElement = lastLineElement;
lastLineElement = elementTmp;

const lineTmp = firstLine;
firstLine = lastLine;
lastLine = lineTmp;
}

const firstCodeLine = document.getElementById(`codeline-${ firstLine }`);
const lastCodeLine = document.getElementById(`codeline-${ lastLine }`);
Expand Down Expand Up @@ -168,6 +183,20 @@ function setupLineRangeHandlers() {
}

let rangeStart, rangeEnd;

const highlightedRange = handleLineRange(window.location.hash);
// Set range start/end to elements from hash
if (highlightedRange !== undefined) {
rangeStart = highlightedRange[0];
rangeEnd = highlightedRange[1];
} else if (location.hash !== "" && location.hash[1] === "L") {
const lineNum = parseInt(location.hash.substring(2));
const hashElement = document.getElementById(location.hash.substring(1));
if (hashElement !== null && hashElement.tagName === "A" && !isNaN(lineNum)) {
rangeStart = hashElement;
}
}

linenodiv.addEventListener("click", ev => {
if (ev.ctrlKey || ev.metaKey) {
return;
Expand Down

0 comments on commit e90f8f0

Please sign in to comment.