aboutsummaryrefslogtreecommitdiffstats
path: root/app/scrollable.go
blob: bca202321165b0196d556a5c946b593eb03a92c0 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
package app

// Scrollable implements vertical scrolling
type Scrollable struct {
	scroll int
	height int
	elems  int
}

func (s *Scrollable) Scroll() int {
	return s.scroll
}

func (s *Scrollable) PercentVisible() float64 {
	if s.elems <= 0 {
		return 1.0
	}
	return float64(s.height) / float64(s.elems)
}

func (s *Scrollable) PercentScrolled() float64 {
	if s.elems <= 0 {
		return 1.0
	}
	return float64(s.scroll) / float64(s.elems)
}

func (s *Scrollable) NeedScrollbar() bool {
	needScrollbar := true
	if s.PercentVisible() >= 1.0 {
		needScrollbar = false
	}
	return needScrollbar
}

func (s *Scrollable) UpdateScroller(height, elems int) {
	s.height = height
	s.elems = elems
}

func (s *Scrollable) EnsureScroll(selectingIdx int) {
	if selectingIdx < 0 {
		return
	}

	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
	}
}