2019-03-17 23:45:48 -05:00
|
|
|
import * as I from 'immutable';
|
|
|
|
|
|
|
|
import {Resource} from '@avocado/resource';
|
2019-03-18 20:04:12 -05:00
|
|
|
import {Property} from '@avocado/mixins';
|
2019-03-17 23:45:48 -05:00
|
|
|
|
|
|
|
export class Trait {
|
|
|
|
|
2019-03-19 10:02:18 -05:00
|
|
|
constructor(entity, params, state) {
|
2019-03-17 23:45:48 -05:00
|
|
|
this.entity = entity;
|
2019-03-19 10:02:18 -05:00
|
|
|
this.params = I.fromJS(this.constructor.defaultParams()).merge(params);
|
|
|
|
this.state = I.fromJS(this.constructor.defaultState()).merge(state);
|
2019-03-17 23:45:48 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
acceptStateChange(change) {
|
2019-03-19 10:02:18 -05:00
|
|
|
if (!change.state) {
|
|
|
|
return;
|
2019-03-18 21:22:54 -05:00
|
|
|
}
|
2019-03-19 10:02:18 -05:00
|
|
|
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;
|
2019-03-18 20:03:30 -05:00
|
|
|
}
|
|
|
|
}
|
2019-03-19 10:02:18 -05:00
|
|
|
this.state = this.state.merge(undefinedProperties);
|
2019-03-17 23:45:48 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
actions() {
|
|
|
|
return {};
|
|
|
|
}
|
|
|
|
|
2019-03-18 20:00:02 -05:00
|
|
|
destroy() {}
|
2019-03-17 23:45:48 -05:00
|
|
|
|
|
|
|
hooks() {
|
|
|
|
return {};
|
|
|
|
}
|
|
|
|
|
|
|
|
hydrate() {
|
|
|
|
return Promise.resolve();
|
|
|
|
}
|
|
|
|
|
2019-03-19 11:12:28 -05:00
|
|
|
initialize() {}
|
|
|
|
|
2019-03-17 23:45:48 -05:00
|
|
|
label() {
|
|
|
|
return this.constructor.name;
|
|
|
|
}
|
|
|
|
|
|
|
|
listeners() {
|
|
|
|
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();
|
|
|
|
}
|
|
|
|
|
|
|
|
}
|
|
|
|
|
2019-03-18 20:04:12 -05:00
|
|
|
export function simpleState(key, meta = {}) {
|
2019-03-17 23:45:48 -05:00
|
|
|
return (Superclass) => {
|
2019-03-18 20:04:12 -05:00
|
|
|
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);
|
2019-03-17 23:45:48 -05:00
|
|
|
}
|
|
|
|
}
|