UNPKG

@atlaskit/editor-core

Version:

A package contains Atlassian editor core functionality

74 lines 2.77 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var tslib_1 = require("tslib"); var React = require("react"); /** * Wraps component in a high order component that watches state changes of given plugins * and passes those states to the wrapped component. * * Example: * <WithPluginState * eventDispatcher={eventDispatcher} * editorView={editorView} * plugins={{ * hyperlink: hyperlinkPluginKey * }} * render={renderComponent} * /> * * renderComponent: ({ hyperlink }) => React.Compoment; */ var WithPluginState = (function (_super) { tslib_1.__extends(WithPluginState, _super); function WithPluginState() { var _this = _super !== null && _super.apply(this, arguments) || this; _this.state = {}; _this.listeners = {}; return _this; } WithPluginState.prototype.handlePluginStateChange = function (propName, pluginState) { if (this.state[propName] !== pluginState) { this.setState((_a = {}, _a[propName] = pluginState, _a)); } var _a; }; WithPluginState.prototype.subscribe = function (props) { var _this = this; var eventDispatcher = props.eventDispatcher, editorView = props.editorView, plugins = props.plugins; if (!eventDispatcher || !editorView) { return; } var pluginsState = Object.keys(plugins).reduce(function (acc, propName) { var pluginKey = plugins[propName]; var handler = _this.handlePluginStateChange.bind(_this, propName); eventDispatcher.on(pluginKey.key, handler); _this.listeners[pluginKey.key] = handler; acc[propName] = pluginKey.getState(editorView.state); return acc; }, {}); this.setState(pluginsState); }; WithPluginState.prototype.componentWillMount = function () { this.subscribe(this.props); }; WithPluginState.prototype.componentWillReceiveProps = function (nextProps, prevProps) { if (nextProps.eventDispatcher && nextProps.eventDispatcher && !prevProps.eventDispatcher) { this.subscribe(nextProps); } }; WithPluginState.prototype.componentWillUnmount = function () { var _this = this; var eventDispatcher = this.props.eventDispatcher; if (!eventDispatcher) { return; } Object.keys(this.listeners).forEach(function (key) { return eventDispatcher.off(key, _this.listeners[key]); }); }; WithPluginState.prototype.render = function () { var render = this.props.render; return render(this.state); }; return WithPluginState; }(React.Component)); exports.default = WithPluginState; //# sourceMappingURL=index.js.map