UNPKG

@botonic/react

Version:

Build Chatbots using React

67 lines 2.92 kB
import { jsx as _jsx } from "react/jsx-runtime"; import { isWhatsapp } from '@botonic/core'; import React, { useContext } from 'react'; import { RequestContext } from '../../contexts'; import { truncateText } from '../../util'; import { Button } from '../button/index'; import { MultichannelContext } from './multichannel-context'; import { WHATSAPP_MAX_BUTTON_CHARS } from './whatsapp/constants'; export const MultichannelButton = props => { var _a; const requestContext = useContext(RequestContext); const multichannelContext = useContext(MultichannelContext); const hasUrl = () => Boolean(props.url); const hasPath = () => Boolean(props.path); const hasPayload = () => Boolean(props.payload); const hasPostback = () => hasPath() || hasPayload(); const hasWebview = () => Boolean(props.webview); const getUrl = () => props.url; const getWebview = () => props.webview; const increaseCurrentIndex = () => { if (typeof multichannelContext.currentIndex === 'number') { multichannelContext.currentIndex += 1; } else if (typeof multichannelContext.currentIndex === 'string') { const lastChar = multichannelContext.currentIndex.charCodeAt(multichannelContext.currentIndex.length - 1); multichannelContext.currentIndex = String.fromCharCode(lastChar + 1); } }; const formatIndex = index => { var _a; const boldIndex = (_a = multichannelContext.boldIndex) !== null && _a !== void 0 ? _a : false; return boldIndex ? `*${index}*` : index; }; const getText = () => { let text = props.children; const newline = props.newline || ''; const separator = multichannelContext.indexSeparator || ' '; const index = multichannelContext.currentIndex ? `${formatIndex(multichannelContext.currentIndex + separator)} ` : ''; if (hasPostback()) { text = newline + `${index}${text}`; } else if (hasUrl()) { text = newline + `- ${text}`; } return text; }; if (isWhatsapp(requestContext.session)) { const asText = (_a = props.asText) !== null && _a !== void 0 ? _a : true; if (asText) { if (hasUrl()) { return `${getText()}: ${getUrl()}`; } else if (hasPath() || hasPayload()) { const text = getText(); increaseCurrentIndex(); return `${text}`; } else if (hasWebview()) return _jsx(Button, Object.assign({}, props, { children: getText() })); } return (_jsx(Button, Object.assign({}, props, { children: truncateText(props.children, WHATSAPP_MAX_BUTTON_CHARS) }))); } return _jsx(Button, Object.assign({}, props, { children: props.children })); }; //# sourceMappingURL=multichannel-button.js.map