avocado-old/packages/entity/index.js

286 lines
7.1 KiB
JavaScript
Raw Normal View History

2019-03-17 23:45:48 -05:00
import * as I from 'immutable';
2019-04-16 16:40:20 -05:00
import D from 'debug';
import without from 'lodash.without';
2019-03-17 23:45:48 -05:00
import {compose} from '@avocado/core';
import {EventEmitter} from '@avocado/mixins';
import {Resource} from '@avocado/resource';
2019-04-16 17:52:56 -05:00
import {Synchronized} from '@avocado/state';
2019-04-16 16:40:20 -05:00
import {hasTrait, lookupTrait} from './trait-registry';
const debug = D('@avocado/entity:traits');
function copyTraitProperties(from, to, instance) {
do {
Object.getOwnPropertyNames(from).forEach((property) => {
// Nooope.
2019-04-18 20:44:33 -05:00
switch (property) {
case 'state':
return;
2019-04-16 16:40:20 -05:00
}
// Make sure it's actually a property.
let descriptor = Object.getOwnPropertyDescriptor(from, property);
if (!descriptor.get && !descriptor.set) {
return;
}
// Bind properties to trait instance.
if (descriptor.get) {
descriptor.get = descriptor.get.bind(instance);
}
if (descriptor.set) {
descriptor.set = descriptor.set.bind(instance);
}
Object.defineProperty(to, property, descriptor);
});
} while (Object.prototype !== (from = Object.getPrototypeOf(from)));
2019-04-12 14:11:26 -05:00
}
2019-04-07 11:51:28 -05:00
2019-04-16 16:40:20 -05:00
function enumerateTraitProperties(prototype) {
const keys = [];
do {
Object.getOwnPropertyNames(prototype).forEach((property) => {
2019-04-18 20:44:33 -05:00
let descriptor = Object.getOwnPropertyDescriptor(prototype, property);
if (!descriptor.get && !descriptor.set) {
return;
}
2019-04-16 16:40:20 -05:00
keys.push(property);
});
} while (Object.prototype !== (prototype = Object.getPrototypeOf(prototype)));
return keys;
2019-03-17 23:45:48 -05:00
}
const decorate = compose(
EventEmitter,
2019-04-16 17:52:56 -05:00
Synchronized,
2019-03-17 23:45:48 -05:00
);
2019-04-16 16:40:20 -05:00
export class Entity extends decorate(Resource) {
2019-03-17 23:45:48 -05:00
constructor() {
super();
2019-04-16 16:40:20 -05:00
this._hooks = {};
2019-04-16 23:44:03 -05:00
this.$$stateDirty = true;
2019-04-16 16:40:20 -05:00
this._traits = {};
this.once('destroyed', () => {
this.removeAllTraits();
});
2019-03-17 23:45:48 -05:00
}
2019-04-16 16:40:20 -05:00
addTrait(type, json = {}) {
if (this.is(type)) {
debug(`Tried to add trait "${type}" when it already exists!`);
return;
}
if (!hasTrait(type)) {
debug(`Tried to add trait "${type}" which isn't registered!`);
return;
}
const Trait = lookupTrait(type);
// Ensure dependencies.
const dependencies = Trait.dependencies();
const allTypes = this.allTraitTypes();
const lacking = without(dependencies, ...allTypes);
if (lacking.length > 0) {
debug(
`Tried to add trait "${type}" but lack one or more dependents: "${
lacking.join('", "')
}"!`
);
return;
}
// Instantiate.
const {params, state} = json;
const instance = new Trait(this, params, state);
// Proxy properties.
copyTraitProperties(Trait.prototype, this, instance);
// Let the Trait do its initialization.
instance.initialize();
// Attach listeners.
const listeners = instance.listeners();
for (const eventName in listeners) {
this.on(eventName, listeners[eventName]);
}
// Proxy methods.
const methods = instance.methods();
for (const key in methods) {
this[key] = methods[key];
}
// Register hook listeners.
const hooks = instance.hooks();
for (const key in hooks) {
this._hooks[key] = this._hooks[key] || [];
this._hooks[key].push({
fn: hooks[key],
type: Trait.type(),
});
}
// Add state.
this.state = this._setInstanceState(this.state, type, instance);
// Track trait.
this._traits[type] = instance;
this.emit('traitAdded', type, instance);
2019-03-17 23:45:48 -05:00
}
addTraits(traits) {
for (const type in traits) {
2019-04-16 16:40:20 -05:00
this.addTrait(type, traits[type]);
2019-03-17 23:45:48 -05:00
}
}
allTraitInstances() {
2019-04-16 16:40:20 -05:00
return this._traits;
2019-03-17 23:45:48 -05:00
}
allTraitTypes() {
2019-04-16 16:40:20 -05:00
return Object.keys(this._traits);
2019-03-17 23:45:48 -05:00
}
fromJSON(json) {
super.fromJSON(json);
2019-04-16 16:40:20 -05:00
this.addTraits(json.traits);
2019-03-17 23:45:48 -05:00
return this;
}
hydrate() {
2019-04-16 16:40:20 -05:00
const promises = [];
for (const type in this._traits) {
const instance = this._traits[type];
promises.push(instance.hydrate());
}
return Promise.all(promises);
2019-03-17 23:45:48 -05:00
}
invokeHook(hook, ...args) {
2019-04-16 16:40:20 -05:00
const results = {};
if (!(hook in this._hooks)) {
return results;
}
for (const {fn, type} of this._hooks[hook]) {
results[type] = fn(...args);
}
return results;
2019-03-17 23:45:48 -05:00
}
invokeHookFlat(hook, ...args) {
2019-04-16 16:40:20 -05:00
const invokeResults = this.invokeHook(hook, ...args);
const results = [];
for (const type in invokeResults) {
results.push(invokeResults[type]);
}
return results;
2019-03-17 23:45:48 -05:00
}
2019-04-16 16:40:20 -05:00
is(type) {
return type in this._traits;
}
patchStateStep(type, step) {
let instance = this._traits[type];
// New trait requested?
if (!this._traits[type]) {
// Doesn't exist?
if (!hasTrait(type)) {
return;
}
this.addTrait(type, step.value);
instance = this._traits[type];
}
else {
// Accept state.
instance.patchState([step]);
}
this.state = this._setInstanceState(this.state, type, instance);
2019-04-05 15:16:55 -05:00
}
2019-03-17 23:45:48 -05:00
removeAllTraits() {
2019-04-16 16:40:20 -05:00
const types = this.allTraitTypes();
2019-03-17 23:45:48 -05:00
this.removeTraits(types);
}
removeTrait(type) {
2019-04-16 16:40:20 -05:00
if (!this.is(type)) {
debug(`Tried to remove trait "${type}" when it doesn't exist!`);
return;
}
// Destroy instance.
const instance = this._traits[type];
instance.destroy();
// Remove methods, hooks, and properties.
const methods = instance.methods();
for (const key in methods) {
delete this[key];
}
const hooks = instance.hooks();
for (const key in hooks) {
delete this._hooks[key];
}
const Trait = lookupTrait(type);
2019-04-18 20:44:33 -05:00
const properties = enumerateTraitProperties(Trait.prototype);
for (let i = 0; i < properties.length; ++i) {
const property = properties[i];
delete this[property];
2019-04-16 16:40:20 -05:00
}
// Remove all event listeners.
const listeners = instance.listeners();
for (const eventName in listeners) {
this.off(eventName, listeners[eventName]);
}
// Remove state.
this.state = this.state.delete(type);
// Remove instance.
delete this._traits[type];
2019-03-17 23:45:48 -05:00
}
removeTraits(types) {
types.forEach((type) => this.removeTrait(type));
}
2019-04-16 16:40:20 -05:00
_setInstanceState(state, type, instance) {
let map = state.has(type) ? state.get(type) : I.Map();
map = map.set('state', instance.state);
map = map.set('params', instance.params);
return state.set(type, map);
2019-03-17 23:45:48 -05:00
}
tick(elapsed) {
2019-04-16 16:40:20 -05:00
for (const type in this._traits) {
const instance = this._traits[type];
instance.tick(elapsed);
}
2019-04-16 16:40:20 -05:00
this.state = this.state.withMutations((state) => {
for (const type in this._traits) {
const instance = this._traits[type];
2019-04-16 17:41:17 -05:00
if (!instance.$$stateDirty) {
continue;
}
instance.$$stateDirty = false;
2019-04-16 23:44:03 -05:00
this.$$stateDirty = true;
2019-04-16 16:40:20 -05:00
this._setInstanceState(state, type, instance);
}
});
}
2019-03-17 23:45:48 -05:00
toJSON() {
2019-04-16 16:40:20 -05:00
const json = {};
for (const type in this._traits) {
json[type] = this._traits[type].toJSON();
}
2019-03-17 23:45:48 -05:00
return {
...super.toJSON(),
2019-04-16 16:40:20 -05:00
traits: json,
};
2019-03-17 23:45:48 -05:00
}
}
2019-04-13 20:53:02 -05:00
export {EntityList, EntityListView} from './list';
2019-03-17 23:45:48 -05:00
export {
hasTrait,
lookupTrait,
registerTrait,
} from './trait-registry';
2019-03-17 23:45:48 -05:00
2019-03-23 23:24:18 -05:00
export {StateProperty, Trait} from './trait';