ConnectionManager.jsx 1.69 KB
Newer Older
Tamas Kecskes's avatar
Tamas Kecskes committed
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
/**
 * @author kecso / https://github.com/kecso
 */
export default class ConnectionManager {
    constructor() {
        this.isConnecting = false;
        this.type = null;
        this.source = null;
        this.notifyMe = null;
        this.changeFn = null;
        this.startPos = null;
        this.currentPos = null;

        this.startConnection = this.startConnection.bind(this);
        this.endConnection = this.endConnection.bind(this);
        this.setListener = this.setListener.bind(this);
        this.clearListener = this.clearListener.bind(this);
    }

    startConnection(source, type, position, notifyMe) {
        this.isConnecting = true;
        this.type = type;
        this.source = source;
        this.startPos = position;
        this.notifyMe = typeof notifyMe === 'function' ? notifyMe : () => {
            console.log('no notification is sent');
        };
        this.fireChange();
    }

    endConnection() {
        this.isConnecting = false;
        const connection = {source: this.source, type: this.type};
        this.source = null;
        this.type = null;
        if (typeof this.notifyMe === 'function') { this.notifyMe(); }
        this.notifyMe = null;
        this.fireChange();
        return connection;
    }

    setListener(changeFn) {
        this.changeFn = changeFn;
    }

    clearListener() {
        this.changeFn = null;
    }

    onMouseMove(newPos) {
        this.currentPos = newPos;
        this.fireChange();
    }

    fireChange() {
        if (this.changeFn) {
            this.changeFn({
                isConnecting: this.isConnecting,
                startPos: this.startPos,
                currentPos: this.currentPos,
            });
        }
    }
}