stencil-quantum
Version:
Experience the quantum realm of stencil.
58 lines (57 loc) • 2.2 kB
JavaScript
import { Provider } from "../provider";
import { hookComponent } from "../utils";
import { throwQuantum } from "../error";
import { getElement } from "@stencil/core";
export function Context(config, key) {
return function (prototype, propertyName) {
const opts = config === null || config === void 0 ? void 0 : config.get(key);
let defaultValue = opts === null || opts === void 0 ? void 0 : opts.default;
delete prototype[propertyName];
hookComponent(prototype, "componentWillLoad", obj => {
const el = getElement(obj);
let provider;
try {
provider = Provider.find(el, key, opts === null || opts === void 0 ? void 0 : opts.namespace, opts === null || opts === void 0 ? void 0 : opts.debug);
provider.hook(el);
}
catch (err) {
}
hookComponent(prototype, "disconnectedCallback", o => {
if (o === obj) {
const el = getElement(obj);
provider === null || provider === void 0 ? void 0 : provider.pauseHook(el, true);
}
});
hookComponent(prototype, "connectedCallback", o => {
if (o === obj) {
const el = getElement(obj);
provider === null || provider === void 0 ? void 0 : provider.pauseHook(el, false);
}
});
Object.defineProperty(obj, propertyName, {
get: () => { var _a; return (_a = provider === null || provider === void 0 ? void 0 : provider.retrieve()) !== null && _a !== void 0 ? _a : defaultValue; },
set: v => {
if ((opts === null || opts === void 0 ? void 0 : opts.mutable) && (provider === null || provider === void 0 ? void 0 : provider.mutable)) {
provider.provide(v);
}
else {
defaultValue = v;
}
},
enumerable: true,
configurable: true
});
return () => {
if (provider)
return;
try {
provider = Provider.find(el, key, opts === null || opts === void 0 ? void 0 : opts.namespace, opts === null || opts === void 0 ? void 0 : opts.debug);
provider.hook(el);
}
catch (err) {
throwQuantum(el, err);
}
};
});
};
}