@turbox3d/reactivity
Version:
Large-scale reactive state management library
69 lines • 2.48 kB
JavaScript
import { quacksLikeADecorator, isPlainObject, includes } from '@turbox3d/shared';
import { Domain, collectionTypes } from '../core/domain';
import { DEFAULT_FIELD_NAME } from '../const/symbol';
export var meta = {
freeze: false
};
export function reactor() {
var config = {
deepProxy: true,
displayName: ''
};
var decorator = function decorator(target, property, descriptor) {
var newDescriptor = {
enumerable: true,
configurable: true,
get: function get() {
var current = this;
if (config.callback) {
var f = function f() {
meta.freeze = true;
config.callback && config.callback.call(current, current, property);
meta.freeze = false;
};
!meta.freeze && f();
}
var defaultValue = descriptor && descriptor.initializer && descriptor.initializer();
return current.propertyGet(property, config, !!(descriptor && descriptor.initializer), defaultValue);
},
set: function set(newVal) {
var current = this;
current.propertySet(property, newVal, config);
}
};
// typescript only: (exp: @reactor() name: string = 'someone';)
if (descriptor === void 0) {
return Object.defineProperty(target, property, newDescriptor);
}
// babel only: (exp: @reactor() name = 'someone';)
return newDescriptor;
};
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
if (isPlainObject(args[0]) || Array.isArray(args[0]) || args[0] && args[0].constructor && includes(collectionTypes, args[0].constructor)) {
var param = args[1];
if (param) {
param.displayName !== void 0 && (config.displayName = param.displayName);
param.isNeedRecord !== void 0 && (config.isNeedRecord = param.isNeedRecord);
param.callback !== void 0 && (config.callback = param.callback);
}
var domain = new Domain();
var propKey = config.displayName || DEFAULT_FIELD_NAME;
var ins = decorator(domain, propKey);
ins[propKey] = args[0];
return ins[propKey];
}
if (quacksLikeADecorator(args)) {
// @decorator
// eslint-disable-next-line prefer-spread
return decorator.apply(null, args);
}
// @decorator(args)
config.deepProxy = args[0] !== void 0 ? args[0] : true;
if (args[1] !== void 0) {
config.isNeedRecord = args[1];
}
config.callback = args[2];
return decorator;
}