avocado-old/packages/entity/trait.js
2019-03-21 23:13:46 -05:00

129 lines
2.6 KiB
JavaScript

import * as I from 'immutable';
import {Resource} from '@avocado/resource';
import {Vector} from '@avocado/math';
import {Property} from '@avocado/mixins';
export class Trait {
constructor(entity, params, state) {
this.entity = entity;
this.params = I.fromJS(this.constructor.defaultParams()).merge(params);
this.state = I.fromJS(this.constructor.defaultState()).merge(state);
}
acceptStateChange(change) {
if (!change.state) {
return;
}
const undefinedProperties = {};
for (const key in change.state) {
const value = change.state[key];
if (key in this.entity) {
this.entity[key] = value;
}
else {
undefinedProperties[key] = value;
}
}
this.state = this.state.merge(undefinedProperties);
}
destroy() {}
hooks() {
return {};
}
hydrate() {
return Promise.resolve();
}
initialize() {}
label() {
return this.constructor.name;
}
listeners() {
return {};
}
methods() {
return {};
}
toJSON() {
return {
params: this.params.toJS(),
state: this.state.toJS(),
};
}
static contextType() {
return {};
}
static defaultParams() {
return {};
}
static defaultState() {
return {};
}
static dependencies() {
return [];
}
static type() {
return this.name.toLowerCase();
}
}
export function simpleState(key, meta = {}) {
return (Superclass) => {
meta.emit = meta.emit || function(...args) {
this.entity.emit(...args);
};
meta.get = meta.get || function(value) {
return this.state.get(key);
};
meta.set = meta.set || function(value) {
this.state = this.state.set(key, value);
};
return Property(key, meta)(Superclass);
}
}
export function simpleStateVector(vector, x, y, meta = {}) {
return (Superclass) => {
meta.default = undefined;
meta.emit = meta.emit || function(...args) {
this.entity.emit(...args);
};
meta.get = meta.get || function() {
return [
this.state.get(x),
this.state.get(y),
];
};
meta.set = meta.set || function(vector) {
if (meta.track && meta.emit) {
if (this.state.get(x) !== vector[0]) {
meta.emit.call(this, `${x}Changed`, this.state.get(x), vector[0]);
}
if (this.state.get(y) !== vector[1]) {
meta.emit.call(this, `${y}Changed`, this.state.get(y), vector[1]);
}
}
this.state = this.state.merge({
[x]: vector[0],
[y]: vector[1],
});
};
return Vector.Mixin(vector, x, y, meta)(Superclass);
};
}