在botframework网络聊天中发送消息(来自建议)后,如何清除聊天输入框? [英] How can i clear the chat input-box after sending the message(from suggestion) in botframework webchat?

查看:95
本文介绍了在botframework网络聊天中发送消息(来自建议)后,如何清除聊天输入框?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用react js和botframework网络聊天来开发机器人应用程序.事情是,我想在发送消息后清除文本输入框(从中发送消息),这是从建议中选择的.建议列表(或自动完成组件)是自定义编码的.我的意思是,如果我键入"hr",建议列表弹出窗口就会出现,如果我从建议中单击一个选项,说"hr门户",它将被发送,但是我写的是"hr".仍然在那里输入字段中,我想清除这一点.并请注意,如果我键入内容并发送正常.问题仅在于当我键入某些内容并从建议中选择某些内容时.其他一切都很好.我该如何清除.任何帮助将不胜感激.

i'm working on a bot application using react js and botframework webchat. The thing is that i want to clear the text input box (from where msgs are sent) after sending the message - which is selected from the suggestion. The Suggestion list(or autocomplete component) is a custom coded one. And What i mean is that if i type "hr" the suggestion list popup will come and if i click on one option from the suggestion, say 'hr portal', it will be sent, but what i wrote ie "hr" remains there in the input field and i want to clear that. And please note that If i type something and send its working fine. The problem is only when i type something and select something from the suggestion. Everything else is fine. How can i clear that. Any help would be really appreciated.

请找到下面的图片以进一步了解.

please find the below image for more understanding.

这是我的代码;

