-
Notifications
You must be signed in to change notification settings - Fork 1
/
Composer.js
285 lines (242 loc) · 8.42 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
/* eslint no-magic-numbers: ["error", { "ignore": [0, 1, 2, 3] }] */
import PropTypes from 'prop-types';
import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import Context from './Context';
import usePrevious from './usePrevious';
import useRefFrom from './useRefFrom';
import vendorPrefix from './vendorPrefix';
function applyAll(...fns) {
return function () {
// eslint-disable-next-line no-invalid-this, prefer-rest-params
fns.forEach(fn => fn.apply(this, arguments));
};
}
function recognitionAbortable(recognition) {
return !!(recognition && typeof recognition.abort === 'function');
}
const Composer = ({
children,
extra,
grammar,
lang,
onDictate,
onError,
onProgress,
onRawEvent,
speechGrammarList,
speechRecognition,
started
}) => {
const [readyState, setReadyState] = useState(0);
const emitDictateOnEndRef = useRef(false);
const extraRef = useRefFrom(extra);
const grammarRef = useRefFrom(grammar);
const langRef = useRefFrom(lang);
const notAllowedRef = useRef(false);
const onDictateRef = useRefFrom(onDictate);
const onErrorRef = useRefFrom(onError);
const onProgressRef = useRefFrom(onProgress);
const onRawEventRef = useRefFrom(onRawEvent);
const prevSpeechRecognition = usePrevious(speechRecognition);
const recognitionRef = useRef();
const speechGrammarListRef = useRefFrom(speechGrammarList);
const speechRecognitionRef = useRefFrom(speechRecognition);
// If "speechRecognition" ponyfill changed, reset the "notAllowed" flag.
if (prevSpeechRecognition !== speechRecognition) {
notAllowedRef.current = false;
}
const handleAudioEnd = useCallback(
({ target }) => target === recognitionRef.current && setReadyState(3),
[recognitionRef, setReadyState]
);
const handleAudioStart = useCallback(
({ target }) => {
if (target !== recognitionRef.current) {
return;
}
setReadyState(2);
// Web Speech API does not emit "result" when nothing is heard, and Chrome does not emit "nomatch" event.
// Because we emitted onProgress, we should emit "dictate" if not error, so they works in pair.
emitDictateOnEndRef.current = true;
onProgressRef.current && onProgressRef.current({ abortable: recognitionAbortable(target), type: 'progress' });
},
[emitDictateOnEndRef, onProgressRef, recognitionRef, setReadyState]
);
const handleEnd = useCallback(
({ target }) => {
if (target !== recognitionRef.current) {
return;
}
recognitionRef.current = undefined;
setReadyState(0);
if (emitDictateOnEndRef.current) {
onDictateRef.current && onDictateRef.current({ type: 'dictate' });
emitDictateOnEndRef.current = false;
}
},
[emitDictateOnEndRef, onDictateRef, recognitionRef, setReadyState]
);
const handleError = useCallback(
event => {
if (event.target !== recognitionRef.current) {
return;
}
// Error out, no need to emit "dictate"
emitDictateOnEndRef.current = false;
recognitionRef.current = undefined;
if (event.error === 'not-allowed') {
notAllowedRef.current = true;
}
setReadyState(0);
onErrorRef.current && onErrorRef.current(event);
},
[emitDictateOnEndRef, onErrorRef, notAllowedRef, recognitionRef, setReadyState]
);
const handleRawEvent = useCallback(
event => {
if (event.target !== recognitionRef.current) {
return;
}
onRawEventRef.current && onRawEventRef.current(event);
},
[onRawEventRef, recognitionRef]
);
const handleResult = useCallback(
({ results: rawResults, target }) => {
if (target !== recognitionRef.current) {
return;
}
if (rawResults.length) {
const results = [].map.call(rawResults, alts => {
// Destructuring breaks Angular due to a bug in Zone.js.
// eslint-disable-next-line prefer-destructuring
const firstAlt = alts[0];
return {
confidence: firstAlt.confidence,
transcript: firstAlt.transcript
};
});
// Destructuring breaks Angular due to a bug in Zone.js.
// eslint-disable-next-line prefer-destructuring
const first = rawResults[0];
if (first.isFinal) {
// After "onDictate" callback, the caller should be able to set "started" to false on an unabortable recognition.
// TODO: Add test for fortification.
recognitionRef.current = undefined;
setReadyState(0);
onDictateRef.current && onDictateRef.current({ result: results[0], type: 'dictate' });
} else {
onProgressRef.current &&
onProgressRef.current({ abortable: recognitionAbortable(target), results, type: 'progress' });
}
}
},
[onDictateRef, onProgressRef, recognitionRef, setReadyState]
);
const handleStart = useCallback(
({ target }) => target === recognitionRef.current && setReadyState(1),
[recognitionRef, setReadyState]
);
useEffect(() => {
if (started) {
if (!speechRecognitionRef.current || notAllowedRef.current) {
throw new Error('Speech recognition is not supported');
}
const grammars = speechGrammarListRef.current && grammarRef.current && new speechGrammarListRef.current();
const recognition = (recognitionRef.current = new speechRecognitionRef.current());
if (grammars) {
grammars.addFromString(grammarRef.current, 1);
recognition.grammars = grammars;
}
recognition.lang = langRef.current;
recognition.interimResults = true;
recognition.onaudioend = applyAll(handleAudioEnd, handleRawEvent);
recognition.onaudiostart = applyAll(handleAudioStart, handleRawEvent);
recognition.onend = applyAll(handleEnd, handleRawEvent);
recognition.onerror = applyAll(handleError, handleRawEvent);
recognition.onnomatch = handleRawEvent;
recognition.onresult = applyAll(handleResult, handleRawEvent);
recognition.onsoundend = handleRawEvent;
recognition.onsoundstart = handleRawEvent;
recognition.onspeechend = handleRawEvent;
recognition.onspeechstart = handleRawEvent;
recognition.onstart = applyAll(handleStart, handleRawEvent);
const { current: extra } = extraRef;
extra &&
Object.entries(extra).forEach(([key, value]) => {
if (key !== 'constructor' && key !== 'prototype' && key !== '__proto__') {
recognition[key] = value;
}
});
recognition.start();
}
return () => {
const { current: recognition } = recognitionRef;
if (recognition) {
if (recognitionAbortable(recognition)) {
recognition.abort();
} else {
throw new Error('Failed to stop recognition while the current one is ongoing and is not abortable.');
}
}
};
}, [
extraRef,
grammarRef,
handleAudioEnd,
handleAudioStart,
handleEnd,
handleError,
handleRawEvent,
handleResult,
handleStart,
langRef,
notAllowedRef,
recognitionRef,
speechGrammarListRef,
speechRecognitionRef,
started
]);
const abortable = recognitionAbortable(recognitionRef.current) && readyState === 2;
const supported = !!speechRecognition && !notAllowedRef.current;
const context = useMemo(
() => ({
abortable,
readyState,
supported
}),
[abortable, readyState, supported]
);
return (
<Context.Provider value={context}>
<Context.Consumer>{context => (typeof children === 'function' ? children(context) : children)}</Context.Consumer>
</Context.Provider>
);
};
Composer.defaultProps = {
children: undefined,
extra: undefined,
grammar: undefined,
lang: undefined,
onDictate: undefined,
onError: undefined,
onProgress: undefined,
onRawEvent: undefined,
speechGrammarList: navigator.mediaDevices && navigator.mediaDevices.getUserMedia && vendorPrefix('SpeechGrammarList'),
speechRecognition: navigator.mediaDevices && navigator.mediaDevices.getUserMedia && vendorPrefix('SpeechRecognition'),
started: undefined
};
Composer.propTypes = {
children: PropTypes.any,
extra: PropTypes.any,
grammar: PropTypes.string,
lang: PropTypes.string,
onDictate: PropTypes.func,
onError: PropTypes.func,
onProgress: PropTypes.func,
onRawEvent: PropTypes.func,
speechGrammarList: PropTypes.any,
speechRecognition: PropTypes.any,
started: PropTypes.any
};
export default Composer;