-
-
Notifications
You must be signed in to change notification settings - Fork 27
/
tracklistloader.go
64 lines (58 loc) · 1.46 KB
/
tracklistloader.go
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
package widgets
import (
"github.com/dweymouth/supersonic/backend/mediaprovider"
)
// Component that manages lazily loading more tracks into a Tracklist
// as the user scrolls near the bottom.
type TracklistLoader struct {
tracklist *Tracklist
iter mediaprovider.TrackIterator
trackBuffer []*mediaprovider.Track
fetching bool
done bool
len int
highestShown int
}
func NewTracklistLoader(tracklist *Tracklist, iter mediaprovider.TrackIterator) TracklistLoader {
t := TracklistLoader{
tracklist: tracklist,
iter: iter,
}
t.tracklist.OnTrackShown = t.onTrackShown
t.fetching = true
go t.loadMoreTracks(25)
return t
}
func (t *TracklistLoader) onTrackShown(tracknum int) {
if tracknum > t.highestShown {
t.highestShown = tracknum
}
if t.highestShown >= t.len-25 && !t.fetching && !t.done {
t.fetching = true
go t.loadMoreTracks(25)
}
}
func (t *TracklistLoader) loadMoreTracks(num int) {
// repeat fetch task as long as user has scrolled near bottom
for !t.done && t.highestShown >= t.len-25 {
if t.trackBuffer == nil {
t.trackBuffer = make([]*mediaprovider.Track, 0, num)
}
t.trackBuffer = t.trackBuffer[:0]
for i := 0; i < num; i++ {
tr := t.iter.Next()
if tr == nil {
t.done = true
break
}
t.trackBuffer = append(t.trackBuffer, tr)
}
t.tracklist.AppendTracks(t.trackBuffer)
t.tracklist.Refresh()
t.len += len(t.trackBuffer)
}
if t.done {
t.trackBuffer = nil
}
t.fetching = false
}