import React from 'react';
import { DirectLine, ConnectionStatus } from 'botframework-directlinejs';
import ReactWebChat from 'botframework-webchat';
import './ChatComponent.css';
var val;
var apiParameters = [];
var currentFocus = -1;
export default class extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            token: '',
            conversationId: '',
            directLine: {},
            view: false,
            feedBack: null,
            value: '',
            popupContent: '',
            storeValue: '',
            suggestions: [],
            suggestionCallback: '',
            suggestionTypedText: "",
            typingChecking: "false",
        };
        this.handleTokenGeneration = this.handleTokenGeneration.bind(this);
        this.handleChange = this.handleChange.bind(this);
        this.handleSaveFeedback = this.handleSaveFeedback.bind(this);
        this.handleSuggestion = this.handleSuggestion.bind(this);
        this.handleClose = this.handleClose.bind(this);
        this.handleSuggestionClick = this.handleSuggestionClick.bind(this);
        this.handleKeyDown = this.handleKeyDown.bind(this);
        this.moveHighlight = this.moveHighlight.bind(this);
        this.getSuggestionHtml = this.getSuggestionHtml.bind(this);
    }
    getSuggestionHtml(suggestion) {
        const lowerCaseSuggestion = suggestion.toLowerCase();
        return {
            __html: lowerCaseSuggestion.includes(this.state.suggestionTypedText) ? lowerCaseSuggestion
                .replace(this.state.suggestionTypedText, `<b>${this.state.suggestionTypedText}</b>`) : lowerCaseSuggestion
        };
    }
    handleTokenGeneration = async () => {
        console.log("11111");
        const response = await fetch(`api/TokenGenerationService/GetToken`);
        const data = await response.json();
        this.setState({
            token: data.categoryObject.token, conversationId:
                data.categoryObject.conversationId
        });
        this.state.directLine = new DirectLine({ token: this.state.token });
        this.setState({ view: true });
        this.setState({ typingChecking: "true" });
        console.log("conversationId");
    };
    async handleSuggestion(val, store) {
        if (val === "") {
            this.setState({
                suggestions: []
            });
        }
        else {
            apiParameters = [];
            var valuess = null;
            const response = await fetch(`api/TokenGenerationService/GetAzureSearch?myparam1=${val}`);
            const data = await response.json();
            var values = ["Hello", "yes", "no", "exit", "Welcome", "Thank You", "Approve", "Apply leave", "Reject", "Absence Balance", "Leave Balance", "Upcoming Holidays", "Apply Comp-Off", "Approve Leave", "Raise Incident Tickets", "Project Allocation Info", "Reporting Manager Change", "Reporting Manager Approval", "Approve Isolve Tickets", "My Manager", "My Account Manager", "Generate Salary Certificate", "Isolve Ticket Status", "Internal Job Posting", "My Designation", "My Joining Date", "RM Approval", "RM Change", "Resource Allocation", "ESettlement Approval", "SO Approval", "Cash advance Approval", "Purchase Request Approval", "Referral status", "HR Ticket", "Platinum Support"];
            valuess = values.filter(s =>
                s.toLocaleLowerCase().startsWith(val.toLowerCase())
            );
            valuess = valuess.concat(data.az_search);
            this.setState({
                suggestions: valuess,
                suggestionCallback: store,
                suggestionTypedText: val.toLowerCase()
            });
            // alert(data.az_search);
            var totCount = data.az_search;
            console.log("kkkkkk" + totCount);
        }
    }
    moveHighlight(event, direction) {
        event.preventDefault();
        const { highlightedIndex, suggestions } = this.state;
        if (!suggestions.length) return;
        let newIndex = (highlightedIndex + direction + suggestions.length) % suggestions.length;
        if (newIndex !== highlightedIndex) {
            this.setState({
                highlightedIndex: newIndex,
            });
        }
    }
    keyDownHandlers = {
        ArrowDown(event) {
            this.moveHighlight(event, 1);
        },
        ArrowUp(event) {
            this.moveHighlight(event, -1);
        },
        Enter(event) {
            const { suggestions } = this.state;
            if (!suggestions.length) {
                // menu is closed so there is no selection to accept -> do nothing
                return
            }
            event.preventDefault()
            this.applySuggestion(suggestions[this.state.highlightedIndex]);
        },
    }
    handleKeyDown(event) {
        // console.log("lokkkkkkkkkkkk")
        if (this.keyDownHandlers[event.key])
            this.keyDownHandlers[event.key].call(this, event)
    }
    async handleSuggestionClick(event) {
        await this.applySuggestion(event.currentTarget.textContent);
    }
    async applySuggestion(newValue) {
        //newValue = null;
        await this.setState({ typingChecking: "false", suggestions: [], highlightedIndex: 0 });
        this.state.suggestionCallback.dispatch({
            type: 'WEB_CHAT/SEND_MESSAGE',
            payload: {
                text: newValue
            }
        });
        await this.setState({ typingChecking: "true" });
    }
    getSuggestionCss(index) {
        var HIGHLIGHTED_CSS = "HIGHLIGHTED_CSS";
        var SUGGESTION_CSS = "SUGGESTION_CSS";
        return index === this.state.highlightedIndex ? HIGHLIGHTED_CSS : SUGGESTION_CSS;
    }
    handleClose(elmnt) {
        var x = document.getElementsByClassName("autocomplete-items");
        for (var i = 0; i < x.length; i++) {
            if (elmnt !== x[i]) {
                x[i].parentNode.removeChild(x[i]);
            }
        }
    }
    async componentDidMount() {
        try {
            await this.handleTokenGeneration();
            const store =
                window.WebChat.createStore(
                    {},
                    ({ getState }) => next => action => {
                        this.state.directLine.connectionStatus$
                            .subscribe(connectionStatus => {
                                if (connectionStatus === ConnectionStatus.ExpiredToken) {
                                    console.log("expired");
                                }
                                if (action.type === 'WEB_CHAT/SET_SEND_BOX') {
                                    const val = action.payload.text;
                                    if (this.state.typingChecking === "true") {
                                        this.setState({
                                            highlightedIndex: -1,
                                        });
                                        console.log(this.state.typingChecking);
                                        this.handleSuggestion(val, store);
                                    }
                                }
                                if (action.type === 'DIRECT_LINE/DISCONNECT_FULFILLED') {
                                    console.log("final" + connectionStatus);
                                    console.log("finalexpired" + ConnectionStatus.ExpiredToken);
                                    console.log("final");
                                    this.handleTokenGeneration();
                                }
                            });
                        return next(action)
                    }
                );
            this.setState({ storeValue: store });
        } catch (error) {
            console.log("error in fetching token");
            console.log(error);
        }
        this.state.directLine.activity$
            .filter(activity => activity.type === 'message')
            .subscribe(function (activity) {
                //console.log("oooooooooooooooooooooo");
            }
                // message => console.log("received message ", message.text)
            );
    }
    handleSaveFeedback(ans) {
        // console.log(this.state.conversationId);
        //  console.log(this.state.feedBack);
        var userID = "C94570";
        var feedbackmsg = this.state.value;
        var feedbacktype = this.state.feedBack;
        var convId = this.state.conversationId;
        fetch('api/Feedback/SaveFeedback',
            {
                method: "POST",
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ Uid: userID, FeedbackMessage: feedbackmsg, Convid: convId, FeedbackType: feedbacktype })
            }).
            then(response => response.text())
            .then(data => {
                console.log(data.getResult);
            });
        this.setState({ value: '' });
    }
    feedback(ans) {
        this.setState({ feedBack: ans });
        if (ans === "Send") {
            this.handleSaveFeedback(ans);
        }
        else if (ans === "Yes") {
            this.setState({ popupContent: "How was your experience?" });
            // console.log(this.state.value)
        }
        else if (ans === "No") {
            this.setState({ popupContent: "What went wrong?" });
            // console.log(this.state.value)
        }
    }
    handleChange = (event) => {
        this.setState({ value: event.target.value });
    }
    styleOptions = {
        bubbleBackground: 'rgba(0, 0, 255, .1)',
        bubbleFromUserBackground: 'rgba(0, 255, 0, .1)',
        botAvatarInitials: 'DIA',
        userAvatarInitials: 'ME'
    }
    render() {
        if (!this.state.view) {
            return
            <div />
        } else {
            const filteredSuggestions = this.state.suggestions.filter(
                suggestion =>
                    suggestion.toLowerCase().indexOf(this.state.suggestionTypedText.toLowerCase())
                    > -1
            );
            //   console.log(this.state.view);
            return (
                <div className="react-container webchat" >
                    <div onKeyDown={this.handleKeyDown.bind(this)}>
                        <div >
                            <ReactWebChat styleOptions={this.styleOptions} directLine={this.state.directLine} webSocket={true} userID='C94570' username='Thomas' store={this.state.storeValue} sendTypingIndicator={true} />
                        </div>
                    </div>
                    <div className="SuggestionParent" id="Suggestion1">
                        {this.state.suggestions.map((suggestion, index) => (
                            <div className={this.getSuggestionCss(index)} key={index} onClick={this.handleSuggestionClick} >
                                {suggestion
                                    .toLowerCase()
                                    .startsWith(this.state.suggestionTypedText) ? (
                                        <div>
                                            <b>{this.state.suggestionTypedText}</b>
                                            {suggestion
                                                .toLowerCase()
                                                .replace(this.state.suggestionTypedText, "")}
                                        </div>
                                    ) : (
                                        <div dangerouslySetInnerHTML={this.getSuggestionHtml(suggestion)} />
                                    )}
                            </div>
                        ))}
                    </div>
                    <footer className="chat-footer" >
                        <div className="foot-footer">
                            Was I helpful ?
         <span className="feedback" onClick={() => this.feedback("Yes")} >Yes</span><span>|</span><span className="feedback" onClick={() => this.feedback("No")}>No</span>
                            {
                                this.state.feedBack === "Yes" || this.state.feedBack === "No" ?
                                    (
                                        <div className="dialog" id="myform">
                                            <div id="textfeedback">
                                                <span id="closeFeedback" onClick={() => this.feedback("Close")}>X</span>
                                                <p>{this.state.popupContent}</p>
                                                <input type="text" id="feedbacktxtbox" required name="textfeedback" placeholder="Pleasure to hear from u!"
                                                    onChange={this.handleChange}
                                                    value={this.state.value} />
                                                <button type="button" id="btnfeedback" onClick={() => this.feedback("Send")}>send</button>
                                            </div>
                                        </div>
                                    ) : null
                            }
                        </div>
                    </footer>
                </div>
            );
        }
    }
}

