import { h, Component } from "preact"; import MessageArea from "./message-area"; import { botman } from "./botman"; import { IMessage, IConfiguration } from "../typings"; export default class Chat extends Component { [key: string]: any botman: any; input: HTMLInputElement; textarea: HTMLInputElement; constructor(props: IChatProps) { super(props); this.botman = botman; this.botman.setUserId(this.props.userId); this.botman.setChatServer(this.props.conf.chatServer); this.state.messages = []; this.state.replyType = ReplyType.Text; } componentDidMount() { if (!this.state.messages.length && this.props.conf.introMessage) { this.writeToMessages({ text: this.props.conf.introMessage, type: "text", from: "chatbot" }); } // Add event listener for widget API window.addEventListener("message", (event: MessageEvent) => { try { this[event.data.method](...event.data.params); } catch (e) { // } }); } sayAsBot(text: string) { this.writeToMessages({ text, type: "text", from: "chatbot" }); } say(text: string, showMessage = true) { const message: IMessage = { text, type: "text", from: "visitor" }; // Send a message from the html user to the server this.botman.callAPI(message.text, false, null, (msg: IMessage) => { msg.from = "chatbot"; this.writeToMessages(msg); }); if (showMessage) { this.writeToMessages(message); } } whisper(text: string) { this.say(text, false); } render({}, state: IChatState) { return (
{this.state.replyType === ReplyType.Text ? ( { this.input = input as HTMLInputElement; }} onKeyPress={this.handleKeyPress} autofocus /> ) : ''} {this.state.replyType === ReplyType.TextArea ? (