UNPKG

@talend/react-cmf

Version:

A framework built on top of best react libraries

97 lines (93 loc) 3.05 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.Dispatcher = Dispatcher; exports.default = void 0; var _propTypes = _interopRequireDefault(require("prop-types")); var _react = require("react"); var _cmfConnect = _interopRequireDefault(require("./cmfConnect")); var _action = _interopRequireDefault(require("./action")); var _actionCreator = _interopRequireDefault(require("./actionCreator")); var _RegistryProvider = require("./RegistryProvider"); function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; } /** * This module expose Dispatcher component. * @module react-cmf/lib/Dispatcher * @see module:react-cmf/lib/action */ /** * This component purpose is to decorate any component and map an user event * to an action to be dispatched * @example function myfunc(event, props, context) { } <Dispatcher onClick={myfunc}> <ChildrenElement /> </Dispatcher> */ function Dispatcher(props) { const registry = (0, _react.useContext)(_RegistryProvider.RegistryContext); // console.log('@@@ registry', registry); /** * on any even just try to find a onTHEEVENT props. * If found execute it with the common stuff * (event, props, context) * @param {object} event the react event dispatched event * @param {string} eventName the name of the event */ function onEvent(event, eventName) { if (props.stopPropagation) { event.stopPropagation(); } if (props.preventDefault) { event.preventDefault(); } if (props[eventName]) { props.dispatchActionCreator(props[eventName], event, props); } } function checkIfActionInfoExist() { _action.default.getOnProps(props).forEach(name => { if (typeof props[name] === 'string') { _actionCreator.default.get({ registry }, props[name]); } }); } checkIfActionInfoExist(); const onProps = _action.default.getOnProps(props); const childrenWithProps = _react.Children.map(props.children, child => { const newProps = {}; onProps.forEach(name => { newProps[name] = event => onEvent(event, name); }); return /*#__PURE__*/(0, _react.cloneElement)(child, newProps); }); return _react.Children.only(childrenWithProps[0]); } Dispatcher.propTypes = { children: _propTypes.default.node.isRequired, stopPropagation: _propTypes.default.bool, preventDefault: _propTypes.default.bool, dispatchActionCreator: _propTypes.default.func }; Dispatcher.displayName = 'Dispatcher'; Dispatcher.defaultProps = { stopPropagation: false, preventDefault: false }; const ConnectedDispatcher = (0, _cmfConnect.default)({ withDispatchActionCreator: true })(Dispatcher); /** * This component purpose is to decorate any component and map an user event * to an action to be dispatched * @example <Dispatcher onClick="actionCreator:identifier" onDrag="actionCreator:anotherid"> <ChildrenElement /> </Dispatcher> */ var _default = exports.default = ConnectedDispatcher; //# sourceMappingURL=Dispatcher.js.map