推荐答案

聊天输入框在Web聊天中称为发送框.清除发送框只是将发送框设置为空字符串.当您正常单击发送按钮时,此操作将自动完成.您可以在提交发送框中看到传奇提交发件箱意味着执行两项操作:发送消息和设置发件箱.

The chat input box is called the send box in Web Chat. Clearing the send box is just setting the send box with an empty string. This is done automatically when you click on the send button normally. You can see in the submit send box saga that submitting the send box means performing two actions: sending the message and setting the send box.

if (sendBoxValue) {
  yield put(sendMessage(sendBoxValue.trim(), method, { channelData }));
  yield put(setSendBox(''));
}

这意味着,如果您使用SUBMIT_SEND_BOX操作,则发送框将被自动清除.当然,如果您希望它与自动完成组件一起使用,则需要在发送框设置自动完成文本,然后再提交.您的另一种选择是在发送消息后仅将SET_SEND_BOX操作与空字符串一起使用.

This means that if you use the SUBMIT_SEND_BOX action then the send box will be cleared automatically. Of course, if you want that to work with your autocomplete component then you'll need to set the send box with the autocompleted text before you submit it. Your other option is to just use the SET_SEND_BOX action with an empty string after you send the message.

这篇关于在botframework网络聊天中发送消息(来自建议)后,如何清除聊天输入框?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