forked from hull-ships/hull-processor
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathengine.js
More file actions
119 lines (103 loc) · 2.79 KB
/
engine.js
File metadata and controls
119 lines (103 loc) · 2.79 KB
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
import _ from "lodash";
import { EventEmitter } from "events";
import superagent from "superagent";
const EVENT = "CHANGE";
export default class Engine extends EventEmitter {
constructor(config, { ship, currentUser }) {
super();
this.config = config;
const userId = currentUser && currentUser.id;
this.state = { ship, loading: false };
this.compute({ ship, userId });
this.compute = _.debounce(this.compute, 1000);
this.updateParent = _.debounce(this.updateParent, 1000);
}
setState(changes) {
this.state = { ...this.state, ...changes };
this.emitChange();
return this.state;
}
getState() {
return this.state || {};
}
addChangeListener(listener) {
this.addListener(EVENT, listener);
}
removeChangeListener(listener) {
this.removeListener(EVENT, listener);
}
emitChange() {
this.emit(EVENT);
}
searchUser(userSearch) {
this.compute({ userSearch, ship: this.state.ship });
}
updateShip(ship) {
this.compute({ ship, user: this.state.user });
}
updateParent(code) {
if (window.parent) {
window.parent.postMessage(JSON.stringify({
from: "embedded-ship",
action: "update",
ship: { private_settings: { code } }
}), "*");
}
}
updateCode(code) {
const { ship } = this.state || {};
if (!ship || !ship.id) return;
const newShip = {
...ship,
private_settings: {
...ship.private_settings,
code
}
};
this.updateParent(code);
this.setState({ ship: newShip });
this.compute({
ship: newShip,
user: this.state.user
});
}
compute(params) {
if (this.state.loading) return false;
this.setState({ loading: true });
if (this.computing) {
this.computing.abort();
}
this.computing = superagent.post("/compute")
.query(this.config)
.send(params)
.accept("json")
.end((error, { body = {}, status } = {}) => {
try {
this.computing = false;
if (error) {
this.setState({
error: { ...body, status },
loading: false,
initialized: true
});
} else {
const { ship, user, took, result } = body || {};
// Don't kill user code
if (this && this.state && this.state.ship && this.state.ship.private_settings) {
ship.private_settings.code = this.state.ship.private_settings.code;
}
this.setState({
loading: false,
initialized: true,
error: null,
ship, user, result, took
});
}
} catch (err) {
this.computing = false;
this.setState({ loading: false, error: err });
}
});
return this.computing;
}
}