UNPKG

2.82 kBJavaScriptView Raw
1"use strict";function _interopDefault(t){return t&&"object"==typeof t&&"default"in t?t.default:t}Object.defineProperty(exports,"__esModule",{value:!0});var react=require("react"),PropTypes=_interopDefault(require("prop-types")),isShallowEqual=function(t,e){if(t===e)return!0;for(var r in t)if(!(r in e))return!1;for(var r in e)if(t[r]!==e[r])return!1;return!0},isObjectNotNull=function(t,e){return"object"==typeof t&&"object"==typeof e&&null!==t&&null!==e},State=function(r){function t(t,e){r.call(this,t,e),this.broadcast=e.__statty__.broadcast,this.inspect=e.__statty__.inspect,this.state=t.state?t.state:t.select(this.broadcast.getState()),this.update=this.update.bind(this),this.setStateIfNeeded=this.setStateIfNeeded.bind(this)}return r&&(t.__proto__=r),((t.prototype=Object.create(r&&r.prototype)).constructor=t).prototype.update=function(t){if(this.props.state)this.setState(t);else{var e=this.broadcast.getState(),r=t(e);this.inspect&&this.inspect(e,r,t),this.broadcast.setState(r)}},t.prototype.setStateIfNeeded=function(t){var e=this.state,r=this.props.select(t);isObjectNotNull(e,r)&&isShallowEqual(e,r)||this.setState(r)},t.prototype.componentDidMount=function(){this.props.state||(this.subscriptionId=this.broadcast.subscribe(this.setStateIfNeeded),this.setStateIfNeeded(this.broadcast.getState()))},t.prototype.componentWillUnmount=function(){this.subscriptionId&&this.broadcast.unsubscribe(this.subscriptionId)},t.prototype.render=function(){return this.props.render(this.props.select(this.props.state?this.state:this.broadcast.getState()),this.update)||null},t}(react.Component);function createBroadcast(t){var o={},r=1,i=t;return{getState:function(){return i},setState:function(t){i=t;for(var e=Object.keys(o),r=0,s=e.length;r<s;r++)o[e[r]]&&o[e[r]](t)},subscribe:function(t){if("function"!=typeof t)throw new Error("listener must be a function.");var e=r;return o[e]=t,r+=1,e},unsubscribe:function(t){o[t]=void 0}}}State.defaultProps={select:function(t){return t},render:function(){return null}},State.contextTypes={__statty__:PropTypes.object.isRequired},State.propTypes={state:PropTypes.object,render:PropTypes.func,select:PropTypes.func};var Provider=function(r){function t(t,e){r.call(this,t,e),this.broadcast=createBroadcast(t.state)}return r&&(t.__proto__=r),((t.prototype=Object.create(r&&r.prototype)).constructor=t).prototype.getChildContext=function(){return{__statty__:{broadcast:this.broadcast,inspect:this.props.inspect}}},t.prototype.render=function(){var t=this.props.children;return Array.isArray(t)?t[0]:t},t}(react.Component);Provider.childContextTypes={__statty__:PropTypes.object},Provider.propTypes={inspect:PropTypes.func,state:PropTypes.object.isRequired,children:PropTypes.node.isRequired},exports.Provider=Provider,exports.State=State;
2//# sourceMappingURL=statty.cjs.min.js.map