avocado-old/packages/state/synchronizer.js

59 lines
1.2 KiB
JavaScript
Raw Normal View History

2019-03-20 18:33:13 -05:00
import * as I from 'immutable';
2019-04-07 15:46:07 -05:00
import {nextStep} from './next-step';
2019-04-07 20:04:40 -05:00
export class Synchronizer {
2019-03-20 18:33:13 -05:00
constructor(statefuls) {
this._state = I.Map();
this._statefuls = statefuls;
2019-04-19 22:29:28 -05:00
this.updateState();
2019-03-20 18:33:13 -05:00
}
2019-04-05 15:16:55 -05:00
patchState(patch) {
2019-04-05 22:14:29 -05:00
const stepMap = {};
2019-04-07 15:46:07 -05:00
for (const step of patch) {
const [key, substep] = nextStep(step)
2019-04-05 22:14:29 -05:00
if (!stepMap[key]) {
stepMap[key] = [];
}
2019-04-07 15:46:07 -05:00
stepMap[key].push(substep);
2019-04-05 22:14:29 -05:00
}
for (const key in stepMap) {
2019-04-05 15:16:55 -05:00
const stateful = this._statefuls[key];
if (!stateful) {
continue;
}
2019-04-05 22:14:29 -05:00
stateful.patchState(stepMap[key]);
2019-04-05 15:16:55 -05:00
}
}
2019-04-19 22:29:28 -05:00
setStateful(key, stateful) {
this._statefuls[key] = stateful;
}
get state() {
2019-03-20 18:33:13 -05:00
return this._state;
}
2019-04-07 15:15:55 -05:00
tick(elapsed) {
2019-03-20 18:33:13 -05:00
for (const key in this._statefuls) {
const stateful = this._statefuls[key];
2019-04-07 15:15:55 -05:00
stateful.tick(elapsed);
2019-03-20 18:33:13 -05:00
}
2019-04-19 22:29:28 -05:00
this.updateState();
}
updateState() {
2019-04-23 15:25:03 -05:00
if (AVOCADO_SERVER) {
this._state = this._state.withMutations((state) => {
for (const key in this._statefuls) {
const stateful = this._statefuls[key];
state.set(key, stateful.state);
}
});
}
2019-03-20 18:33:13 -05:00
}
}