@botonic/plugin-flow-builder
Version:
Use Flow Builder to show your contents
73 lines • 3.41 kB
JavaScript
import { __awaiter } from "tslib";
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import { Text } from '@botonic/react';
import { ACCESS_TOKEN_VARIABLE_KEY, EMPTY_PAYLOAD, SOURCE_INFO_SEPARATOR, VARIABLE_PATTERN, } from '../constants';
import { trackOneContent } from '../tracking';
import { getValueFromKeyPath } from '../utils';
import { ContentFieldsBase } from './content-fields-base';
import { FlowButton } from './flow-button';
import { HtButtonStyle } from './hubtype-fields';
export class FlowText extends ContentFieldsBase {
constructor() {
super(...arguments);
this.text = '';
this.buttons = [];
this.buttonStyle = HtButtonStyle.BUTTON;
}
static fromHubtypeCMS(cmsText, locale, cmsApi) {
const newText = new FlowText(cmsText.id);
newText.code = cmsText.code;
newText.buttonStyle = cmsText.content.buttons_style || HtButtonStyle.BUTTON;
newText.text = this.getTextByLocale(locale, cmsText.content.text);
newText.buttons = cmsText.content.buttons.map(button => FlowButton.fromHubtypeCMS(button, locale, cmsApi));
newText.followUp = cmsText.follow_up;
return newText;
}
static replaceVariables(text, request) {
const matches = text.match(VARIABLE_PATTERN);
let replacedText = text;
if (matches && request) {
matches.forEach(match => {
const keyPath = match.slice(1, -1);
const botVariable = keyPath.endsWith(ACCESS_TOKEN_VARIABLE_KEY)
? match
: getValueFromKeyPath(request, keyPath);
// TODO In local if change variable and render multiple times the value is always the last update
replacedText = replacedText.replace(match, this.isValidType(botVariable) ? botVariable : match);
});
}
return replacedText;
}
static isValidType(botVariable) {
const validTypes = ['boolean', 'string', 'number'];
return validTypes.includes(typeof botVariable);
}
trackFlow(request) {
return __awaiter(this, void 0, void 0, function* () {
yield trackOneContent(request, this);
for (const button of this.buttons) {
yield button.trackFlow(request);
}
});
}
static fromAIAgent(id, textMessage) {
if (textMessage.type === 'text') {
return _jsx(Text, { children: textMessage.content.text }, id);
}
return (_jsxs(Text, { children: [textMessage.content.text, textMessage.content.buttons.map((button, buttonIndex) => {
const buttonData = {
id: `${id}-button-${buttonIndex}`,
text: button.text,
url: button.url,
payload: button.payload ||
`${EMPTY_PAYLOAD}${SOURCE_INFO_SEPARATOR}${buttonIndex}`,
};
return FlowButton.fromAIAgent(buttonData).renderButton(buttonIndex);
})] }, id));
}
toBotonic(id, request) {
const replacedText = FlowText.replaceVariables(this.text, request);
return (_jsxs(Text, { children: [replacedText, this.buttons.map((button, buttonIndex) => button.renderButton(buttonIndex, this.buttonStyle))] }, id));
}
}
//# sourceMappingURL=flow-text.js.map