@nualang/nualang-ui-components 0.1.1419 → 0.1.1421

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -9,7 +9,7 @@ const ENDPOINT = import.meta.env.REACT_APP_GCLOUD_SPEECH || "wss://speech-rec-se
9
9
  const socket = io(ENDPOINT, {
10
10
  withCredentials: true,
11
11
  autoConnect: false,
12
- transports: ["websocket"] // use WebSocket only
12
+ transports: ["websocket", "polling"] // use WebSocket, fallback to polling if necessary
13
13
  });
14
14
  socket.on("connect_error", error => {
15
15
  // revert to classic upgrade
@@ -54,6 +54,24 @@ export default function useRecognition(props = {}) {
54
54
  const stopAudioRecordingTimeoutIdRef = useRef();
55
55
  const streamRef = useRef();
56
56
  const serverErrorRef = useRef();
57
+ const hasAlertedConnectionErrorRef = useRef(false);
58
+ // Guards against a second click landing during the async start-up window,
59
+ // before recognizing/isRecognizingDisabled state has re-rendered the button.
60
+ const isStartingRef = useRef(false);
61
+
62
+ // Lets us query, e.g., how often students end up on the polling fallback
63
+ // (a proxy for "couldn't connect via websocket") or hit connect errors.
64
+ function trackConnectionDiagnostics(eventName, extra = {}) {
65
+ if (typeof trackRecommendedEvent !== "function") {
66
+ return;
67
+ }
68
+ trackRecommendedEvent(eventName, {
69
+ A1_browser: `${getBrowserInfo(navigator.userAgent)}`,
70
+ A2_machine_info: `${getMachineInfo(navigator.userAgent)}`,
71
+ A3_exercise: gameId ? `${exerciseName}-${gameId}` : `${exerciseName}`,
72
+ ...extra
73
+ });
74
+ }
57
75
  async function loadModule() {
58
76
  try {
59
77
  await audioContextRef.current.audioWorklet.addModule(`/worklets/recording-processor-v2.js`);
@@ -72,7 +90,9 @@ export default function useRecognition(props = {}) {
72
90
  });
73
91
  await loadModule();
74
92
  }
75
- audioContextRef.current.resume();
93
+ // Must be awaited - an unawaited rejection here would leave the
94
+ // context suspended with no error surfaced, silently killing capture.
95
+ await audioContextRef.current.resume();
76
96
  } catch (e) {
77
97
  console.error(`Sorry, there was an issue setting up the audio context`, e);
78
98
  throw e;
@@ -80,13 +100,71 @@ export default function useRecognition(props = {}) {
80
100
  }
81
101
  useEffect(() => {
82
102
  function onConnect() {
103
+ hasAlertedConnectionErrorRef.current = false;
83
104
  setIsSocketConnected(true);
105
+ // socket.io.engine.transport.name is "polling" here only when the
106
+ // websocket attempt failed and it fell back - the clearest signal we
107
+ // have that a student couldn't connect via websocket.
108
+ trackConnectionDiagnostics("speech_recognition_socket_connected", {
109
+ A4_transport: socket.io.engine.transport.name
110
+ });
84
111
  }
85
112
  function onDisconnect() {
86
113
  setIsSocketConnected(false);
114
+ // The server-side recognize stream/session is gone with the connection
115
+ // (no state recovery), so leaving recognizing:true would keep streaming
116
+ // audio into a void with no feedback until the 10s no-transcript timer.
117
+ setRecognitionState(prevState => {
118
+ if (stopAudioRecordingTimeoutIdRef.current) {
119
+ clearTimeout(stopAudioRecordingTimeoutIdRef.current);
120
+ stopAudioRecordingTimeoutIdRef.current = null;
121
+ }
122
+ // A start() in flight (isStartingRef/isRecognizingDisabled set, but
123
+ // recognizing not yet true) needs the same unwind as an active
124
+ // recording - otherwise it's neither idle nor recovered, and the
125
+ // getUserMedia continuation below would still flip recognizing:true
126
+ // once it resolves against a dead socket.
127
+ const isStarting = isStartingRef.current || prevState.isRecognizingDisabled;
128
+ if (!prevState.recognizing && !isStarting) {
129
+ // Truly idle - nothing to unwind, but the mic button is about to go
130
+ // disabled - without this the student just finds a dead button
131
+ // later with no explanation. Guarded so it only fires once per
132
+ // disconnected streak.
133
+ if (!hasAlertedConnectionErrorRef.current) {
134
+ hasAlertedConnectionErrorRef.current = true;
135
+ recognitionAlert("Connection to the speech recognition service was lost. The microphone will be unavailable until it reconnects.");
136
+ }
137
+ return prevState;
138
+ }
139
+ isStartingRef.current = false;
140
+ closeAll(true);
141
+ if (!hasAlertedConnectionErrorRef.current) {
142
+ hasAlertedConnectionErrorRef.current = true;
143
+ recognitionAlert(prevState.recognizing ? "Connection to the speech recognition service was lost while recording. Please try again." : "Connection to the speech recognition service was lost while starting the microphone. Please try again.");
144
+ }
145
+ return {
146
+ ...prevState,
147
+ recognizing: false,
148
+ isRecognizingDisabled: false
149
+ };
150
+ });
151
+ }
152
+ function onConnectError(error) {
153
+ console.error(error);
154
+ trackConnectionDiagnostics("speech_recognition_connect_error", {
155
+ A4_error_message: `${error?.message}`
156
+ });
157
+ // Without this, a blocked/failed connection (e.g. a school network
158
+ // firewall blocking the websocket) leaves the mic button silently
159
+ // disabled with no feedback to the student.
160
+ if (!hasAlertedConnectionErrorRef.current) {
161
+ hasAlertedConnectionErrorRef.current = true;
162
+ recognitionAlert("Could not connect to the speech recognition service. Please check your network connection (some school Wi-Fi/firewalls block this) and refresh the page.");
163
+ }
87
164
  }
88
165
  socket.on("connect", onConnect);
89
166
  socket.on("disconnect", onDisconnect);
167
+ socket.on("connect_error", onConnectError);
90
168
 
91
169
  // no-op if the socket is already connected
92
170
  socket.connect();
@@ -94,14 +172,19 @@ export default function useRecognition(props = {}) {
94
172
  socket.disconnect();
95
173
  socket.off("connect", onConnect);
96
174
  socket.off("disconnect", onDisconnect);
97
- closeAll();
175
+ socket.off("connect_error", onConnectError);
176
+ closeAll(false, true);
98
177
  };
99
178
  }, []);
100
179
 
101
180
  /**
102
181
  * Stops recording and closes everything down. Runs on error or on stop.
182
+ * By default the AudioContext is only suspended, not closed, so the next
183
+ * start() can reuse it instead of re-fetching/re-registering the audio
184
+ * worklet module (a source of noticeable start-up lag). Pass fullClose
185
+ * when the hook itself is unmounting and the context should be released.
103
186
  */
104
- function closeAll(keepSocketAlive) {
187
+ function closeAll(keepSocketAlive, fullClose = false) {
105
188
  // Clear the listeners (prevents issue if opening and closing repeatedly)
106
189
  if (keepSocketAlive) {
107
190
  socket.off("speechData");
@@ -114,6 +197,7 @@ export default function useRecognition(props = {}) {
114
197
  track.stop();
115
198
  });
116
199
  }
200
+ streamRef.current = null;
117
201
  if (processorRef.current) {
118
202
  if (audioInputRef.current) {
119
203
  try {
@@ -122,19 +206,30 @@ export default function useRecognition(props = {}) {
122
206
  logger.warn(`Attempt to disconnect input failed: ${error}`);
123
207
  }
124
208
  }
125
- processorRef.current.disconnect(audioContextRef.current.destination);
209
+ try {
210
+ processorRef.current.disconnect(audioContextRef.current?.destination);
211
+ } catch (error) {
212
+ logger.warn(`Attempt to disconnect processor failed: ${error}`);
213
+ }
214
+ }
215
+ audioInputRef.current = null;
216
+ processorRef.current = null;
217
+ if (!audioContextRef.current) {
218
+ return;
126
219
  }
127
- if (audioContextRef.current) {
220
+ if (fullClose) {
128
221
  audioContextRef.current.close().then(function () {
129
- audioInputRef.current = null;
130
- processorRef.current = null;
131
222
  audioContextRef.current = null;
132
223
  });
224
+ } else {
225
+ audioContextRef.current.suspend().catch(error => {
226
+ logger.warn(`Failed to suspend audio context: ${error}`);
227
+ });
133
228
  }
134
229
  }
135
- function recognitionAlert(message) {
230
+ function recognitionAlert(message, severity = "error") {
136
231
  if (openSnackbar) {
137
- openSnackbar(message, "error");
232
+ openSnackbar(message, severity);
138
233
  } else {
139
234
  alert(message);
140
235
  }
@@ -148,7 +243,15 @@ export default function useRecognition(props = {}) {
148
243
  const initRecording = async (gcloudParams, onData, onError) => {
149
244
  try {
150
245
  await setupAudioContext();
151
- const handleSuccess = function (stream) {
246
+ const handleSuccess = async function (stream) {
247
+ streamRef.current = stream;
248
+ if (!socket.connected) {
249
+ // Dropped while getUserMedia was resolving - don't buffer a stale
250
+ // startGoogleCloudStream for a session the server already tore
251
+ // down. onDisconnect owns the alert/state reset.
252
+ closeAll(true);
253
+ return;
254
+ }
152
255
  const gcloudConfig = {
153
256
  config: {
154
257
  encoding: "LINEAR16",
@@ -167,12 +270,28 @@ export default function useRecognition(props = {}) {
167
270
  };
168
271
  socket.emit("startGoogleCloudStream", gcloudConfig, version); // init socket Google Speech Connection
169
272
 
170
- streamRef.current = stream;
171
273
  audioInputRef.current = audioContextRef.current.createMediaStreamSource(stream);
172
274
  serverErrorRef.current = null;
173
275
  processorRef.current = new AudioWorkletNode(audioContextRef.current, "recording-processor-v2");
174
276
  processorRef.current.connect(audioContextRef.current.destination);
175
- audioContextRef.current.resume();
277
+ try {
278
+ // Awaited so a rejection reaches the getUserMedia .catch() below
279
+ // instead of vanishing as an unhandled rejection.
280
+ await audioContextRef.current.resume();
281
+ } catch (resumeError) {
282
+ // stream/audioInput/processor are already live at this point -
283
+ // without this the mic track and worklet node would leak past the
284
+ // failure that the outer .catch() alerts and resets state for.
285
+ closeAll(true);
286
+ throw resumeError;
287
+ }
288
+ if (!socket.connected) {
289
+ // Dropped mid-resume; onDisconnect has already (or is about to)
290
+ // close these same resources, so stop instead of wiring nodes onto
291
+ // a torn-down session.
292
+ closeAll(true);
293
+ return;
294
+ }
176
295
  audioInputRef.current.connect(processorRef.current);
177
296
  processorRef.current.port.onmessage = event => {
178
297
  const audioData = event.data;
@@ -188,50 +307,86 @@ export default function useRecognition(props = {}) {
188
307
  socket.emit("binaryData", result, version);
189
308
  };
190
309
  if (window.MediaRecorder) {
191
- mediaRecorderRef.current = new MediaRecorder(stream);
192
- mediaRecorderRef.current.ondataavailable = e => {
193
- const audioChunks = [];
194
- audioChunks.push(e.data);
195
- const audioBlob = new Blob(audioChunks, {
196
- type: mediaRecorderRef.current.mimeType
197
- });
198
- const audioUrl = URL.createObjectURL(audioBlob);
199
- setRecognitionState(prevState => ({
200
- ...prevState,
201
- attemptAudioURL: audioUrl,
202
- audioBlob: audioBlob
203
- }));
204
- };
205
- mediaRecorderRef.current.start();
310
+ // This only powers the "listen back to your attempt" playback
311
+ // feature, not recognition itself. A codec/construction failure
312
+ // here (seen in some embedded/older WebKit webviews) must not
313
+ // abort the recording flow that already started above.
314
+ try {
315
+ mediaRecorderRef.current = new MediaRecorder(stream);
316
+ mediaRecorderRef.current.ondataavailable = e => {
317
+ const audioChunks = [];
318
+ audioChunks.push(e.data);
319
+ const audioBlob = new Blob(audioChunks, {
320
+ type: mediaRecorderRef.current.mimeType
321
+ });
322
+ const audioUrl = URL.createObjectURL(audioBlob);
323
+ setRecognitionState(prevState => ({
324
+ ...prevState,
325
+ attemptAudioURL: audioUrl,
326
+ audioBlob: audioBlob
327
+ }));
328
+ };
329
+ mediaRecorderRef.current.start();
330
+ } catch (mediaRecorderError) {
331
+ console.error("Failed to start MediaRecorder for attempt playback", mediaRecorderError);
332
+ mediaRecorderRef.current = null;
333
+ }
206
334
  }
207
- if (/Android|webOS|Safari|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)) {
335
+ if (
336
+ // Excludes bare "Safari", which also matches every desktop
337
+ // Chrome/Edge/Firefox UA string and was adding this delay for
338
+ // almost all browsers, not just mobile ones.
339
+ /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)) {
208
340
  // wait half second to indicate recording, this helps prevent speech being lost at the start
209
341
  return new Promise(resolve => setTimeout(resolve, 500));
210
342
  }
211
343
  };
212
344
  if (navigator && navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
213
345
  navigator.mediaDevices.getUserMedia(constraints).then(handleSuccess).then(() => {
346
+ isStartingRef.current = false;
347
+ // socket.connected is checked directly (not the isSocketConnected
348
+ // state, which may not have re-rendered yet) so a disconnect that
349
+ // landed mid-setup can't be raced into recognizing:true - onDisconnect
350
+ // already unwound this startup, so just release what handleSuccess
351
+ // just created.
352
+ if (!socket.connected) {
353
+ closeAll(true);
354
+ return;
355
+ }
214
356
  if (!serverErrorRef.current) {
215
357
  setRecognitionState(prevState => ({
216
358
  ...prevState,
217
- recognizing: true
359
+ recognizing: true,
360
+ isRecognizingDisabled: false
218
361
  }));
219
362
  }
220
363
  }).catch(err => {
221
364
  /* handle the error */
222
365
  console.error(err);
223
- if (["Permission denied", "The request is not allowed by the user agent or the platform in the current context, possibly because the user denied permission.", "The request is not allowed by the user agent or the platform in the current context."].includes(err?.message)) {
224
- recognitionAlert("Permission denied, Please allow microphone access and refresh the page.");
366
+ // Match on err.name (the DOMException standard) rather than the
367
+ // message text, which varies by browser/locale and previously
368
+ // meant most getUserMedia failures (e.g. a Permissions-Policy
369
+ // block when embedded in an iframe/webview such as an LMS app)
370
+ // were logged but never surfaced to the student.
371
+ const isEmbedded = typeof window !== "undefined" && window.self !== window.top;
372
+ if (["NotAllowedError", "PermissionDeniedError", "SecurityError"].includes(err?.name)) {
373
+ recognitionAlert(isEmbedded ? "Microphone access was blocked. If you're inside another app, make sure it allows microphone access." : "Permission denied, Please allow microphone access and refresh the page.");
374
+ } else {
375
+ recognitionAlert("Could not access the microphone. Please refresh the page and try again.");
225
376
  }
377
+ isStartingRef.current = false;
226
378
  setRecognitionState(prevState => ({
227
379
  ...prevState,
228
- recognizing: false
380
+ recognizing: false,
381
+ isRecognizingDisabled: false
229
382
  }));
230
383
  });
231
384
  } else {
385
+ isStartingRef.current = false;
232
386
  setRecognitionState(prevState => ({
233
387
  ...prevState,
234
- recognizing: false
388
+ recognizing: false,
389
+ isRecognizingDisabled: false
235
390
  }));
236
391
  recognitionAlert("Speech recognition not supported, please try another browser.");
237
392
  }
@@ -250,6 +405,12 @@ export default function useRecognition(props = {}) {
250
405
  }
251
406
  });
252
407
  } catch (error) {
408
+ isStartingRef.current = false;
409
+ setRecognitionState(prevState => ({
410
+ ...prevState,
411
+ recognizing: false,
412
+ isRecognizingDisabled: false
413
+ }));
253
414
  if (onError) {
254
415
  onError(error);
255
416
  }
@@ -280,7 +441,7 @@ export default function useRecognition(props = {}) {
280
441
  };
281
442
  trackRecommendedEvent("speech_recognition_no_transcript", eventBody);
282
443
  };
283
- const stopRecording = (keepSocketAlive, triggerEvent) => {
444
+ const stopRecording = (keepSocketAlive, triggerEvent, fullClose = false) => {
284
445
  // indicate end stream to trigger interim transcript to return as final transcript
285
446
  if (socket) {
286
447
  indicateEndStream();
@@ -289,7 +450,7 @@ export default function useRecognition(props = {}) {
289
450
  mediaRecorderRef.current.stop();
290
451
  }
291
452
  setTimeout(() => {
292
- closeAll(keepSocketAlive);
453
+ closeAll(keepSocketAlive, fullClose);
293
454
  setRecognitionState(prevState => ({
294
455
  ...prevState,
295
456
  isRecognizingDisabled: false
@@ -305,7 +466,7 @@ export default function useRecognition(props = {}) {
305
466
  };
306
467
  useEffect(() => {
307
468
  return () => {
308
- stopRecording(false);
469
+ stopRecording(false, false, true);
309
470
  };
310
471
  }, []);
311
472
  const startRecognition = (lang, speechContexts, model) => {
@@ -408,6 +569,16 @@ export default function useRecognition(props = {}) {
408
569
  stop();
409
570
  };
410
571
  const start = (lang, speechContexts, model) => {
572
+ // Ignore a repeat click while a start is already in flight or once
573
+ // recognizing - a ref check because it must be synchronous, unlike state.
574
+ if (isStartingRef.current || recognitionState.recognizing) {
575
+ return;
576
+ }
577
+ isStartingRef.current = true;
578
+ setRecognitionState(prevState => ({
579
+ ...prevState,
580
+ isRecognizingDisabled: true
581
+ }));
411
582
  stopAudioRecordingTimeoutIdRef.current = setTimeout(() => {
412
583
  stop();
413
584
  }, audioRecordingLimit);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nualang/nualang-ui-components",
3
- "version": "0.1.1419",
3
+ "version": "0.1.1421",
4
4
  "type": "module",
5
5
  "main": "dist/index.js",
6
6
  "files": [
@@ -177,6 +177,7 @@
177
177
  "build-storybook": "storybook build",
178
178
  "clean": "rimraf dist",
179
179
  "compile": "pnpm run clean && cross-env NODE_ENV=production babel src/components --out-dir dist --copy-files --no-copy-ignored",
180
+ "watch": "pnpm run clean && cross-env NODE_ENV=production babel src/components --out-dir dist --copy-files --no-copy-ignored --watch",
180
181
  "version": "pnpm run compile && git add -A",
181
182
  "postversion": "pnpm publish && git push && git push --tags",
182
183
  "localpack": "pnpm run compile && pnpm pack",