2020-06-23 11:19:59 -05:00
|
|
|
import {arrayUnique, flatten, mapObject} from '@avocado/core';
|
|
|
|
import memoize from 'lodash.memoize';
|
|
|
|
import {invokeHookFlat, registerHooks} from 'scwp';
|
|
|
|
|
|
|
|
export const globals = memoize(() => (
|
|
|
|
invokeHookFlat('behaviorContextGlobals')
|
|
|
|
.reduce((r, results) => ({
|
|
|
|
...r,
|
|
|
|
...results,
|
|
|
|
}), {})
|
|
|
|
));
|
|
|
|
|
|
|
|
export default class Context {
|
|
|
|
|
|
|
|
constructor(defaults = {}) {
|
|
|
|
this.map = new Map();
|
|
|
|
this.clear();
|
|
|
|
this.addObjectMap(defaults);
|
|
|
|
}
|
|
|
|
|
|
|
|
add(key, value, type = 'undefined') {
|
2020-06-25 09:52:57 -05:00
|
|
|
if (key) {
|
|
|
|
this.map.set(key, [value, type]);
|
|
|
|
}
|
2020-06-23 11:19:59 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
addObjectMap(map) {
|
|
|
|
Object.entries(map)
|
|
|
|
.forEach(([key, [variable, type]]) => (
|
|
|
|
this.add(key, variable, type)
|
|
|
|
));
|
|
|
|
}
|
|
|
|
|
|
|
|
all() {
|
|
|
|
return Array.from(this.map.keys())
|
|
|
|
.reduce((r, key) => ({
|
|
|
|
...r,
|
|
|
|
[key]: this.get(key),
|
|
|
|
}), {});
|
|
|
|
}
|
|
|
|
|
|
|
|
clear() {
|
|
|
|
this.destroy();
|
|
|
|
this.add('context', this, 'context');
|
|
|
|
this.addObjectMap(globals());
|
|
|
|
}
|
|
|
|
|
2020-06-23 19:44:31 -05:00
|
|
|
description() {
|
|
|
|
const children = Object.entries(this.all())
|
|
|
|
.reduce((r, [key, [, type]]) => ({
|
|
|
|
...r,
|
|
|
|
[key]: {type},
|
|
|
|
}), {});
|
|
|
|
return {
|
|
|
|
children,
|
|
|
|
type: 'context',
|
|
|
|
};
|
|
|
|
}
|
|
|
|
|
2020-06-23 11:19:59 -05:00
|
|
|
destroy() {
|
|
|
|
this.map.clear();
|
|
|
|
}
|
|
|
|
|
|
|
|
get(key) {
|
|
|
|
return this.has(key) ? this.map.get(key) : [undefined, 'undefined'];
|
|
|
|
}
|
|
|
|
|
|
|
|
getValue(key) {
|
|
|
|
return this.get(key)[0];
|
|
|
|
}
|
|
|
|
|
|
|
|
getType(key) {
|
|
|
|
return this.get(key)[1];
|
|
|
|
}
|
|
|
|
|
|
|
|
has(key) {
|
|
|
|
return this.map.has(key);
|
|
|
|
}
|
|
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
registerHooks({
|
|
|
|
autoreg$accept: (type, M) => {
|
|
|
|
if ('hooks' === type && 'behaviorContextGlobals' in M) {
|
|
|
|
globals.cache.clear();
|
|
|
|
}
|
|
|
|
},
|
|
|
|
}, module.id);
|