avocado-old/packages/entity/index.js
2019-04-12 14:02:49 -05:00

147 lines
2.6 KiB
JavaScript

import * as I from 'immutable';
import {compose} from '@avocado/core';
import {EventEmitter} from '@avocado/mixins';
import {Resource} from '@avocado/resource';
import {Traits} from './traits';
class TraitProxy {
has(entity, property, receiver) {
if (property in entity) {
return Reflect.has(entity, property, receiver);
}
else {
return entity._traits.hasProperty(property);
}
}
get(entity, property, receiver) {
if (property in entity) {
return Reflect.get(entity, property, receiver);
}
else {
return entity._traits.getProperty(property);
}
}
set(entity, property, value, receiver) {
if (
(property in entity)
|| !entity._traits.setProperty(property, value, receiver)
) {
return Reflect.set(entity, property, value, receiver);
}
else {
return true;
}
}
}
const decorate = compose(
EventEmitter,
);
class Entity extends decorate(Resource) {
constructor() {
super();
this._traits = new Traits(createProxy(this));
}
addTrait(type, trait) {
this._traits.addTrait(type, trait);
}
addTraits(traits) {
for (const type in traits) {
this._traits.addTrait(type, traits[type]);
}
}
allTraitInstances() {
return this._traits.allInstances();
}
allTraitTypes() {
return this._traits.allTypes();
}
fromJSON(json) {
super.fromJSON(json);
this._traits.fromJSON(json.traits);
return this;
}
is(type) {
return this._traits.hasTrait(type);
}
hydrate() {
return this._traits.hydrate();
}
invokeHook(hook, ...args) {
return this._traits.invokeHook(hook, ...args);
}
invokeHookFlat(hook, ...args) {
return this._traits.invokeHookFlat(hook, ...args);
}
patchState(patch) {
this._traits.patchState(patch);
}
removeAllTraits() {
const types = this._traits.allTypes();
this.removeTraits(types);
}
removeTrait(type) {
this._traits.removeTrait(type);
}
removeTraits(types) {
types.forEach((type) => this.removeTrait(type));
}
get state() {
return this._traits.state;
}
tick(elapsed) {
if (this.isTicking) {
this._traits.tick(elapsed);
}
}
toJSON() {
return {
...super.toJSON(),
traits: this._traits.toJSON(),
}
}
}
export function create() {
return createProxy(new Entity());
}
export function createProxy(entity) {
return new Proxy(entity, new TraitProxy());
}
export {EntityList} from './list';
export {
hasTrait,
lookupTrait,
registerTrait,
} from './trait-registry';
export {StateProperty, Trait} from './trait';