aboutsummaryrefslogtreecommitdiff
path: root/src_js/opcut/renderer.js
blob: 378b3c0717dcdee4b87e85207f66a83e3f4e23b1 (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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
/** @module opcut/renderer2 */

import * as snabbdom from 'snabbdom/es/snabbdom';
import snabbdomAttributes from 'snabbdom/es/modules/attributes';
import snabbdomClass from 'snabbdom/es/modules/class';
import snabbdomProps from 'snabbdom/es/modules/props';
// import snabbdomStyle from 'snabbdom/es/modules/style';
import snabbdomDataset from 'snabbdom/es/modules/dataset';
import snabbdomEvent from 'snabbdom/es/modules/eventlisteners';

import * as u from 'opcut/util';
import * as ev from 'opcut/ev';


const patch = snabbdom.init([
    snabbdomAttributes,
    snabbdomClass,
    snabbdomProps,
    // snabbdomStyle,
    snabbdomDataset,
    snabbdomEvent
]);


function vhFromArray(node) {
    if (!node)
        return [];
    if (u.isString(node))
        return node;
    if (!u.isArray(node))
        throw 'Invalid node structure';
    if (node.length < 1)
        return [];
    if (typeof node[0] != 'string')
        return node.map(vhFromArray);
    const hasData = node.length > 1 && u.isObject(node[1]);
    const children = u.pipe(
        u.map(vhFromArray),
        u.flatten,
        Array.from
    )(node.slice(hasData ? 2 : 1));
    const result = hasData ?
        snabbdom.h(node[0], node[1], children) :
        snabbdom.h(node[0], children);
    return result;
}

/**
 * Virtual DOM renderer
 */
export class Renderer {

    /**
     * Calls `init` method
     * @param {HTMLElement} [el=document.body]
     * @param {Any} [initState=null]
     * @param {Function} [vtCb=null]
     * @param {Number} [maxFps=30]
     */
    constructor(el, initState, vtCb, maxFps) {
        this.init(el, initState, vtCb, maxFps);
    }

    /**
     * Initialize renderer
     * @param {HTMLElement} [el=document.body]
     * @param {Any} [initState=null]
     * @param {Function} [vtCb=null]
     * @param {Number} [maxFps=30]
     * @return {Promise}
     */
    init(el, initState, vtCb, maxFps) {
        this._state = null;
        this._changes = [];
        this._promise = null;
        this._timeout = null;
        this._lastRender = null;
        this._vtCb = vtCb;
        this._maxFps = u.isNumber(maxFps) ? maxFps : 30;
        this._vNode = el || document.querySelector('body');
        if (initState)
            return this.change(_ => initState);
        return new Promise(resolve => { resolve(); });
    }

    /**
     * Get current state value referenced by `paths`
     * @param {...Path} paths
     * @return {Any}
     */
    get(...paths) {
        return u.get(paths, this._state);
    }

    /**
     * Change current state value referenced by `path`
     * @param {Path} path
     * @param {Any} value
     * @return {Promise}
     */
    set(path, value) {
        if (arguments.length < 2) {
            value = path;
            path = [];
        }
        return this.change(path, _ => value);
    }

    /**
     * Change current state value referenced by `path`
     * @param {Path} path
     * @param {Function} cb
     * @return {Promise}
     */
    change(path, cb) {
        if (arguments.length < 2) {
            cb = path;
            path = [];
        }
        this._changes.push([path, cb]);
        if (this._promise)
            return this._promise;
        this._promise = new Promise((resolve, reject) => {
            setTimeout(() => {
                try {
                    this._change();
                } catch(e) {
                    this._promise = null;
                    reject(e);
                    throw e;
                }
                this._promise = null;
                resolve();
            }, 0);
        });
        return this._promise;
    }

    _change() {
        let change = false;
        while (this._changes.length > 0) {
            const [path, cb] = this._changes.shift();
            const view = u.get(path);
            const oldState = this._state;
            this._state = u.change(path, cb, this._state);
            if (this._state && u.equals(view(oldState),
                                        view(this._state)))
                continue;
            change = true;
            if (!this._vtCb || this._timeout)
                continue;
            const delay = (!this._lastRender || !this._maxFps ?
                0 :
                (1000 / this._maxFps) -
                (performance.now() - this._lastRender));
            this._timeout = setTimeout(() => {
                this._timeout = null;
                this._lastRender = performance.now();
                const vNode = vhFromArray(this._vtCb(this));
                patch(this._vNode, vNode);
                this._vNode = vNode;
                ev.fire(this, 'render', [this._state]);
            }, (delay > 0 ? delay : 0));
        }
        if (change)
            ev.fire(this, 'change', [this._state]);
    }

}
// Renderer.prototype.set = u.curry(Renderer.prototype.set);
// Renderer.prototype.change = u.curry(Renderer.prototype.change);


/**
 * Default renderer
 * @static
 * @type {Renderer}
 */
const defaultRenderer = new Renderer();
export default defaultRenderer;