Project

General

Profile

1
/*
2
    Based on:
3
    Copyright (c) 2016 Wilson Page wilsonpage@me.com
4
    https://github.com/wilsonpage/fastdom
5
*/
6

    
7
import { requestAnimationFrame } from './index';
8

    
9
export const fastdom = {
10

    
11
    reads: [],
12
    writes: [],
13

    
14
    measure: function(task) {
15
        this.reads.push(task);
16
        scheduleFlush(this);
17
        return task;
18
    },
19

    
20
    mutate: function(task) {
21
        this.writes.push(task);
22
        scheduleFlush(this);
23
        return task;
24
    },
25

    
26
    clear: function(task) {
27
        return remove(this.reads, task) || remove(this.writes, task);
28
    }
29

    
30
};
31

    
32
function scheduleFlush(fastdom) {
33
    if (!fastdom.scheduled) {
34
        fastdom.scheduled = true;
35
        requestAnimationFrame(flush.bind(null, fastdom));
36
    }
37
}
38

    
39
function flush(fastdom) {
40

    
41
    runTasks(fastdom.reads);
42
    runTasks(fastdom.writes.splice(0, fastdom.writes.length));
43

    
44
    fastdom.scheduled = false;
45

    
46
    if (fastdom.reads.length || fastdom.writes.length) {
47
        scheduleFlush(fastdom);
48
    }
49

    
50
}
51

    
52
function runTasks(tasks) {
53
    var task;
54
    while (task = tasks.shift()) {
55
        task();
56
    }
57
}
58

    
59
function remove(array, item) {
60
    var index = array.indexOf(item);
61
    return !!~index && !!array.splice(index, 1);
62
}
(3-3/9)