-
Notifications
You must be signed in to change notification settings - Fork 626
Expand file tree
/
Copy pathAnswer.tsx
More file actions
408 lines (386 loc) · 12.4 KB
/
Answer.tsx
File metadata and controls
408 lines (386 loc) · 12.4 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
import { useEffect, useMemo, useState, useRef, forwardRef } from "react";
import { useBoolean } from "@fluentui/react-hooks";
import { FontIcon, Stack, Text } from "@fluentui/react";
import styles from "./Answer.module.css";
import { AskResponse, Citation } from "../../api";
import { parseAnswer } from "./AnswerParser";
import ReactMarkdown from "react-markdown";
import remarkGfm from "remark-gfm";
import supersub from "remark-supersub";
import pauseIcon from "../../assets/pauseIcon.svg";
import speakerIcon from "../../assets/speakerIcon.svg";
import * as sdk from "microsoft-cognitiveservices-speech-sdk";
import * as SpeechSDK from "microsoft-cognitiveservices-speech-sdk";
declare global {
interface Window {
webkitAudioContext: typeof AudioContext;
}
}
interface Props {
answer: AskResponse;
onCitationClicked: (citedDocument: Citation) => void;
onSpeak?: any;
isActive?: boolean;
index: number;
}
const MyStackComponent = forwardRef<HTMLDivElement, any>((props, ref) => (
<div {...props} ref={ref} />
));
export const Answer = ({
answer,
onCitationClicked,
onSpeak,
isActive,
index,
}: Props) => {
const [isRefAccordionOpen, { toggle: toggleIsRefAccordionOpen }] =
useBoolean(false);
const filePathTruncationLimit = 50;
const answerContainerRef = useRef<HTMLDivElement>(null); // read the text from the container
const messageBoxId = "message-" + index;
const [isSpeaking, setIsSpeaking] = useState(false); // for speaker on
const [showSpeaker, setShowSpeaker] = useState(true); //for show and hide the speaker icon
const [isPaused, setIsPaused] = useState(false); //for pause
const parsedAnswer = useMemo(() => parseAnswer(answer), [answer]);
const [chevronIsExpanded, setChevronIsExpanded] =
useState(isRefAccordionOpen);
const refContainer = useRef<HTMLDivElement>(null);
const [audioContext, setAudioContext] = useState<AudioContext | null>(null); //Manully manage the audio context eg pausing resuming
const [synthesizerData, setSynthesizerData] = useState({
token: "",
region: "",
});
const [synthesizer, setSynthesizer] =
useState<SpeechSDK.SpeechSynthesizer | null>(null);
const [audioDestination, setAudioDestination] =
useState<SpeechSDK.SpeakerAudioDestination | null>(null);
const [playbackTimeout, setPlaybackTimeout] = useState<NodeJS.Timeout | null>(
null
);
const [remainingDuration, setRemainingDuration] = useState<number>(0);
const [startTime, setStartTime] = useState<number | null>(null);
const handleChevronClick = () => {
setChevronIsExpanded(!chevronIsExpanded);
toggleIsRefAccordionOpen();
};
const initializeSynthesizer = () => {
const speechConfig = sdk.SpeechConfig.fromAuthorizationToken(
synthesizerData.token,
synthesizerData.region
);
const newAudioDestination = new SpeechSDK.SpeakerAudioDestination();
const audioConfig =
SpeechSDK.AudioConfig.fromSpeakerOutput(newAudioDestination);
const newSynthesizer = new SpeechSDK.SpeechSynthesizer(
speechConfig,
audioConfig
);
setSynthesizer(newSynthesizer);
setAudioDestination(newAudioDestination);
if (playbackTimeout) {
clearTimeout(playbackTimeout);
}
setRemainingDuration(0);
};
useEffect(() => {
if (synthesizerData.token != "") {
initializeSynthesizer();
return () => {
if (synthesizer) {
synthesizer.close();
}
if (audioDestination) {
audioDestination.close();
}
if (playbackTimeout) {
clearTimeout(playbackTimeout);
}
};
}
}, [index, synthesizerData]);
useEffect(() => {
const fetchSythesizerData = async () => {
const response = await fetch("/api/speech");
try {
if (!response.ok) {
throw new Error("Network response was not ok");
}
const data = await response.json();
setSynthesizerData({ token: data.token, region: data.region });
} catch (e) {
console.log(e);
}
};
fetchSythesizerData();
}, []);
useEffect(() => {
if (!isActive && synthesizer && isSpeaking) {
resetSpeech();
}
}, [isActive, synthesizer]);
useEffect(() => {
return () => {
if (isSpeaking) {
resetSpeech();
}
};
}, []);
useEffect(() => {
setChevronIsExpanded(isRefAccordionOpen);
// if (chevronIsExpanded && refContainer.current) {
// refContainer.current.scrollIntoView({ behavior: 'smooth' });
// }
// After genrating answer then only show speaker icon
if (parsedAnswer.markdownFormatText === "Generating answer...") {
setShowSpeaker(false);
} else {
setShowSpeaker(true);
}
}, [parsedAnswer]);
const createCitationFilepath = (
citation: Citation,
index: number,
truncate: boolean = false
) => {
let citationFilename = "";
if (citation.filepath && citation.chunk_id != null) {
if (truncate && citation.filepath.length > filePathTruncationLimit) {
const citationLength = citation.filepath.length;
citationFilename = `${citation.filepath.substring(0, 20)}...${citation.filepath.substring(citationLength - 20)} - Part ${citation.chunk_id}`;
} else {
citationFilename = `${citation.filepath} - Part ${citation.chunk_id}`;
}
} else {
citationFilename = `Citation ${index}`;
}
return citationFilename;
};
const getAnswerText = () => {
if (answerContainerRef.current) {
const text = answerContainerRef.current.textContent ?? "";
return text;
}
return "";
};
const startSpeech = () => {
if (synthesizer) {
const text = getAnswerText();
synthesizer?.speakTextAsync(
text,
(result) => {
if (
result.reason === SpeechSDK.ResultReason.SynthesizingAudioCompleted
) {
const duration = result.audioDuration / 10000;
setRemainingDuration(duration);
setStartTime(Date.now());
handleTimeout(duration);
} else if (result.reason === SpeechSDK.ResultReason.Canceled) {
setIsSpeaking(false);
setIsPaused(false);
} else {
console.error("Synthesis failed: ", result.errorDetails);
}
},
(error) => {
console.error("Synthesis error: ", error);
setIsSpeaking(false);
setIsPaused(false);
}
);
setIsSpeaking(true);
}
};
const handleTimeout = (remainingDuration: number) => {
setPlaybackTimeout(
setTimeout(() => {
setIsSpeaking(false);
setIsPaused(false);
onSpeak(index, "stop");
}, remainingDuration)
);
};
const resetSpeech = () => {
//audioDestination?.close();
audioDestination?.pause();
setIsSpeaking(false);
setIsPaused(false);
//synthesizer?.close();
initializeSynthesizer();
};
const handleSpeakPauseResume = () => {
if (isSpeaking) {
if (isPaused) {
onSpeak(index, "speak", resetSpeech);
audioDestination?.resume();
setIsPaused(false);
setStartTime(Date.now());
handleTimeout(remainingDuration);
} else {
onSpeak(index, "pause");
audioDestination?.pause();
setIsPaused(true);
const elapsed = Date.now() - (startTime || 0);
const newRemainingDuration = remainingDuration - elapsed;
setRemainingDuration(newRemainingDuration);
if (playbackTimeout) {
clearTimeout(playbackTimeout);
}
}
} else {
onSpeak(index, "speak", resetSpeech);
startSpeech();
}
};
useEffect(() => {
const handleCopy = () => {
alert("Please consider where you paste this content.");
};
const messageBox = document.getElementById(messageBoxId);
messageBox?.addEventListener("copy", handleCopy);
return () => {
messageBox?.removeEventListener("copy", handleCopy);
};
}, []);
const getSpeechButtons = () => {
const speechStatus = !showSpeaker
? "none"
: showSpeaker && !isSpeaking
? "Speak"
: isSpeaking && isPaused
? "Resume"
: "Pause";
switch (speechStatus) {
case "Speak":
case "Resume":
return (
<button
data-testid="play-button"
id="speakerbtn"
title={"Read aloud"}
onClick={handleSpeakPauseResume}
style={{ border: 0, backgroundColor: "transparent" }}
>
<img src={speakerIcon} alt="Speak" />
</button>
);
case "Pause":
return (
<button
data-testid="pause-button"
id="pausebtn"
title={"Pause"}
onClick={handleSpeakPauseResume}
style={{ border: 0, backgroundColor: "transparent" }}
>
<img src={pauseIcon} alt={isPaused ? "Resume" : "Pause"} />
</button>
);
default:
return null;
}
};
return (
<>
<MyStackComponent
data-testid="message-box"
className={styles.answerContainer}
id={messageBoxId}
ref={answerContainerRef}
>
<Stack.Item grow>
<div className={styles.answerText}>
<ReactMarkdown
remarkPlugins={[remarkGfm, supersub]}
children={parsedAnswer.markdownFormatText}
/>
</div>
</Stack.Item>
<Stack horizontal className={styles.answerFooter} verticalAlign="start">
<Stack.Item className={styles.answerDisclaimerContainer}>
<span
className={`${styles.answerDisclaimer} ${styles.mobileAnswerDisclaimer}`}
>
AI-generated content may be incorrect
</span>
</Stack.Item>
{!!parsedAnswer.citations.length && (
<Stack.Item aria-label="References">
<Stack style={{ width: "100%" }}>
<Stack
horizontal
horizontalAlign="start"
verticalAlign="center"
tabIndex={0}
onClick={handleChevronClick}
role="button"
onKeyDown={(e) =>
e.key === " " || e.key === "Enter"
? handleChevronClick()
: null
}
data-testid="toggle-citations-list"
>
<Text className={styles.accordionTitle}>
<span data-testid="no-of-references">
{parsedAnswer.citations.length > 1
? parsedAnswer.citations.length + " references"
: "1 reference"}
</span>
</Text>
<FontIcon
className={styles.accordionIcon}
iconName={
chevronIsExpanded ? "ChevronDown" : "ChevronRight"
}
aria-hidden={false}
data-testid="chevron-icon"
/>
</Stack>
</Stack>
</Stack.Item>
)}
</Stack>
{chevronIsExpanded && (
<div
data-testid="citations-container"
ref={refContainer}
style={{
marginTop: 8,
display: "flex",
flexDirection: "column",
height: "100%",
gap: "4px",
maxWidth: "100%",
}}
>
{parsedAnswer.citations.map((citation, idx) => {
return (
<span
data-testid="citation-block"
role="button"
onKeyDown={(e) =>
e.key === " " || e.key === "Enter"
? onCitationClicked(citation)
: () => { }
}
tabIndex={0}
title={createCitationFilepath(citation, ++idx)}
key={idx}
onClick={() => onCitationClicked(citation)}
className={styles.citationContainer}
>
<div className={styles.citation} key={idx}>
{idx}
</div>
{createCitationFilepath(citation, idx, true)}
</span>
);
})}
</div>
)}
<Stack.Item>{getSpeechButtons()}</Stack.Item>
</MyStackComponent>
</>
);
};