Repository navigation
Expand file tree
/
Copy pathChat.tsx
More file actions
257 lines (215 loc) · 9.16 KB
/
Copy pathChat.tsx
File metadata and controls
257 lines (215 loc) · 9.16 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
import * as React from 'react';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';
import { Observable } from 'rxjs/Observable';
import { Subscription } from 'rxjs/Subscription';
import { Activity, IBotConnection, User, DirectLine, DirectLineOptions, CardActionTypes } from 'botframework-directlinejs';
import { createStore, ChatActions, sendMessage } from './Store';
import { Provider } from 'react-redux';
import { SpeechOptions } from './SpeechOptions';
import { Speech } from './SpeechModule';
import { ActivityOrID, FormatOptions } from './Types';
import * as konsole from './Konsole';
export interface ChatProps {
user: User,
bot: User,
botConnection?: IBotConnection,
directLine?: DirectLineOptions,
speechOptions?: SpeechOptions,
locale?: string,
selectedActivity?: BehaviorSubject<ActivityOrID>,
sendTyping?: boolean,
formatOptions?: FormatOptions,
resize?: 'none' | 'window' | 'detect'
}
import { History } from './History';
import { MessagePane } from './MessagePane';
import { Shell } from './Shell';
export class Chat extends React.Component<ChatProps, {}> {
private store = createStore();
private botConnection: IBotConnection;
private activitySubscription: Subscription;
private connectionStatusSubscription: Subscription;
private selectedActivitySubscription: Subscription;
private chatviewPanel: HTMLElement;
private resizeListener = () => this.setSize();
constructor(props: ChatProps) {
super(props);
konsole.log("BotChat.Chat props", props);
this.store.dispatch<ChatActions>({
type: 'Set_Locale',
locale: props.locale || (window.navigator as any)["userLanguage"] || window.navigator.language || 'en'
});
if (props.formatOptions)
this.store.dispatch<ChatActions>({ type: 'Set_Format_Options', options: props.formatOptions });
if (props.sendTyping)
this.store.dispatch<ChatActions>({ type: 'Set_Send_Typing', sendTyping: props.sendTyping });
if (props.speechOptions) {
Speech.SpeechRecognizer.setSpeechRecognizer(props.speechOptions.speechRecognizer);
Speech.SpeechSynthesizer.setSpeechSynthesizer(props.speechOptions.speechSynthesizer);
}
}
private handleIncomingActivity(activity: Activity) {
let state = this.store.getState();
switch (activity.type) {
case "message":
this.store.dispatch<ChatActions>({ type: activity.from.id === state.connection.user.id ? 'Receive_Sent_Message' : 'Receive_Message', activity });
break;
case "typing":
if (activity.from.id !== state.connection.user.id)
this.store.dispatch<ChatActions>({ type: 'Show_Typing', activity });
break;
}
}
private setSize() {
this.store.dispatch<ChatActions>({
type: 'Set_Size',
width: this.chatviewPanel.offsetWidth,
height: this.chatviewPanel.offsetHeight
});
}
componentDidMount() {
// Now that we're mounted, we know our dimensions. Put them in the store (this will force a re-render)
this.setSize();
const botConnection = this.props.directLine
? (this.botConnection = new DirectLine(this.props.directLine))
: this.props.botConnection
;
if (this.props.resize === 'window')
window.addEventListener('resize', this.resizeListener);
this.store.dispatch<ChatActions>({ type: 'Start_Connection', user: this.props.user, bot: this.props.bot, botConnection, selectedActivity: this.props.selectedActivity });
this.connectionStatusSubscription = botConnection.connectionStatus$.subscribe(connectionStatus =>{
if(this.props.speechOptions && this.props.speechOptions.speechRecognizer){
let refGrammarId = botConnection.referenceGrammarId;
if(refGrammarId)
this.props.speechOptions.speechRecognizer.referenceGrammarId = refGrammarId;
}
this.store.dispatch<ChatActions>({ type: 'Connection_Change', connectionStatus })
}
);
this.activitySubscription = botConnection.activity$.subscribe(
activity => this.handleIncomingActivity(activity),
error => konsole.log("activity$ error", error)
);
if (this.props.selectedActivity) {
this.selectedActivitySubscription = this.props.selectedActivity.subscribe(activityOrID => {
this.store.dispatch<ChatActions>({
type: 'Select_Activity',
selectedActivity: activityOrID.activity || this.store.getState().history.activities.find(activity => activity.id === activityOrID.id)
});
});
}
}
componentWillUnmount() {
this.connectionStatusSubscription.unsubscribe();
this.activitySubscription.unsubscribe();
if (this.selectedActivitySubscription)
this.selectedActivitySubscription.unsubscribe();
if (this.botConnection)
this.botConnection.end();
window.removeEventListener('resize', this.resizeListener);
}
// At startup we do three render passes:
// 1. To determine the dimensions of the chat panel (nothing needs to actually render here, so we don't)
// 2. To determine the margins of any given carousel (we just render one mock activity so that we can measure it)
// 3. (this is also the normal re-render case) To render without the mock activity
private setFocus() {
// HUGE HACK - set focus back to input after clicking on an action
// React makes this hard to do well, so we just do an end run around them
(this.chatviewPanel.querySelector(".wc-shellinput") as HTMLInputElement).focus();
}
render() {
const state = this.store.getState();
konsole.log("BotChat.Chat state", state);
// only render real stuff after we know our dimensions
let header: JSX.Element;
/*
if (state.format.options.showHeader) header =
<div className="wc-header">
<span>{ state.format.strings.title }</span>
</div>;
*/
let resize: JSX.Element;
if (this.props.resize === 'detect') resize =
<ResizeDetector onresize={ this.resizeListener } />;
return (
<Provider store={ this.store }>
<div className="wc-chatview-panel" ref={ div => this.chatviewPanel = div }>
{ header }
<MessagePane setFocus={ () => this.setFocus() }>
<History setFocus={ () => this.setFocus() }/>
</MessagePane>
<Shell />
{ resize }
</div>
</Provider>
);
}
}
export interface IDoCardAction {
(type: CardActionTypes, value: string | object): void;
}
export const doCardAction = (
botConnection: IBotConnection,
from: User,
locale: string,
sendMessage: (value: string, user: User, locale: string) => void,
): IDoCardAction => (
type,
actionValue
) => {
const text = (typeof actionValue === 'string') ? actionValue as string : undefined;
const value = (typeof actionValue === 'object')? actionValue as object : undefined;
switch (type) {
case "imBack":
if (typeof text === 'string')
sendMessage(text, from, locale);
break;
case "postBack":
sendPostBack(botConnection, text, value, from, locale);
break;
case "call":
case "openUrl":
case "playAudio":
case "playVideo":
case "showImage":
case "downloadFile":
case "signin":
window.open(text);
break;
default:
konsole.log("unknown button type", type);
}
}
export const sendPostBack = (botConnection: IBotConnection, text: string, value: object, from: User, locale: string) => {
botConnection.postActivity({
type: "message",
text,
value,
from,
locale
})
.subscribe(id => {
konsole.log("success sending postBack", id)
}, error => {
konsole.log("failed to send postBack", error);
});
}
export const renderIfNonempty = (value: any, renderer: (value: any) => JSX.Element ) => {
if (value !== undefined && value !== null && (typeof value !== 'string' || value.length > 0))
return renderer(value);
}
export const classList = (...args:(string | boolean)[]) => {
return args.filter(Boolean).join(' ');
}
// note: container of this element must have CSS position of either absolute or relative
const ResizeDetector = (props: {
onresize: () => void
}) =>
// adapted to React from https://github.com/developit/simple-element-resize-detector
<iframe
style={ { position: 'absolute', left: '0', top: '-100%', width: '100%', height: '100%', margin: '1px 0 0', border: 'none', opacity: 0, visibility: 'hidden', pointerEvents: 'none' } }
ref={ frame => {
if (frame)
frame.contentWindow.onresize = props.onresize;
} }
/>;