[PATCH v3 4/6] cgit.js: line range highlight: improve vertical scroll logic

Andy Green andy at warmcat.com
Sun Jun 24 04:44:44 CEST 2018


Instead of following the browser heuristic to put any matching
id element to the top left of the browser window, compute the
number of visible lines vertically in the window, and the
middle of the highlit range, and try to centre the middle of
the highlit range in the window.

If the top of the range is no longer visible due to a range
consisting of more lines than the window can show, fall back to
placing the top of the range at the top of the window.

Signed-off-by: Andy Green <andy at warmcat.com>
---
 cgit.js |   20 ++++++++++++++++----
 1 file changed, 16 insertions(+), 4 deletions(-)

diff --git a/cgit.js b/cgit.js
index 772843a..29b2c3d 100644
--- a/cgit.js
+++ b/cgit.js
@@ -31,7 +31,7 @@ function cgit_line_range_highlight()
 	if (l2 < l1)
 		l2 = l1;
 
-	var lh, t = 0, e1, e2, de;
+	var lh, t = 0, e1, e2, de, hl, v, n;
 
 	e1 = e = document.getElementById('n' + l1);
 	if (!e)
@@ -60,13 +60,25 @@ function cgit_line_range_highlight()
 
 	e.parentElement.parentElement.insertBefore(de, e.parentElement.parentElement.firstChild);
 
-	while (l1 <= l2) {
+	n = l1;
+	while (n <= l2) {
 		var e1;
-		e1 = document.getElementById('n' + l1++);
+		e1 = document.getElementById('n' + n++);
 		e1.style.backgroundColor = "yellow";
 	}
 
-	e.scrollIntoView(true);
+	hl = (window.innerHeight / (e.offsetHeight + 1));
+	v = (l1 + ((l2 - l1) / 2)) - (hl / 2);
+	if (v > l1)
+		v = l1;
+	if (v < 0)
+		v = 1;
+
+	e1 = document.getElementById('n' + Math.round(v));
+	if (e1)
+		e1.scrollIntoView(true);
+	else
+		e.scrollIntoView(true);
 }
 
 /* line range highlight */



More information about the CGit mailing list