UNPKG

react-magic-state

Version:
58 lines (57 loc) 2.01 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const react_1 = require("react"); const core_1 = require("./core"); function view(component) { var _a; let wrapper; if ((_a = component.prototype) === null || _a === void 0 ? void 0 : _a.isReactComponent) { wrapper = wrapComponentClass(component); } else { wrapper = wrapFunctionComponent(component); } return wrapper; } exports.view = view; function wrapComponentClass(component) { const baseClass = component; const wrapper = class extends baseClass { constructor(props) { super(props); this.state = Object.assign(Object.assign({}, super.state), { reactionCount: 0 }); this._increaseReactionCount = this._increaseReactionCount.bind(this); this.render = core_1.wrapObserver(this.render); } componentDidMount() { core_1.addReaction(this.render, this._increaseReactionCount); if (super.componentDidMount) { super.componentDidMount(); } } componentWillUnmount() { if (super.componentWillUnmount) { super.componentWillUnmount(); } this.render = core_1.unwrapObserver(this.render); } _increaseReactionCount() { this.setState({ reactionCount: this.state.reactionCount + 1 }); } }; return wrapper; } function wrapFunctionComponent(component) { const wrapper = core_1.wrapObserver(function () { const [, setState] = react_1.useState(0); react_1.useEffect(() => { core_1.addReaction(wrapper, () => { setState(s => s + 1); return () => core_1.unwrapObserver(wrapper); }); }, []); return Reflect.apply(component, this, arguments); }); wrapper["displayName"] = component.name; return wrapper; }