-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathApp.tsx
More file actions
404 lines (347 loc) · 11.5 KB
/
App.tsx
File metadata and controls
404 lines (347 loc) · 11.5 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
import React, { useEffect, useRef, useState } from 'react';
import TitleSlide from './slides/TitleSlide';
import PlaceholderSlide from './slides/PlaceholderSlide';
import Footer from './components/Footer';
const slides = [
<TitleSlide />,
<PlaceholderSlide />,
];
let hasAttemptedInitialVoiceStart = false;
const MIN_ZOOM_LEVEL = 0.8;
const MAX_ZOOM_LEVEL = 1.4;
const ZOOM_STEP = 0.1;
type VoiceAction =
| 'next'
| 'previous'
| 'startAnimation'
| 'stopAnimation'
| 'zoomIn'
| 'zoomOut';
const VOICE_COMMANDS: Array<{
action: VoiceAction;
label: string;
phrases: string[];
}> = [
{ action: 'next', label: 'Next Slide', phrases: ['next slide please', 'next slide'] },
{
action: 'previous',
label: 'Previous Slide',
phrases: ['previous slide please', 'previous slide', 'lets go back', 'go back'],
},
{ action: 'startAnimation', label: 'Start Animation', phrases: ['start animation'] },
{ action: 'stopAnimation', label: 'Stop Animation', phrases: ['stop animation'] },
{ action: 'zoomOut', label: 'Zoom Out', phrases: ['zoom out'] },
{ action: 'zoomIn', label: 'Zoom In', phrases: ['zoom in'] },
];
const normalizeTranscript = (transcript: string) =>
transcript
.toLowerCase()
.replace(/['’]/g, '')
.replace(/[^a-z0-9\s]/g, ' ')
.replace(/\s+/g, ' ')
.trim();
const clampZoomLevel = (zoomLevel: number) =>
Number(Math.min(MAX_ZOOM_LEVEL, Math.max(MIN_ZOOM_LEVEL, zoomLevel)).toFixed(2));
const getSpeechRecognition = () => {
if (typeof window === 'undefined') {
return null;
}
return window.SpeechRecognition ?? window.webkitSpeechRecognition ?? null;
};
const getVoiceErrorMessage = (error: string) => {
switch (error) {
case 'audio-capture':
return 'No microphone was found for voice commands.';
case 'network':
return 'Voice recognition hit a network error.';
case 'not-allowed':
case 'service-not-allowed':
return 'Microphone access was denied.';
default:
return 'Voice recognition stopped unexpectedly.';
}
};
const getMicrophonePermissionErrorMessage = (error: unknown) => {
if (error instanceof DOMException) {
switch (error.name) {
case 'NotAllowedError':
case 'SecurityError':
return 'Microphone access was denied.';
case 'NotFoundError':
return 'No microphone was found for voice commands.';
case 'NotReadableError':
return 'The microphone is busy in another application.';
default:
return error.message || 'Microphone access could not be started.';
}
}
return error instanceof Error ? error.message : 'Microphone access could not be started.';
};
const App: React.FC = () => {
const [currentSlide, setCurrentSlide] = useState(0);
const [zoomLevel, setZoomLevel] = useState(1);
const [animationsPaused, setAnimationsPaused] = useState(false);
const [isFullscreen, setIsFullscreen] = useState(false);
const [isVoiceEnabled, setIsVoiceEnabled] = useState(false);
const [isVoiceListening, setIsVoiceListening] = useState(false);
const [lastHeard, setLastHeard] = useState<string | null>(null);
const [lastCommand, setLastCommand] = useState<string | null>(null);
const [voiceError, setVoiceError] = useState<string | null>(null);
const recognitionRef = useRef<SpeechRecognition | null>(null);
const shouldKeepListeningRef = useRef(false);
const isVoiceSupported = getSpeechRecognition() !== null;
const commandHandlersRef = useRef({
next: () => undefined,
previous: () => undefined,
startAnimation: () => undefined,
stopAnimation: () => undefined,
zoomIn: () => undefined,
zoomOut: () => undefined,
});
const goToNext = () => {
setCurrentSlide(prev => Math.min(slides.length - 1, prev + 1));
};
const goToPrev = () => {
setCurrentSlide(prev => Math.max(0, prev - 1));
};
const zoomIn = () => {
setZoomLevel(prev => clampZoomLevel(prev + ZOOM_STEP));
};
const zoomOut = () => {
setZoomLevel(prev => clampZoomLevel(prev - ZOOM_STEP));
};
const startAnimations = () => {
setAnimationsPaused(false);
};
const stopAnimations = () => {
setAnimationsPaused(true);
};
const toggleFullscreen = () => {
if (!document.fullscreenElement) {
document.documentElement.requestFullscreen();
} else {
if (document.exitFullscreen) {
document.exitFullscreen();
}
}
};
useEffect(() => {
const handleFullscreenChange = () => {
setIsFullscreen(Boolean(document.fullscreenElement));
};
document.addEventListener('fullscreenchange', handleFullscreenChange);
handleFullscreenChange();
return () => {
document.removeEventListener('fullscreenchange', handleFullscreenChange);
};
}, []);
commandHandlersRef.current = {
next: goToNext,
previous: goToPrev,
startAnimation: startAnimations,
stopAnimation: stopAnimations,
zoomIn,
zoomOut,
};
const setVoiceControlsEnabled = (shouldEnable: boolean) => {
if (!isVoiceSupported) {
setVoiceError('Voice recognition is not supported in this browser.');
return;
}
const recognition = recognitionRef.current;
if (!recognition) {
return;
}
shouldKeepListeningRef.current = shouldEnable;
setIsVoiceEnabled(shouldEnable);
setVoiceError(null);
try {
if (shouldEnable) {
recognition.start();
return;
}
recognition.stop();
} catch (error) {
if (error instanceof DOMException && error.name === 'InvalidStateError') {
return;
}
shouldKeepListeningRef.current = false;
setIsVoiceEnabled(false);
setVoiceError(error instanceof Error ? error.message : 'Voice recognition could not start.');
}
};
const requestMicrophonePermission = async () => {
if (typeof navigator === 'undefined' || !navigator.mediaDevices?.getUserMedia) {
setVoiceControlsEnabled(true);
return;
}
try {
const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
stream.getTracks().forEach(track => track.stop());
setVoiceControlsEnabled(true);
} catch (error) {
shouldKeepListeningRef.current = false;
setIsVoiceEnabled(false);
setVoiceError(getMicrophonePermissionErrorMessage(error));
}
};
// Keyboard navigation
useEffect(() => {
const handleKeyDown = (e: KeyboardEvent) => {
if (e.key === 'ArrowRight' || e.key === 'ArrowDown') {
goToNext();
} else if (e.key === 'ArrowLeft' || e.key === 'ArrowUp') {
goToPrev();
} else if (e.key === 'f' || e.key === 'F') {
toggleFullscreen();
} else if (e.key === '+') {
zoomIn();
} else if (e.key === '-') {
zoomOut();
} else if (e.key === ' ') {
if (animationsPaused) {
startAnimations();
} else {
stopAnimations();
}
} else if (e.key === 'v' || e.key === 'V') {
if (shouldKeepListeningRef.current) {
setVoiceControlsEnabled(false);
} else {
void requestMicrophonePermission();
}
}
};
window.addEventListener('keydown', handleKeyDown);
return () => window.removeEventListener('keydown', handleKeyDown);
}, [animationsPaused]);
useEffect(() => {
if (!isVoiceSupported) {
return undefined;
}
const SpeechRecognition = getSpeechRecognition();
if (!SpeechRecognition) {
return undefined;
}
const recognition = new SpeechRecognition();
recognition.continuous = true;
recognition.interimResults = false;
recognition.lang = 'en-US';
recognition.maxAlternatives = 3;
recognition.onstart = () => {
setVoiceError(null);
setIsVoiceListening(true);
};
recognition.onresult = (event: SpeechRecognitionEvent) => {
for (let resultIndex = event.resultIndex; resultIndex < event.results.length; resultIndex += 1) {
const result = event.results[resultIndex];
if (!result.isFinal) {
continue;
}
const transcripts = Array.from({ length: result.length }, (_, index) => result[index].transcript);
const primaryTranscript = transcripts[0]?.trim();
if (primaryTranscript) {
setLastHeard(primaryTranscript);
}
const matchedCommand = transcripts
.map(transcript => normalizeTranscript(transcript))
.map(normalizedTranscript =>
VOICE_COMMANDS.find(command =>
command.phrases.some(phrase => phrase === normalizedTranscript)
)
)
.find(Boolean);
if (!matchedCommand) {
continue;
}
setLastCommand(matchedCommand.label);
commandHandlersRef.current[matchedCommand.action]();
}
};
recognition.onerror = (event: SpeechRecognitionErrorEvent) => {
if (event.error === 'aborted' && !shouldKeepListeningRef.current) {
return;
}
if (event.error === 'no-speech') {
return;
}
shouldKeepListeningRef.current = false;
setIsVoiceEnabled(false);
setIsVoiceListening(false);
setVoiceError(getVoiceErrorMessage(event.error));
};
recognition.onend = () => {
setIsVoiceListening(false);
if (!shouldKeepListeningRef.current) {
setIsVoiceEnabled(false);
return;
}
try {
recognition.start();
} catch (error) {
shouldKeepListeningRef.current = false;
setIsVoiceEnabled(false);
setVoiceError(
error instanceof Error ? error.message : 'Voice recognition could not restart.'
);
}
};
recognitionRef.current = recognition;
if (!hasAttemptedInitialVoiceStart) {
const initialVoiceStartTimeout = window.setTimeout(() => {
if (recognitionRef.current === recognition && !hasAttemptedInitialVoiceStart) {
hasAttemptedInitialVoiceStart = true;
void requestMicrophonePermission();
}
}, 0);
return () => {
window.clearTimeout(initialVoiceStartTimeout);
shouldKeepListeningRef.current = false;
recognition.onstart = null;
recognition.onresult = null;
recognition.onerror = null;
recognition.onend = null;
recognition.abort();
recognitionRef.current = null;
};
}
return () => {
shouldKeepListeningRef.current = false;
recognition.onstart = null;
recognition.onresult = null;
recognition.onerror = null;
recognition.onend = null;
recognition.abort();
recognitionRef.current = null;
};
}, [isVoiceSupported]);
return (
<div className="min-h-screen w-full flex flex-col items-center justify-center p-4 bg-slate-900 font-sans">
<main className="relative z-0 w-full max-w-7xl flex-grow flex flex-col items-center justify-center">
<div
className={`presentation-stage w-full ${animationsPaused ? 'animations-paused' : ''}`}
style={{ transform: `scale(${zoomLevel})` }}
>
<div className="slide-container w-full">
{slides[currentSlide]}
</div>
</div>
</main>
<Footer
currentSlide={currentSlide}
goToNext={goToNext}
goToPrev={goToPrev}
isFullscreen={isFullscreen}
isVoiceEnabled={isVoiceEnabled}
isVoiceListening={isVoiceListening}
isVoiceSupported={isVoiceSupported}
lastCommand={lastCommand}
lastHeard={lastHeard}
slides={slides}
toggleFullscreen={toggleFullscreen}
voiceError={voiceError}
/>
</div>
);
};
export default App;