From mboxrd@z Thu Jan 1 00:00:00 1970 From: andy at warmcat.com (Andy Green) Date: Sun, 24 Jun 2018 10:44:39 +0800 Subject: [PATCH v3 3/6] cgit.js: line range highlight: make responsive to url changes In-Reply-To: <152980795804.2873.3939128717470466784.stgit@mail.warmcat.com> References: <152980795804.2873.3939128717470466784.stgit@mail.warmcat.com> Message-ID: <152980827936.2873.16560860248848406305.stgit@mail.warmcat.com> Browser default interpretation of the # part of the URL is to try to match it to an element ID one time at page load. Subsequent modifications in the URL bar are ignored, even if you hit enter there. This patch makes the line range highlight able to clean up after itself and be reapplied, and has the highlight function listen for hashchange events and re-interpret the # part when they occur. Now if you edit the URL and press enter, any existing highlight is removed, the # part reinterpreted and the new highlight applied automatically. This is particularly useful if you edit the # link with the intention to show a range before copying the URL. Clicking on the line number, which changes the URL bar to have a corresponding #n part, also triggers hashchange and makes the clicked line be highlit immediately. Signed-off-by: Andy Green --- cgit.js | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) diff --git a/cgit.js b/cgit.js index 501c98f..772843a 100644 --- a/cgit.js +++ b/cgit.js @@ -2,8 +2,24 @@ function cgit_line_range_highlight() { var h = window.location.hash, l1 = 0, l2 = 0, e, t; + e = document.getElementById("cgit_line_range"); + if (e) { + l1 = e.l1; + while (l1 <= e.l2) { + var e1; + e1 = document.getElementById('n' + l1++); + e1.style.backgroundColor = null; + } + + e.remove(); + } + l1 = parseInt(h.substring(2)); + if (!l1) + return; + t = h.indexOf("-"); + l2 = l1; if (t >= 1) l2 = parseInt(h.substring(t + 1)); else @@ -12,6 +28,9 @@ function cgit_line_range_highlight() if (!l1) return; + if (l2 < l1) + l2 = l1; + var lh, t = 0, e1, e2, de; e1 = e = document.getElementById('n' + l1); @@ -25,6 +44,9 @@ function cgit_line_range_highlight() de.className = "selected-lines"; de.style.bottom = e.style.bottom; de.style.top = t + 'px'; + de.id = "cgit_line_range"; + de.l1 = l1; + de.l2 = l2; /* DOM structure is different by one level for /blame/ */ e1 = e.parentElement.parentElement.parentNode; @@ -39,6 +61,7 @@ function cgit_line_range_highlight() e.parentElement.parentElement.insertBefore(de, e.parentElement.parentElement.firstChild); while (l1 <= l2) { + var e1; e1 = document.getElementById('n' + l1++); e1.style.backgroundColor = "yellow"; } @@ -51,3 +74,6 @@ function cgit_line_range_highlight() document.addEventListener("DOMContentLoaded", function() { cgit_line_range_highlight(); }, false); +window.addEventListener("hashchange", function() { + cgit_line_range_highlight(); +}, false);