-
Notifications
You must be signed in to change notification settings - Fork 1.6k
/
Copy pathComposer.js
369 lines (328 loc) · 13.2 KB
/
Composer.js
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
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
import { Composer as APIComposer, hooks } from 'botframework-webchat-api';
import { Composer as SayComposer } from 'react-say';
import createEmotion from '@emotion/css/create-instance';
import createStyleSet from './Styles/createStyleSet';
import MarkdownIt from 'markdown-it';
import PropTypes from 'prop-types';
import React, { useCallback, useMemo, useRef, useState } from 'react';
import {
speechSynthesis as bypassSpeechSynthesis,
SpeechSynthesisUtterance as BypassSpeechSynthesisUtterance
} from './hooks/internal/BypassSpeechSynthesisPonyfill';
import addTargetBlankToHyperlinksMarkdown from './Utils/addTargetBlankToHyperlinksMarkdown';
import createCSSKey from './Utils/createCSSKey';
import createDefaultActivityMiddleware from './Middleware/Activity/createCoreMiddleware';
import createDefaultActivityStatusMiddleware from './Middleware/ActivityStatus/createCoreMiddleware';
import createDefaultAttachmentForScreenReaderMiddleware from './Middleware/AttachmentForScreenReader/createCoreMiddleware';
import createDefaultAttachmentMiddleware from './Middleware/Attachment/createCoreMiddleware';
import createDefaultAvatarMiddleware from './Middleware/Avatar/createCoreMiddleware';
import createDefaultCardActionMiddleware from './Middleware/CardAction/createCoreMiddleware';
import createDefaultToastMiddleware from './Middleware/Toast/createCoreMiddleware';
import createDefaultTypingIndicatorMiddleware from './Middleware/TypingIndicator/createCoreMiddleware';
import Dictation from './Dictation';
import downscaleImageToDataURL from './Utils/downscaleImageToDataURL';
import ErrorBox from './ErrorBox';
import mapMap from './Utils/mapMap';
import singleToArray from './Utils/singleToArray';
import UITracker from './hooks/internal/UITracker';
import WebChatUIContext from './hooks/internal/WebChatUIContext';
const { useReferenceGrammarID, useStyleOptions } = hooks;
// eslint-disable-next-line no-undef
const node_env = process.env.node_env || process.env.NODE_ENV;
const emotionPool = {};
function styleSetToEmotionObjects(styleToEmotionObject, styleSet) {
return mapMap(styleSet, (style, key) => (key === 'options' ? style : styleToEmotionObject(style)));
}
const ComposerCore = ({
children,
extraStyleSet,
nonce,
renderMarkdown,
styleSet,
suggestedActionsAccessKey,
webSpeechPonyfillFactory
}) => {
const [dictateAbortable, setDictateAbortable] = useState();
const [referenceGrammarID] = useReferenceGrammarID();
const [styleOptions] = useStyleOptions();
const focusSendBoxCallbacksRef = useRef([]);
const focusTranscriptCallbacksRef = useRef([]);
const internalMarkdownIt = useMemo(() => new MarkdownIt(), []);
const scrollToCallbacksRef = useRef([]);
const scrollToEndCallbacksRef = useRef([]);
// Instead of having a `scrollUpCallbacksRef` and `scrollDownCallbacksRef`, they are combined into a single `scrollRelativeCallbacksRef`.
// The first argument tells whether it should go "up" or "down".
const scrollRelativeCallbacksRef = useRef([]);
const dictationOnError = useCallback(err => {
console.error(err);
}, []);
const internalRenderMarkdownInline = useMemo(
() => markdown => {
const tree = internalMarkdownIt.parseInline(markdown);
// We should add rel="noopener noreferrer" and target="_blank"
const patchedTree = addTargetBlankToHyperlinksMarkdown(tree);
return internalMarkdownIt.renderer.render(patchedTree);
},
[internalMarkdownIt]
);
const styleToEmotionObject = useMemo(() => {
// Emotion doesn't hash with nonce. We need to provide the pooling mechanism.
// 1. If 2 instances use different nonce, they should result in different hash;
// 2. If 2 instances are being mounted, pooling will make sure we render only 1 set of <style> tags, instead of 2.
const emotion =
emotionPool[nonce] || (emotionPool[nonce] = createEmotion({ key: `webchat--css-${createCSSKey()}`, nonce }));
return style => emotion.css(style);
}, [nonce]);
const patchedStyleSet = useMemo(
() =>
styleSetToEmotionObjects(styleToEmotionObject, {
...(styleSet || createStyleSet(styleOptions)),
...extraStyleSet
}),
[extraStyleSet, styleOptions, styleSet, styleToEmotionObject]
);
const webSpeechPonyfill = useMemo(() => {
const ponyfill = webSpeechPonyfillFactory && webSpeechPonyfillFactory({ referenceGrammarID });
const { speechSynthesis, SpeechSynthesisUtterance } = ponyfill || {};
return {
...ponyfill,
speechSynthesis: speechSynthesis || bypassSpeechSynthesis,
SpeechSynthesisUtterance: SpeechSynthesisUtterance || BypassSpeechSynthesisUtterance
};
}, [referenceGrammarID, webSpeechPonyfillFactory]);
const scrollPositionObserversRef = useRef([]);
const [numScrollPositionObservers, setNumScrollPositionObservers] = useState(0);
const dispatchScrollPosition = useCallback(
event => scrollPositionObserversRef.current.forEach(observer => observer(event)),
[scrollPositionObserversRef]
);
const observeScrollPosition = useCallback(
observer => {
scrollPositionObserversRef.current = [...scrollPositionObserversRef.current, observer];
setNumScrollPositionObservers(scrollPositionObserversRef.current.length);
return () => {
scrollPositionObserversRef.current = scrollPositionObserversRef.current.filter(target => target !== observer);
setNumScrollPositionObservers(scrollPositionObserversRef.current.length);
};
},
[scrollPositionObserversRef, setNumScrollPositionObservers]
);
const transcriptFocusObserversRef = useRef([]);
const [numTranscriptFocusObservers, setNumTranscriptFocusObservers] = useState(0);
const dispatchTranscriptFocus = useCallback(
event => transcriptFocusObserversRef.current.forEach(observer => observer(event)),
[transcriptFocusObserversRef]
);
const observeTranscriptFocus = useCallback(
observer => {
transcriptFocusObserversRef.current = [...transcriptFocusObserversRef.current, observer];
setNumTranscriptFocusObservers(transcriptFocusObserversRef.current.length);
return () => {
transcriptFocusObserversRef.current = transcriptFocusObserversRef.current.filter(target => target !== observer);
setNumTranscriptFocusObservers(transcriptFocusObserversRef.current.length);
};
},
[transcriptFocusObserversRef, setNumTranscriptFocusObservers]
);
const context = useMemo(
() => ({
dictateAbortable,
dispatchScrollPosition,
dispatchTranscriptFocus,
focusSendBoxCallbacksRef,
focusTranscriptCallbacksRef,
internalMarkdownItState: [internalMarkdownIt],
internalRenderMarkdownInline,
nonce,
numScrollPositionObservers,
numTranscriptFocusObservers,
observeScrollPosition,
observeTranscriptFocus,
renderMarkdown,
scrollRelativeCallbacksRef,
scrollToCallbacksRef,
scrollToEndCallbacksRef,
setDictateAbortable,
styleSet: patchedStyleSet,
styleToEmotionObject,
suggestedActionsAccessKey,
webSpeechPonyfill
}),
[
dictateAbortable,
dispatchScrollPosition,
dispatchTranscriptFocus,
focusSendBoxCallbacksRef,
focusTranscriptCallbacksRef,
internalMarkdownIt,
internalRenderMarkdownInline,
nonce,
numScrollPositionObservers,
numTranscriptFocusObservers,
observeScrollPosition,
observeTranscriptFocus,
patchedStyleSet,
renderMarkdown,
scrollRelativeCallbacksRef,
scrollToCallbacksRef,
scrollToEndCallbacksRef,
setDictateAbortable,
styleToEmotionObject,
suggestedActionsAccessKey,
webSpeechPonyfill
]
);
return (
<SayComposer ponyfill={webSpeechPonyfill}>
<WebChatUIContext.Provider value={context}>
{children}
<Dictation onError={dictationOnError} />
</WebChatUIContext.Provider>
</SayComposer>
);
};
ComposerCore.defaultProps = {
extraStyleSet: undefined,
nonce: undefined,
renderMarkdown: undefined,
styleSet: undefined,
suggestedActionsAccessKey: 'A a Å å',
webSpeechPonyfillFactory: undefined
};
ComposerCore.propTypes = {
extraStyleSet: PropTypes.any,
nonce: PropTypes.string,
renderMarkdown: PropTypes.func,
styleSet: PropTypes.any,
suggestedActionsAccessKey: PropTypes.oneOfType([PropTypes.oneOf([false]), PropTypes.string]),
webSpeechPonyfillFactory: PropTypes.func
};
const Composer = ({
activityMiddleware,
activityStatusMiddleware,
attachmentForScreenReaderMiddleware,
attachmentMiddleware,
avatarMiddleware,
cardActionMiddleware,
children,
extraStyleSet,
renderMarkdown,
styleSet,
suggestedActionsAccessKey,
toastMiddleware,
typingIndicatorMiddleware,
webSpeechPonyfillFactory,
...composerProps
}) => {
const { nonce, onTelemetry } = composerProps;
const patchedActivityMiddleware = useMemo(
() => [...singleToArray(activityMiddleware), ...createDefaultActivityMiddleware()],
[activityMiddleware]
);
const patchedActivityStatusMiddleware = useMemo(
() => [...singleToArray(activityStatusMiddleware), ...createDefaultActivityStatusMiddleware()],
[activityStatusMiddleware]
);
const patchedAttachmentForScreenReaderMiddleware = useMemo(
() => [
...singleToArray(attachmentForScreenReaderMiddleware),
...createDefaultAttachmentForScreenReaderMiddleware()
],
[attachmentForScreenReaderMiddleware]
);
const patchedAttachmentMiddleware = useMemo(
() => [...singleToArray(attachmentMiddleware), ...createDefaultAttachmentMiddleware()],
[attachmentMiddleware]
);
const patchedAvatarMiddleware = useMemo(
() => [...singleToArray(avatarMiddleware), ...createDefaultAvatarMiddleware()],
[avatarMiddleware]
);
const patchedCardActionMiddleware = useMemo(
() => [...singleToArray(cardActionMiddleware), ...createDefaultCardActionMiddleware()],
[cardActionMiddleware]
);
const patchedToastMiddleware = useMemo(() => [...singleToArray(toastMiddleware), ...createDefaultToastMiddleware()], [
toastMiddleware
]);
const patchedTypingIndicatorMiddleware = useMemo(
() => [...singleToArray(typingIndicatorMiddleware), ...createDefaultTypingIndicatorMiddleware()],
[typingIndicatorMiddleware]
);
return (
<React.Fragment>
<APIComposer
activityMiddleware={patchedActivityMiddleware}
activityStatusMiddleware={patchedActivityStatusMiddleware}
attachmentForScreenReaderMiddleware={patchedAttachmentForScreenReaderMiddleware}
attachmentMiddleware={patchedAttachmentMiddleware}
avatarMiddleware={patchedAvatarMiddleware}
cardActionMiddleware={patchedCardActionMiddleware}
downscaleImageToDataURL={downscaleImageToDataURL}
// Under dev server of create-react-app, "NODE_ENV" will be set to "development".
internalErrorBoxClass={node_env === 'development' ? ErrorBox : undefined}
nonce={nonce}
toastMiddleware={patchedToastMiddleware}
typingIndicatorMiddleware={patchedTypingIndicatorMiddleware}
{...composerProps}
>
<ComposerCore
extraStyleSet={extraStyleSet}
nonce={nonce}
renderMarkdown={renderMarkdown}
styleSet={styleSet}
suggestedActionsAccessKey={suggestedActionsAccessKey}
webSpeechPonyfillFactory={webSpeechPonyfillFactory}
>
{children}
{onTelemetry && <UITracker />}
</ComposerCore>
</APIComposer>
</React.Fragment>
);
};
Composer.defaultProps = {
...APIComposer.defaultProps,
...ComposerCore.defaultProps,
activityMiddleware: undefined,
activityRenderer: undefined,
activityStatusMiddleware: undefined,
activityStatusRenderer: undefined,
attachmentForScreenReaderMiddleware: undefined,
attachmentMiddleware: undefined,
attachmentRenderer: undefined,
avatarMiddleware: undefined,
avatarRenderer: undefined,
cardActionMiddleware: undefined,
children: undefined,
nonce: undefined,
renderMarkdown: undefined,
toastMiddleware: undefined,
toastRenderer: undefined,
typingIndicatorMiddleware: undefined,
typingIndicatorRenderer: undefined,
webSpeechPonyfillFactory: undefined
};
Composer.propTypes = {
...APIComposer.propTypes,
...ComposerCore.propTypes,
activityMiddleware: PropTypes.oneOfType([PropTypes.arrayOf(PropTypes.func), PropTypes.func]),
activityRenderer: PropTypes.func,
activityStatusMiddleware: PropTypes.oneOfType([PropTypes.arrayOf(PropTypes.func), PropTypes.func]),
activityStatusRenderer: PropTypes.func,
attachmentForScreenReaderMiddleware: PropTypes.oneOfType([PropTypes.arrayOf(PropTypes.func), PropTypes.func]),
attachmentMiddleware: PropTypes.oneOfType([PropTypes.arrayOf(PropTypes.func), PropTypes.func]),
attachmentRenderer: PropTypes.func,
avatarMiddleware: PropTypes.oneOfType([PropTypes.arrayOf(PropTypes.func), PropTypes.func]),
avatarRenderer: PropTypes.func,
cardActionMiddleware: PropTypes.func,
children: PropTypes.any,
nonce: PropTypes.string,
renderMarkdown: PropTypes.func,
toastMiddleware: PropTypes.oneOfType([PropTypes.arrayOf(PropTypes.func), PropTypes.func]),
toastRenderer: PropTypes.func,
typingIndicatorMiddleware: PropTypes.oneOfType([PropTypes.arrayOf(PropTypes.func), PropTypes.func]),
typingIndicatorRenderer: PropTypes.func,
webSpeechPonyfillFactory: PropTypes.func
};
export default Composer;