@botonic/react
Version:
Build Chatbots using React
55 lines • 2.83 kB
JavaScript
import { __rest } from "tslib";
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import { INPUT } from '@botonic/core';
import merge from 'lodash.merge';
import React from 'react';
import { SENDERS } from '../constants';
import { createErrorBoundary } from '../util/error-boundary';
import { warnDeprecatedProps } from '../util/logs';
import { mapObjectNonBooleanValues } from '../util/react';
import { Message } from './message';
import { Reply } from './reply';
/**
*
* @param name as it appears at ThemeProps' message.customTypes key
* @param CustomMessageComponent
* @param defaultProps Props for the wrapper Message
* @param ErrorBoundary to recover in case it fails
*/
export const customMessage = ({ name, component: CustomMessageComponent, defaultProps = {}, errorBoundary: ErrorBoundary = createErrorBoundary(), }) => {
const CustomMessage = props => {
warnDeprecatedProps(defaultProps, 'customMessage:');
if (defaultProps.from === SENDERS.user)
defaultProps.ack = 1;
return (_jsx(Message, Object.assign({}, merge(mapObjectNonBooleanValues(defaultProps), props), { type: INPUT.CUSTOM })));
};
const splitChildren = props => {
const { children } = props;
const isReply = e => e.type === Reply;
try {
if (!Array.isArray(children) && !isReply(children)) {
return { replies: null, childrenWithoutReplies: children };
}
const childrenArray = React.Children.toArray(children);
const replies = childrenArray.filter(isReply);
const childrenWithoutReplies = childrenArray.filter(e => !isReply(e));
return {
replies: replies,
childrenWithoutReplies,
};
}
catch (e) {
return { replies: null, childrenWithoutReplies: children };
}
};
const WrappedComponent = props => {
const { id, children } = props, customMessageProps = __rest(props, ["id", "children"]);
const { replies, childrenWithoutReplies } = splitChildren(props);
return (_jsxs(CustomMessage, Object.assign({ id: id, json: Object.assign(Object.assign({}, customMessageProps), { id, children: childrenWithoutReplies, customTypeName: name }) }, { children: [_jsx(ErrorBoundary, Object.assign({}, customMessageProps, { children: _jsx(CustomMessageComponent, Object.assign({}, customMessageProps, { children: childrenWithoutReplies })) }), 'errorBoundary'), replies] })));
};
WrappedComponent.customTypeName = name;
// eslint-disable-next-line react/display-name
WrappedComponent.deserialize = msg => (_jsx(WrappedComponent, Object.assign({ id: msg.id, json: msg.data }, msg.data), msg.key));
return WrappedComponent;
};
//# sourceMappingURL=custom-message.js.map