git ssb

0+

alanz / patchwork



forked from Matt McKegg / patchwork

Tree: 8acd553f8fa30f4b8a87229695d165ff34d49efc

Files: 8acd553f8fa30f4b8a87229695d165ff34d49efc / lib / scroller.js

1485 bytesRaw
1var pull = require('pull-stream')
2var Pause = require('pull-pause')
3var Value = require('mutant/value')
4var onceIdle = require('mutant/once-idle')
5var computed = require('mutant/computed')
6
7module.exports = Scroller
8
9function Scroller (scroller, content, render, cb) {
10 var toRenderCount = Value(0)
11 var toAppendCount = Value(0)
12
13 var queueLength = computed([toRenderCount, toAppendCount], (a, b) => a + b)
14
15 var pause = Pause(function () {})
16 var running = true
17 var appendQueue = []
18
19 function appendLoop () {
20 var distanceFromBottom = scroller.scrollHeight - (scroller.scrollTop + scroller.clientHeight)
21 if (distanceFromBottom < scroller.clientHeight) {
22 while (appendQueue.length) {
23 content.appendChild(appendQueue.shift())
24 }
25 }
26
27 toAppendCount.set(appendQueue.length)
28 if (queueLength() < 5) {
29 // queue running low, resume stream
30 pause.resume()
31 }
32
33 if (running || queueLength()) {
34 window.requestAnimationFrame(appendLoop)
35 }
36 }
37
38 var stream = pull(
39 pause,
40 pull.drain(function (msg) {
41 toRenderCount.set(toRenderCount() + 1)
42
43 onceIdle(() => {
44 var element = render(msg)
45 appendQueue.push(element)
46 toRenderCount.set(toRenderCount() - 1)
47 })
48
49 if (queueLength() > 5) {
50 pause.pause()
51 }
52 }, function (err) {
53 running = false
54 cb ? cb(err) : console.error(err)
55 })
56 )
57
58 stream.queue = queueLength
59
60 appendLoop()
61 return stream
62}
63

Built with git-ssb-web