avocado-old/packages/state/synchronized.js

78 lines
1.5 KiB
JavaScript
Raw Normal View History

2019-04-07 11:43:50 -05:00
import * as I from 'immutable';
import {compose} from '@avocado/core';
import {Property} from '@avocado/mixins';
2019-04-07 15:46:07 -05:00
import {nextStep} from './next-step';
2019-04-07 11:43:50 -05:00
const decorate = compose(
Property('state'),
);
export class Synchronized extends decorate(class {}) {
constructor() {
super();
this.state = I.Map();
}
synchronizedChildren() {
return [];
}
patchState(patch) {
for (const step of patch) {
const {op, path, value} = step;
if ('/' === path) {
for (const key in value) {
2019-04-11 06:49:42 -05:00
this.patchStateStep(key, {
op,
path,
value: value[key],
});
2019-04-07 11:43:50 -05:00
}
}
else {
2019-04-07 15:46:07 -05:00
const [key, substep] = nextStep(step);
2019-04-11 06:49:42 -05:00
this.patchStateStep(key, {
op: substep.op,
path: substep.path,
value: substep.value,
});
2019-04-07 11:43:50 -05:00
}
}
}
patchStateStep(key, step) {
if (!(key in this)) {
return;
}
if (this[key] instanceof Synchronized) {
this[key].patchState([step]);
}
else {
this[key] = step.value;
}
}
tick(elapsed) {
2019-04-12 13:18:34 -05:00
const children = this.synchronizedChildren();
for (const key of children) {
2019-04-07 11:43:50 -05:00
if (this[key] instanceof Synchronized) {
this[key].tick(elapsed);
}
}
2019-04-12 13:18:34 -05:00
this.state = this.state.withMutations((state) => {
for (const key of children) {
if (this[key] instanceof Synchronized) {
state.set(key, this[key].state);
}
else {
state.set(key, this[key]);
}
}
});
2019-04-07 11:43:50 -05:00
}
}