From 1068365afa0c2a0f55d37b17360ad832657531a0 Mon Sep 17 00:00:00 2001 From: Koni Marti Date: Mon, 29 Jan 2024 23:52:26 +0100 Subject: scrollable: rewrite with scroll offset Rewrite the scrolling logic to consider a scroll offset. Ensure correct lower and upper bounds of the scroll variable. Cap offset at half of the screen height. Signed-off-by: Koni Marti Tested-by: Jason Cox Acked-by: Robin Jarry --- app/scrollable.go | 40 +++++++++++++++++++++++++--------------- 1 file changed, 25 insertions(+), 15 deletions(-) (limited to 'app/scrollable.go') diff --git a/app/scrollable.go b/app/scrollable.go index bca20232..3a0555fe 100644 --- a/app/scrollable.go +++ b/app/scrollable.go @@ -3,6 +3,7 @@ package app // Scrollable implements vertical scrolling type Scrollable struct { scroll int + offset int height int elems int } @@ -11,6 +12,14 @@ func (s *Scrollable) Scroll() int { return s.scroll } +func (s *Scrollable) SetOffset(offset int) { + s.offset = offset +} + +func (s *Scrollable) ScrollOffset() int { + return s.offset +} + func (s *Scrollable) PercentVisible() float64 { if s.elems <= 0 { return 1.0 @@ -38,30 +47,31 @@ func (s *Scrollable) UpdateScroller(height, elems int) { s.elems = elems } -func (s *Scrollable) EnsureScroll(selectingIdx int) { - if selectingIdx < 0 { +func (s *Scrollable) EnsureScroll(idx int) { + if idx < 0 { return } + middle := s.height / 2 + switch { + case s.offset > middle: + s.scroll = idx - middle + case idx < s.scroll+s.offset: + s.scroll = idx - s.offset + case idx >= s.scroll-s.offset+s.height: + s.scroll = idx + s.offset - s.height + 1 + } + maxScroll := s.elems - s.height if maxScroll < 0 { maxScroll = 0 } - if selectingIdx >= s.scroll && selectingIdx < s.scroll+s.height { - if s.scroll > maxScroll { - s.scroll = maxScroll - } - return - } - - if selectingIdx >= s.scroll+s.height { - s.scroll = selectingIdx - s.height + 1 - } else if selectingIdx < s.scroll { - s.scroll = selectingIdx - } - if s.scroll > maxScroll { s.scroll = maxScroll } + + if s.scroll < 0 { + s.scroll = 0 + } } -- cgit