UNPKG

dash-renderer

Version:

render dash components in react

347 lines (340 loc) 18.2 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = void 0; var _react = _interopRequireWildcard(require("react")); var _ramda = require("ramda"); var _reactRedux = require("react-redux"); var _ComponentErrorBoundary = _interopRequireDefault(require("../components/error/ComponentErrorBoundary.react")); var _actions = require("../actions"); var _dependencies = require("../actions/dependencies"); var _wrapping = require("./wrapping"); var _registry = _interopRequireDefault(require("../registry")); var _isSimpleComponent = _interopRequireDefault(require("../isSimpleComponent")); var _selectors = require("./selectors"); var _CheckedComponent = _interopRequireDefault(require("./CheckedComponent")); var _DashContext = require("./DashContext"); var _excluded = ["componentPath", "_dashprivate_error", "_passedComponent", "_newRender"], _excluded2 = ["_dash_error"]; function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; } function _interopRequireWildcard(e, t) { if ("function" == typeof WeakMap) var r = new WeakMap(), n = new WeakMap(); return (_interopRequireWildcard = function _interopRequireWildcard(e, t) { if (!t && e && e.__esModule) return e; var o, i, f = { __proto__: null, default: e }; if (null === e || "object" != typeof e && "function" != typeof e) return f; if (o = t ? n : r) { if (o.has(e)) return o.get(e); o.set(e, f); } for (var _t in e) "default" !== _t && {}.hasOwnProperty.call(e, _t) && ((i = (o = Object.defineProperty) && Object.getOwnPropertyDescriptor(e, _t)) && (i.get || i.set) ? o(f, _t, i) : f[_t] = e[_t]); return f; })(e, t); } function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; } function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; } function _defineProperty(e, r, t) { return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; } function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == typeof i ? i : i + ""; } function _toPrimitive(t, r) { if ("object" != typeof t || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != typeof i) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } function _slicedToArray(r, e) { return _arrayWithHoles(r) || _iterableToArrayLimit(r, e) || _unsupportedIterableToArray(r, e) || _nonIterableRest(); } function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } function _unsupportedIterableToArray(r, a) { if (r) { if ("string" == typeof r) return _arrayLikeToArray(r, a); var t = {}.toString.call(r).slice(8, -1); return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0; } } function _arrayLikeToArray(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; } function _iterableToArrayLimit(r, l) { var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (null != t) { var e, n, i, u, a = [], f = !0, o = !1; try { if (i = (t = t.call(r)).next, 0 === l) { if (Object(t) !== t) return; f = !1; } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0); } catch (r) { o = !0, n = r; } finally { try { if (!f && null != t.return && (u = t.return(), Object(u) !== u)) return; } finally { if (o) throw n; } } return a; } } function _arrayWithHoles(r) { if (Array.isArray(r)) return r; } function _objectWithoutProperties(e, t) { if (null == e) return {}; var o, r, i = _objectWithoutPropertiesLoose(e, t); if (Object.getOwnPropertySymbols) { var n = Object.getOwnPropertySymbols(e); for (r = 0; r < n.length; r++) o = n[r], -1 === t.indexOf(o) && {}.propertyIsEnumerable.call(e, o) && (i[o] = e[o]); } return i; } function _objectWithoutPropertiesLoose(r, e) { if (null == r) return {}; var t = {}; for (var n in r) if ({}.hasOwnProperty.call(r, n)) { if (-1 !== e.indexOf(n)) continue; t[n] = r[n]; } return t; } // Define a type for the memoized keys function DashWrapper(_ref) { var componentPath = _ref.componentPath, _dashprivate_error = _ref._dashprivate_error, _passedComponent = _ref._passedComponent, _newRender = _ref._newRender, extras = _objectWithoutProperties(_ref, _excluded); var dispatch = (0, _reactRedux.useDispatch)(); var memoizedKeys = (0, _react.useRef)({}); var newRender = (0, _react.useRef)(false); var renderedPath = (0, _react.useRef)(componentPath); var renderComponent = null; var renderComponentProps = null; var renderH = null; // Get the config for the component as props var config = (0, _reactRedux.useSelector)(_selectors.selectConfig); // Select component and it's props, along with render hash, changed props and the reason for render var _useSelector = (0, _reactRedux.useSelector)((0, _selectors.selectDashProps)(componentPath), _selectors.selectDashPropsEqualityFn), _useSelector2 = _slicedToArray(_useSelector, 5), component = _useSelector2[0], componentProps = _useSelector2[1], h = _useSelector2[2], changedProps = _useSelector2[3], renderType = _useSelector2[4]; renderComponent = component; renderComponentProps = componentProps; renderH = h; (0, _react.useMemo)(() => { if (_newRender) { newRender.current = true; renderH = 0; if (renderH in memoizedKeys.current) { delete memoizedKeys.current[renderH]; } } else { newRender.current = false; } renderedPath.current = componentPath; }, [_newRender]); var setProps = newProps => { var _renderComponentProps = renderComponentProps, id = _renderComponentProps.id; var _dash_error = newProps._dash_error, restProps = _objectWithoutProperties(newProps, _excluded2); // eslint-disable-next-line @typescript-eslint/ban-ts-comment // @ts-ignore dispatch((dispatch, getState) => { var currentState = getState(); var graphs = currentState.graphs; var oldLayout = (0, _wrapping.getComponentLayout)(renderedPath.current, currentState); if (!oldLayout) return; var oldProps = oldLayout.props; if (!oldProps) return; var changedProps = (0, _ramda.pickBy)((val, key) => !(0, _ramda.equals)(val, oldProps[key]), restProps); if (_dash_error) { dispatch((0, _actions.onError)({ type: 'frontEnd', error: _dash_error })); } if ((0, _ramda.isEmpty)(changedProps)) { return; } // Identify the modified props that are required for callbacks var watchedKeys = (0, _dependencies.getWatchedKeys)(id, (0, _ramda.keys)(changedProps), graphs); (0, _reactRedux.batch)(() => { // Only dispatch changes to Dash if a watched prop changed if (watchedKeys.length) { dispatch((0, _actions.notifyObservers)({ id, props: (0, _ramda.pick)(watchedKeys, changedProps) })); } // Always update this component's props dispatch((0, _actions.updateProps)({ props: changedProps, itempath: renderedPath.current, renderType: 'internal' })); }); }); }; var createContainer = (0, _react.useCallback)((container, containerPath, _childNewRender) => { var _container$props; if ((0, _isSimpleComponent.default)(renderComponent)) { return renderComponent; } return /*#__PURE__*/_react.default.createElement(DashWrapper, { key: container !== null && container !== void 0 && (_container$props = container.props) !== null && _container$props !== void 0 && _container$props.id ? (0, _dependencies.stringifyId)(container.props.id) : (0, _wrapping.stringifyPath)(containerPath), _dashprivate_error: _dashprivate_error, componentPath: containerPath, _passedComponent: container, _newRender: _childNewRender }); }, []); var wrapChildrenProp = (0, _react.useCallback)((node, childrenPath, _childNewRender) => { if (Array.isArray(node)) { return node.map((n, i) => { if ((0, _wrapping.isDryComponent)(n)) { return createContainer(n, (0, _ramda.concat)(componentPath, ['props', ...childrenPath, i]), _childNewRender); } return n; }); } if (!(0, _wrapping.isDryComponent)(node)) { return node; } return createContainer(node, (0, _ramda.concat)(componentPath, ['props', ...childrenPath]), _childNewRender); }, [componentPath]); var extraProps = _objectSpread({ setProps }, extras); if ((0, _wrapping.checkRenderTypeProp)(renderComponent)) { extraProps['dashRenderType'] = newRender.current ? 'parent' : changedProps ? renderType : 'parent'; } var setHydratedProps = (component, componentProps) => { // Hydrate components props var childrenProps = (0, _ramda.pathOr)([], ['children_props', component === null || component === void 0 ? void 0 : component.namespace, component === null || component === void 0 ? void 0 : component.type], config); var props = (0, _ramda.mergeRight)((0, _ramda.dissoc)('children', componentProps), extraProps); var _loop = function _loop() { var childrenProp = childrenProps[i]; var childNewRender = 0; if (childrenProp.split('.')[0].replace('[]', '').replace('{}', '') in changedProps || newRender.current || !renderH) { childNewRender = {}; } var handleObject = (obj, opath) => { return (0, _ramda.mapObjIndexed)((node, k) => wrapChildrenProp(node, [...opath, k], childNewRender), obj); }; if (childrenProp.includes('.')) { var childrenPath = childrenProp.split('.'); var node; var nodeValue; if (childrenProp.includes('[]')) { var _node; var frontPath = [], backPath = []; var found = false, hasObject = false; // At first the childrenPath is always a list of strings. childrenPath.forEach(p => { if (!found) { if (p.includes('[]')) { found = true; if (p.includes('{}')) { hasObject = true; frontPath.push(p.replace('{}', '').replace('[]', '')); } else { frontPath.push(p.replace('[]', '')); } } else if (p.includes('{}')) { hasObject = true; frontPath.push(p.replace('{}', '')); } else { frontPath.push(p); } } else { if (p.includes('{}')) { hasObject = true; backPath.push(p.replace('{}', '')); } else { backPath.push(p); } } }); node = (0, _ramda.path)(frontPath, props); if (node === undefined || !((_node = node) !== null && _node !== void 0 && _node.length)) { return 0; // continue } var firstNode = (0, _ramda.path)(backPath, node[0]); if (!firstNode) { return 0; // continue } nodeValue = node.map((el, i) => { var elementPath = (0, _ramda.concat)(frontPath, (0, _ramda.concat)([i], backPath)); var listValue; if (hasObject) { if (backPath.length) { listValue = handleObject((0, _ramda.path)(backPath, el), elementPath); } else { listValue = handleObject(el, elementPath); } } else { listValue = wrapChildrenProp((0, _ramda.path)(backPath, el), elementPath, childNewRender); } return (0, _ramda.assocPath)(backPath, listValue, el); }); childrenPath = frontPath; } else { if (childrenProp.includes('{}')) { // Only supports one level of nesting. var front = []; var dynamic = []; var hasBack = false; var _backPath = []; for (var j = 0; j < childrenPath.length; j++) { var cur = childrenPath[j]; if (cur.includes('{}')) { dynamic = (0, _ramda.concat)(front, [cur.replace('{}', '')]); if (j < childrenPath.length - 1) { hasBack = true; } } else { if (hasBack) { _backPath.push(cur); } else { front.push(cur); } } } var dynValue = (0, _ramda.path)(dynamic, props); if (dynValue !== undefined) { // too dynamic for proper ts. // eslint-disable-next-line @typescript-eslint/ban-ts-comment // @ts-ignore nodeValue = (0, _ramda.mapObjIndexed)((d, k) => wrapChildrenProp(hasBack ? (0, _ramda.path)(_backPath, d) : d, hasBack ? (0, _ramda.concat)(dynamic, (0, _ramda.concat)([k], _backPath)) : (0, _ramda.concat)(dynamic, [k]), childNewRender), dynValue); childrenPath = dynamic; } } else { node = (0, _ramda.path)(childrenPath, props); if (node === undefined) { return 0; // continue } nodeValue = wrapChildrenProp(node, childrenPath, childNewRender); } } props = (0, _ramda.assocPath)(childrenPath, nodeValue, props); } else { if (childrenProp.includes('{}')) { var opath = childrenProp.replace('{}', ''); var isArray = childrenProp.includes('[]'); if (isArray) { opath = opath.replace('[]', ''); } var _node2 = props[opath]; if (_node2 !== undefined) { if (isArray) { for (var _j = 0; _j < _node2.length; _j++) { var aPath = (0, _ramda.concat)([opath], [_j]); props = (0, _ramda.assocPath)(aPath, handleObject(_node2[_j], aPath), props); } } else { props = (0, _ramda.assoc)(opath, handleObject(_node2, [opath]), props); } } } else { var _node3 = props[childrenProp]; if (_node3 !== undefined) { props = (0, _ramda.assoc)(childrenProp, wrapChildrenProp(_node3, [childrenProp], childNewRender), props); } } } }, _ret; for (var i = 0; i < childrenProps.length; i++) { _ret = _loop(); if (_ret === 0) continue; } if ((0, _ramda.type)(props.id) === 'Object') { // Turn object ids (for wildcards) into unique strings. // Because of the `dissoc` above we're not mutating the layout, // just the id we pass on to the rendered component props.id = (0, _dependencies.stringifyId)(props.id); } return props; }; var hydrateFunc = () => { if (newRender.current) { renderComponent = _passedComponent; renderComponentProps = _passedComponent === null || _passedComponent === void 0 ? void 0 : _passedComponent.props; } if (!renderComponent) { return null; } var element = _registry.default.resolve(renderComponent); var hydratedProps = setHydratedProps(renderComponent, renderComponentProps); var hydratedChildren; if (renderComponentProps.children !== undefined) { hydratedChildren = wrapChildrenProp(renderComponentProps.children, ['children'], !renderH || newRender.current || 'children' in changedProps ? {} : 0); } newRender.current = false; return config.props_check ? /*#__PURE__*/_react.default.createElement(_CheckedComponent.default, { element: element, props: hydratedProps, component: renderComponent }, (0, _wrapping.createElement)(element, hydratedProps, extraProps, hydratedChildren)) : (0, _wrapping.createElement)(element, hydratedProps, extraProps, hydratedChildren); }; var hydrated = null; if (renderH in memoizedKeys.current && !newRender.current) { hydrated = /*#__PURE__*/_react.default.isValidElement(memoizedKeys.current[renderH]) ? memoizedKeys.current[renderH] : null; } if (!hydrated) { hydrated = hydrateFunc(); memoizedKeys.current = { [renderH]: hydrated }; } return renderComponent ? /*#__PURE__*/_react.default.createElement(_ComponentErrorBoundary.default, { componentType: renderComponent.type, componentId: (0, _ramda.is)(Object, renderComponentProps.id) ? (0, _dependencies.stringifyId)(renderComponentProps.id) : renderComponentProps.id, error: _dashprivate_error, dispatch: dispatch }, /*#__PURE__*/_react.default.createElement(_DashContext.DashContextProvider, { componentPath: componentPath }, /*#__PURE__*/_react.default.isValidElement(hydrated) ? hydrated : /*#__PURE__*/_react.default.createElement("div", null))) : /*#__PURE__*/_react.default.createElement("div", null); } var _default = exports.default = DashWrapper;