-
Notifications
You must be signed in to change notification settings - Fork 1.6k
Expand file tree
/
Copy pathComposer.tsx
More file actions
509 lines (451 loc) · 18.2 KB
/
Composer.tsx
File metadata and controls
509 lines (451 loc) · 18.2 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
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
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
import type {
ComposerProps as APIComposerProps,
SendBoxMiddleware,
SendBoxToolbarMiddleware
} from 'botframework-webchat-api';
import {
Composer as APIComposer,
hooks,
initSendBoxMiddleware,
initSendBoxToolbarMiddleware,
WebSpeechPonyfillFactory
} from 'botframework-webchat-api';
import { DecoratorComposer, type DecoratorMiddleware } from 'botframework-webchat-api/decorator';
import { singleToArray } from 'botframework-webchat-core';
import classNames from 'classnames';
import MarkdownIt from 'markdown-it';
import PropTypes from 'prop-types';
import React, { memo, useCallback, useMemo, useRef, useState, type ReactNode } from 'react';
import { Composer as SayComposer } from 'react-say';
import createDefaultAttachmentMiddleware from './Attachment/createMiddleware';
import BuiltInDecorator from './BuiltInDecorator';
import Dictation from './Dictation';
import ErrorBox from './ErrorBox';
import {
speechSynthesis as bypassSpeechSynthesis,
SpeechSynthesisUtterance as BypassSpeechSynthesisUtterance
} from './hooks/internal/BypassSpeechSynthesisPonyfill';
import { StyleToEmotionObjectComposer, useStyleToEmotionObject } from './hooks/internal/styleToEmotionObject';
import UITracker from './hooks/internal/UITracker';
import useInjectStyles from './hooks/internal/useInjectStyles';
import WebChatUIContext from './hooks/internal/WebChatUIContext';
import { FocusSendBoxScope } from './hooks/sendBoxFocus';
import { ScrollRelativeTranscriptScope } from './hooks/transcriptScrollRelative';
import createDefaultActivityMiddleware from './Middleware/Activity/createCoreMiddleware';
import createDefaultActivityStatusMiddleware from './Middleware/ActivityStatus/createCoreMiddleware';
import createDefaultAttachmentForScreenReaderMiddleware from './Middleware/AttachmentForScreenReader/createCoreMiddleware';
import createDefaultAvatarMiddleware from './Middleware/Avatar/createCoreMiddleware';
import createDefaultCardActionMiddleware from './Middleware/CardAction/createCoreMiddleware';
import createDefaultScrollToEndButtonMiddleware from './Middleware/ScrollToEndButton/createScrollToEndButtonMiddleware';
import createDefaultToastMiddleware from './Middleware/Toast/createCoreMiddleware';
import createDefaultTypingIndicatorMiddleware from './Middleware/TypingIndicator/createCoreMiddleware';
import CustomElementsComposer from './providers/CustomElements/CustomElementsComposer';
import HTMLContentTransformComposer from './providers/HTMLContentTransformCOR/HTMLContentTransformComposer';
import { type HTMLContentTransformMiddleware } from './providers/HTMLContentTransformCOR/private/HTMLContentTransformContext';
import SendBoxComposer from './providers/internal/SendBox/SendBoxComposer';
import { LiveRegionTwinComposer } from './providers/LiveRegionTwin';
import ModalDialogComposer from './providers/ModalDialog/ModalDialogComposer';
import ReducedMotionComposer from './providers/ReducedMotion/ReducedMotionComposer';
import useTheme from './providers/Theme/useTheme';
import createDefaultSendBoxMiddleware from './SendBox/createMiddleware';
import createDefaultSendBoxToolbarMiddleware from './SendBoxToolbar/createMiddleware';
import createStyleSet from './Styles/createStyleSet';
import WebChatTheme from './Styles/WebChatTheme';
import useCustomPropertiesClassName from './Styles/useCustomPropertiesClassName';
import { type ContextOf } from './types/ContextOf';
import { type FocusTranscriptInit } from './types/internal/FocusTranscriptInit';
import addTargetBlankToHyperlinksMarkdown from './Utils/addTargetBlankToHyperlinksMarkdown';
import downscaleImageToDataURL from './Utils/downscaleImageToDataURL';
import mapMap from './Utils/mapMap';
const { useGetActivityByKey, useReferenceGrammarID, useStyleOptions, useTrackException } = hooks;
const node_env = process.env.node_env || process.env.NODE_ENV;
function styleSetToEmotionObjects(styleToEmotionObject, styleSet) {
return mapMap(styleSet, (style, key) => (key === 'options' ? style : styleToEmotionObject(style)));
}
type ComposerCoreUIProps = Readonly<{ children?: ReactNode | undefined }>;
const ROOT_STYLE = {
'&.webchat__css-custom-properties': {
'& .webchat__live-region': {
color: 'transparent',
height: 1,
overflow: 'hidden',
position: 'absolute',
top: 0,
whiteSpace: 'nowrap',
width: 1
}
}
};
const ComposerCoreUI = memo(({ children }: ComposerCoreUIProps) => {
const [{ internalLiveRegionFadeAfter }] = useStyleOptions();
const [customPropertiesClassName] = useCustomPropertiesClassName();
const rootClassName = useStyleToEmotionObject()(ROOT_STYLE) + '';
const trackException = useTrackException();
const dictationOnError = useCallback(
(errorEvent: SpeechRecognitionErrorEvent) => {
// Ignore aborted error as it is likely user clicking on the microphone button to abort recognition.
if (errorEvent.error !== 'aborted') {
const nativeError = new Error('Speech recognition failed');
nativeError.cause = errorEvent;
trackException(nativeError, false);
console.error(nativeError);
}
},
[trackException]
);
return (
<div className={classNames('webchat', 'webchat__css-custom-properties', rootClassName, customPropertiesClassName)}>
<CustomElementsComposer>
<FocusSendBoxScope>
<ScrollRelativeTranscriptScope>
<LiveRegionTwinComposer className="webchat__live-region" fadeAfter={internalLiveRegionFadeAfter}>
<ModalDialogComposer>
{/* When <SendBoxComposer> is finalized, it will be using an independent instance that lives inside <BasicSendBox>. */}
<SendBoxComposer>
{children}
<Dictation onError={dictationOnError} />
</SendBoxComposer>
</ModalDialogComposer>
</LiveRegionTwinComposer>
</ScrollRelativeTranscriptScope>
</FocusSendBoxScope>
</CustomElementsComposer>
</div>
);
});
ComposerCoreUI.displayName = 'ComposerCoreUI';
type ComposerCoreProps = Readonly<{
children?: ReactNode;
decoratorMiddleware?: readonly DecoratorMiddleware[] | undefined;
extraStyleSet?: any;
htmlContentTransformMiddleware?: readonly HTMLContentTransformMiddleware[] | undefined;
nonce?: string;
renderMarkdown?: (
markdown: string,
newLineOptions: { markdownRespectCRLF: boolean },
linkOptions: { externalLinkAlt: string }
) => string;
styleSet?: any;
styles?: readonly HTMLStyleElement[];
suggestedActionsAccessKey?: boolean | string;
webSpeechPonyfillFactory?: WebSpeechPonyfillFactory;
}>;
const ComposerCore = ({
children,
extraStyleSet,
nonce,
renderMarkdown,
styles,
styleSet,
suggestedActionsAccessKey,
webSpeechPonyfillFactory
}: ComposerCoreProps) => {
const [dictateAbortable, setDictateAbortable] = useState();
const [referenceGrammarID] = useReferenceGrammarID();
const [styleOptions] = useStyleOptions();
const focusTranscriptCallbacksRef = useRef<((init: FocusTranscriptInit) => Promise<void>)[]>([]);
const internalMarkdownIt = useMemo(() => new MarkdownIt(), []);
const scrollToCallbacksRef = useRef([]);
const scrollToEndCallbacksRef = useRef([]);
const internalRenderMarkdownInline = useMemo(
() => markdown => {
const tree = internalMarkdownIt.parseInline(markdown);
// TODO: Use "betterLink" plugin.
// We should add rel="noopener noreferrer" and target="_blank"
const patchedTree = addTargetBlankToHyperlinksMarkdown(tree);
return internalMarkdownIt.renderer.render(patchedTree);
},
[internalMarkdownIt]
);
const styleToEmotionObject = useStyleToEmotionObject();
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 dispatchScrollPosition = useCallback(
event => scrollPositionObserversRef.current.forEach(observer => observer(event)),
[scrollPositionObserversRef]
);
const observeScrollPosition = useCallback(
observer => {
scrollPositionObserversRef.current = [...scrollPositionObserversRef.current, observer];
return () => {
scrollPositionObserversRef.current = scrollPositionObserversRef.current.filter(target => target !== observer);
};
},
[scrollPositionObserversRef]
);
const transcriptFocusObserversRef = useRef([]);
const [numTranscriptFocusObservers, setNumTranscriptFocusObservers] = useState(0);
const getActivityByKey = useGetActivityByKey();
const dispatchTranscriptFocusByActivityKey = useMemo(() => {
let prevActivityKey: string | symbol | undefined = Symbol();
return activityKey => {
if (activityKey !== prevActivityKey) {
prevActivityKey = activityKey;
const event = { activity: getActivityByKey(activityKey) };
transcriptFocusObserversRef.current.forEach(observer => observer(event));
}
};
}, [getActivityByKey, 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]
);
useInjectStyles(styles, nonce);
const context = useMemo<ContextOf<typeof WebChatUIContext>>(
() => ({
dictateAbortable,
dispatchScrollPosition,
dispatchTranscriptFocusByActivityKey,
focusTranscriptCallbacksRef,
internalMarkdownItState: [internalMarkdownIt],
internalRenderMarkdownInline,
nonce,
numTranscriptFocusObservers,
observeScrollPosition,
observeTranscriptFocus,
renderMarkdown,
scrollToCallbacksRef,
scrollToEndCallbacksRef,
setDictateAbortable,
styleSet: patchedStyleSet,
suggestedActionsAccessKey,
webSpeechPonyfill
}),
[
dictateAbortable,
dispatchScrollPosition,
dispatchTranscriptFocusByActivityKey,
focusTranscriptCallbacksRef,
internalMarkdownIt,
internalRenderMarkdownInline,
nonce,
numTranscriptFocusObservers,
observeScrollPosition,
observeTranscriptFocus,
patchedStyleSet,
renderMarkdown,
scrollToCallbacksRef,
scrollToEndCallbacksRef,
setDictateAbortable,
suggestedActionsAccessKey,
webSpeechPonyfill
]
);
return (
<SayComposer ponyfill={webSpeechPonyfill}>
<WebChatUIContext.Provider value={context}>
<ComposerCoreUI>{children}</ComposerCoreUI>
</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
};
type ComposerProps = APIComposerProps & ComposerCoreProps;
const InternalComposer = ({
activityMiddleware,
activityStatusMiddleware,
attachmentForScreenReaderMiddleware,
attachmentMiddleware,
avatarMiddleware,
cardActionMiddleware,
children,
decoratorMiddleware,
extraStyleSet,
htmlContentTransformMiddleware,
renderMarkdown,
scrollToEndButtonMiddleware,
sendBoxMiddleware: sendBoxMiddlewareFromProps,
sendBoxToolbarMiddleware: sendBoxToolbarMiddlewareFromProps,
styleOptions,
styleSet,
suggestedActionsAccessKey,
toastMiddleware,
typingIndicatorMiddleware,
webSpeechPonyfillFactory,
...composerProps
}: ComposerProps) => {
const { nonce, onTelemetry } = composerProps;
const theme = useTheme();
const patchedActivityMiddleware = useMemo(
() => [...singleToArray(activityMiddleware), ...theme.activityMiddleware, ...createDefaultActivityMiddleware()],
[activityMiddleware, theme.activityMiddleware]
);
const patchedActivityStatusMiddleware = useMemo(
() => [
...singleToArray(activityStatusMiddleware),
...theme.activityStatusMiddleware,
...createDefaultActivityStatusMiddleware()
],
[activityStatusMiddleware, theme.activityStatusMiddleware]
);
const patchedAttachmentForScreenReaderMiddleware = useMemo(
() => [
...singleToArray(attachmentForScreenReaderMiddleware),
...theme.attachmentForScreenReaderMiddleware,
...createDefaultAttachmentForScreenReaderMiddleware()
],
[attachmentForScreenReaderMiddleware, theme.attachmentForScreenReaderMiddleware]
);
const patchedAttachmentMiddleware = useMemo(
() => [
...singleToArray(attachmentMiddleware),
...theme.attachmentMiddleware,
...createDefaultAttachmentMiddleware()
],
[attachmentMiddleware, theme.attachmentMiddleware]
);
const patchedAvatarMiddleware = useMemo(
() => [...singleToArray(avatarMiddleware), ...theme.avatarMiddleware, ...createDefaultAvatarMiddleware()],
[avatarMiddleware, theme.avatarMiddleware]
);
const patchedCardActionMiddleware = useMemo(
() => [
...singleToArray(cardActionMiddleware),
...theme.cardActionMiddleware,
...createDefaultCardActionMiddleware()
],
[cardActionMiddleware, theme.cardActionMiddleware]
);
const patchedToastMiddleware = useMemo(
() => [...singleToArray(toastMiddleware), ...theme.toastMiddleware, ...createDefaultToastMiddleware()],
[toastMiddleware, theme.toastMiddleware]
);
const patchedTypingIndicatorMiddleware = useMemo(
() => [
...singleToArray(typingIndicatorMiddleware),
...theme.typingIndicatorMiddleware,
...createDefaultTypingIndicatorMiddleware()
],
[typingIndicatorMiddleware, theme.typingIndicatorMiddleware]
);
const defaultScrollToEndButtonMiddleware = useMemo(() => createDefaultScrollToEndButtonMiddleware(), []);
const patchedScrollToEndButtonMiddleware = useMemo(
() => [
...singleToArray(scrollToEndButtonMiddleware),
...theme.scrollToEndButtonMiddleware,
...defaultScrollToEndButtonMiddleware
],
[defaultScrollToEndButtonMiddleware, scrollToEndButtonMiddleware, theme.scrollToEndButtonMiddleware]
);
const patchedStyleOptions = useMemo(
() => ({ ...theme.styleOptions, ...styleOptions }),
[styleOptions, theme.styleOptions]
);
const sendBoxMiddleware = useMemo<readonly SendBoxMiddleware[]>(
() =>
Object.freeze([
...initSendBoxMiddleware(sendBoxMiddlewareFromProps, undefined),
...initSendBoxMiddleware(theme.sendBoxMiddleware, undefined),
...createDefaultSendBoxMiddleware()
]),
[sendBoxMiddlewareFromProps, theme.sendBoxMiddleware]
);
const sendBoxToolbarMiddleware = useMemo<readonly SendBoxToolbarMiddleware[]>(
() =>
Object.freeze([
...initSendBoxToolbarMiddleware(sendBoxToolbarMiddlewareFromProps, undefined),
...initSendBoxToolbarMiddleware(theme.sendBoxToolbarMiddleware, undefined),
...createDefaultSendBoxToolbarMiddleware()
]),
[sendBoxToolbarMiddlewareFromProps, theme.sendBoxToolbarMiddleware]
);
return (
<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".
{...(node_env === 'development' ? { internalErrorBoxClass: ErrorBox } : {})}
nonce={nonce}
scrollToEndButtonMiddleware={patchedScrollToEndButtonMiddleware}
sendBoxMiddleware={sendBoxMiddleware}
sendBoxToolbarMiddleware={sendBoxToolbarMiddleware}
styleOptions={patchedStyleOptions}
toastMiddleware={patchedToastMiddleware}
typingIndicatorMiddleware={patchedTypingIndicatorMiddleware}
{...composerProps}
>
<StyleToEmotionObjectComposer nonce={nonce}>
<HTMLContentTransformComposer middleware={htmlContentTransformMiddleware}>
<ReducedMotionComposer>
<BuiltInDecorator>
<DecoratorComposer middleware={decoratorMiddleware}>
<ComposerCore
extraStyleSet={extraStyleSet}
nonce={nonce}
renderMarkdown={renderMarkdown}
styleSet={styleSet}
styles={theme.styles}
suggestedActionsAccessKey={suggestedActionsAccessKey}
webSpeechPonyfillFactory={webSpeechPonyfillFactory}
>
{children}
{onTelemetry && <UITracker />}
</ComposerCore>
</DecoratorComposer>
</BuiltInDecorator>
</ReducedMotionComposer>
</HTMLContentTransformComposer>
</StyleToEmotionObjectComposer>
</APIComposer>
);
};
const Composer = (props: ComposerProps) => (
<WebChatTheme>
<InternalComposer {...props} />
</WebChatTheme>
);
Composer.defaultProps = {
...APIComposer.defaultProps,
...ComposerCore.defaultProps,
children: undefined
};
Composer.propTypes = {
...APIComposer.propTypes,
...ComposerCore.propTypes,
children: PropTypes.any
};
export default Composer;
export type { ComposerProps };