UNPKG

@adpt/core

Version:
86 lines 3.27 kB
"use strict"; /* * Copyright 2018-2019 Unbounded Systems, LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ Object.defineProperty(exports, "__esModule", { value: true }); const tslib_1 = require("tslib"); const index_1 = require("./index"); const jsx_1 = require("./jsx"); const keys_1 = require("./keys"); const ld = tslib_1.__importStar(require("lodash")); function createContext(defaultValue) { const stack = []; // class Provider function providerPush(provider) { stack.push(provider); } function providerPop() { stack.pop(); } function currentVal() { if (stack.length > 0) { return stack[stack.length - 1].props.value; } return defaultValue; } // tslint:disable-next-line:no-shadowed-variable class Provider extends jsx_1.Component { constructor() { super(...arguments); this.cleanup = () => providerPop(); } build() { const { children: child, key } = this.props; if ((child == null) || Array.isArray(child) || !jsx_1.isElement(child)) { throw new index_1.BuildNotImplemented(`A context Provider may only have a single child, which ` + `must be a Component or SFC`); } providerPush(this); // If there was an explicit key set (i.e. not default), propagate // our key to our child, but don't overwrite any key // already on the child props. if (!key || keys_1.isDefaultKey(this.props) || "key" in child.props) return child; const _a = child.props, { children, handle } = _a, childProps = tslib_1.__rest(_a, ["children", "handle"]); return jsx_1.cloneElement(child, Object.assign({ key }, childProps), children); } } // tslint:disable-next-line:no-shadowed-variable class Consumer extends jsx_1.Component { build() { const { children } = this.props; if ((children == null) || Array.isArray(children) || !ld.isFunction(children)) { throw new index_1.BuildNotImplemented(`Children of a context Consumer must be a single function`); } return this.props.children(currentVal()); } } const ret = { Provider, Consumer, currentVal: () => currentVal() }; return ret; } exports.createContext = createContext; function isContextImpl(context) { return ("currentVal" in context); } function useContext(context) { if (!isContextImpl(context)) throw new Error("useContext context not a ContextImpl"); return context.currentVal(); } exports.useContext = useContext; //# sourceMappingURL=context.js.map