100+ copy-paste UI components in plain HTML and CSS: no dependencies, no build step.

0 downloads

dbbasic-web-native/voice-system.js
Download zip
Clone
Clone with git
git clone https://gitstable.com/git/askrobots/dbbasic-web-native.git
HTTPS
https://gitstable.com/git/askrobots/dbbasic-web-native.git
SSH
ssh://git@gitstable.com:2222/askrobots/dbbasic-web-native.git

Cloning needs no sign-in. Pushing over HTTPS asks for your username and an access token. SSH needs your key under SSH keys.

danq9 Add canonical.html v1.0 - The single source of truth for usability standards fb6e650 1 year ago History
voice-system.js · 17.5 KB · 539 lines
1/**
2 * Voice Command System
3 * Automatically registers voice commands based on semantic component intents
4 * Integrates with Web Speech API for recognition and synthesis
5 */
6
7class VoiceCommandSystem {
8 constructor(contextManager) {
9 this.context = contextManager;
10 this.recognition = null;
11 this.synthesis = window.speechSynthesis;
12 this.commands = new Map();
13 this.isListening = false;
14 this.confidenceThreshold = 0.7;
15
16 this.init();
17 }
18
19 init() {
20 // Check for Web Speech API support
21 if (!('webkitSpeechRecognition' in window) && !('SpeechRecognition' in window)) {
22 console.warn('Web Speech API not supported in this browser');
23 return;
24 }
25
26 const SpeechRecognition = window.SpeechRecognition || window.webkitSpeechRecognition;
27 this.recognition = new SpeechRecognition();
28
29 this.recognition.continuous = true;
30 this.recognition.interimResults = true;
31 this.recognition.lang = 'en-US';
32
33 this.setupRecognitionHandlers();
34 this.registerDefaultCommands();
35 this.observeComponents();
36 }
37
38 setupRecognitionHandlers() {
39 this.recognition.onresult = (event) => {
40 const results = Array.from(event.results);
41 const latestResult = results[results.length - 1];
42
43 if (latestResult.isFinal) {
44 const transcript = latestResult[0].transcript.toLowerCase().trim();
45 const confidence = latestResult[0].confidence;
46
47 console.log(`Voice input: "${transcript}" (confidence: ${confidence})`);
48
49 if (confidence >= this.confidenceThreshold) {
50 this.processCommand(transcript);
51 }
52 }
53 };
54
55 this.recognition.onerror = (event) => {
56 console.error('Speech recognition error:', event.error);
57
58 if (event.error === 'no-speech') {
59 // Silence is okay, just keep listening
60 return;
61 }
62
63 if (event.error === 'aborted' || event.error === 'audio-capture') {
64 this.stop();
65 }
66 };
67
68 this.recognition.onend = () => {
69 // Restart if we're supposed to be listening
70 if (this.isListening) {
71 this.recognition.start();
72 }
73 };
74 }
75
76 registerDefaultCommands() {
77 // System commands
78 this.registerCommand({
79 patterns: ['stop listening', 'voice off', 'disable voice'],
80 handler: () => this.stop(),
81 description: 'Stop voice recognition'
82 });
83
84 this.registerCommand({
85 patterns: ['what can i say', 'help', 'voice commands'],
86 handler: () => this.listCommands(),
87 description: 'List available commands'
88 });
89
90 this.registerCommand({
91 patterns: ['scroll up', 'scroll down', 'scroll to top', 'scroll to bottom'],
92 handler: (transcript) => this.handleScroll(transcript),
93 description: 'Scroll the page'
94 });
95 }
96
97 registerCommand(command) {
98 command.patterns.forEach(pattern => {
99 this.commands.set(pattern, command);
100 });
101 }
102
103 observeComponents() {
104 // Watch for components being added/removed
105 const observer = new MutationObserver(() => {
106 this.autoRegisterComponents();
107 });
108
109 observer.observe(document.body, {
110 childList: true,
111 subtree: true
112 });
113
114 // Initial registration
115 this.autoRegisterComponents();
116 }
117
118 autoRegisterComponents() {
119 // Register commands for semantic-action components
120 document.querySelectorAll('semantic-action').forEach(action => {
121 const text = action.textContent.trim();
122 if (text) {
123 const patterns = this.generatePatterns(text);
124
125 this.registerCommand({
126 patterns,
127 handler: () => {
128 action.click();
129 this.speak(`Activated ${text}`);
130 },
131 description: `Activate: ${text}`,
132 component: action
133 });
134 }
135 });
136
137 // Register commands for navigation
138 document.querySelectorAll('[data-nav-id]').forEach(nav => {
139 const id = nav.getAttribute('data-nav-id');
140 const text = nav.textContent.trim();
141
142 this.registerCommand({
143 patterns: [
144 `go to ${text.toLowerCase()}`,
145 `navigate to ${text.toLowerCase()}`,
146 `open ${text.toLowerCase()}`,
147 `show ${text.toLowerCase()}`
148 ],
149 handler: () => {
150 nav.click();
151 this.speak(`Navigating to ${text}`);
152 },
153 description: `Navigate to: ${text}`,
154 component: nav
155 });
156 });
157
158 // Register commands for cards
159 document.querySelectorAll('semantic-card card-title').forEach(card => {
160 const title = card.textContent.trim();
161 const cardElement = card.closest('semantic-card');
162
163 this.registerCommand({
164 patterns: [
165 `open ${title.toLowerCase()}`,
166 `show ${title.toLowerCase()}`,
167 `inspect ${title.toLowerCase()}`
168 ],
169 handler: () => {
170 cardElement.click();
171 this.speak(`Opening ${title}`);
172 },
173 description: `Open card: ${title}`,
174 component: cardElement
175 });
176 });
177
178 // Register commands for inputs
179 document.querySelectorAll('semantic-input[label]').forEach(input => {
180 const label = input.getAttribute('label').toLowerCase();
181
182 this.registerCommand({
183 patterns: [
184 `type ${label}`,
185 `enter ${label}`,
186 `input ${label}`,
187 `fill ${label}`
188 ],
189 handler: () => {
190 input.querySelector('input, textarea')?.focus();
191 this.speak(`Ready to input ${label}. Please speak your text.`);
192 // Start dictation mode
193 this.startDictation(input);
194 },
195 description: `Focus input: ${label}`,
196 component: input
197 });
198 });
199
200 // Register commands for adjusters
201 document.querySelectorAll('semantic-adjuster[label]').forEach(adjuster => {
202 const label = adjuster.getAttribute('label').toLowerCase();
203
204 this.registerCommand({
205 patterns: [
206 `increase ${label}`,
207 `raise ${label}`,
208 `turn up ${label}`
209 ],
210 handler: () => {
211 const step = parseFloat(adjuster.getAttribute('step') || '5');
212 adjuster.value = adjuster.value + step;
213 this.speak(`${label} increased to ${adjuster.value}`);
214 },
215 description: `Increase: ${label}`,
216 component: adjuster
217 });
218
219 this.registerCommand({
220 patterns: [
221 `decrease ${label}`,
222 `lower ${label}`,
223 `turn down ${label}`
224 ],
225 handler: () => {
226 const step = parseFloat(adjuster.getAttribute('step') || '5');
227 adjuster.value = adjuster.value - step;
228 this.speak(`${label} decreased to ${adjuster.value}`);
229 },
230 description: `Decrease: ${label}`,
231 component: adjuster
232 });
233
234 this.registerCommand({
235 patterns: [
236 `set ${label} to *`,
237 `change ${label} to *`
238 ],
239 handler: (transcript) => {
240 const match = transcript.match(/to (\d+)/);
241 if (match) {
242 const value = parseInt(match[1]);
243 adjuster.value = value;
244 this.speak(`${label} set to ${value}`);
245 }
246 },
247 description: `Set ${label} to a value`,
248 component: adjuster
249 });
250 });
251
252 // Register commands for modals
253 document.querySelectorAll('semantic-modal[id]').forEach(modal => {
254 const id = modal.getAttribute('id');
255 const header = modal.querySelector('[slot="header"]')?.textContent.trim() || id;
256
257 this.registerCommand({
258 patterns: [
259 `open ${header.toLowerCase()}`,
260 `show ${header.toLowerCase()}`
261 ],
262 handler: () => {
263 modal.open();
264 this.speak(`Opening ${header}`);
265 },
266 description: `Open modal: ${header}`,
267 component: modal
268 });
269
270 this.registerCommand({
271 patterns: [
272 `close ${header.toLowerCase()}`,
273 `dismiss ${header.toLowerCase()}`
274 ],
275 handler: () => {
276 modal.close();
277 this.speak(`Closing ${header}`);
278 },
279 description: `Close modal: ${header}`,
280 component: modal
281 });
282 });
283
284 // Generic close commands
285 this.registerCommand({
286 patterns: ['close', 'dismiss', 'cancel', 'go back'],
287 handler: () => {
288 // Try to close any open modal
289 const openModal = document.querySelector('semantic-modal[open]');
290 if (openModal) {
291 openModal.close();
292 this.speak('Closed');
293 return;
294 }
295
296 // Try to close any open menu
297 const openMenu = document.querySelector('semantic-menu[open]');
298 if (openMenu) {
299 openMenu.close();
300 this.speak('Closed menu');
301 return;
302 }
303
304 this.speak('Nothing to close');
305 },
306 description: 'Close current dialog or menu'
307 });
308 }
309
310 generatePatterns(text) {
311 const lower = text.toLowerCase();
312 return [
313 lower,
314 `click ${lower}`,
315 `press ${lower}`,
316 `activate ${lower}`,
317 `select ${lower}`
318 ];
319 }
320
321 processCommand(transcript) {
322 // Try exact match first
323 if (this.commands.has(transcript)) {
324 const command = this.commands.get(transcript);
325 command.handler(transcript);
326 return;
327 }
328
329 // Try wildcard patterns
330 for (const [pattern, command] of this.commands.entries()) {
331 if (pattern.includes('*')) {
332 const regex = new RegExp('^' + pattern.replace('*', '.*') + '$');
333 if (regex.test(transcript)) {
334 command.handler(transcript);
335 return;
336 }
337 }
338 }
339
340 // Try fuzzy matching for close matches
341 const matches = this.fuzzyMatch(transcript);
342 if (matches.length > 0) {
343 const bestMatch = matches[0];
344 console.log(`Using fuzzy match: "${bestMatch.pattern}" for "${transcript}"`);
345 bestMatch.command.handler(transcript);
346 return;
347 }
348
349 // No match found
350 console.log(`No command found for: "${transcript}"`);
351 this.speak("I didn't understand that command. Say 'help' for available commands.");
352 }
353
354 fuzzyMatch(transcript) {
355 const matches = [];
356
357 for (const [pattern, command] of this.commands.entries()) {
358 const similarity = this.similarity(transcript, pattern);
359 if (similarity > 0.7) {
360 matches.push({ pattern, command, similarity });
361 }
362 }
363
364 return matches.sort((a, b) => b.similarity - a.similarity);
365 }
366
367 similarity(s1, s2) {
368 // Levenshtein distance for fuzzy matching
369 const longer = s1.length > s2.length ? s1 : s2;
370 const shorter = s1.length > s2.length ? s2 : s1;
371
372 if (longer.length === 0) return 1.0;
373
374 const distance = this.levenshteinDistance(longer, shorter);
375 return (longer.length - distance) / longer.length;
376 }
377
378 levenshteinDistance(s1, s2) {
379 const matrix = [];
380
381 for (let i = 0; i <= s2.length; i++) {
382 matrix[i] = [i];
383 }
384
385 for (let j = 0; j <= s1.length; j++) {
386 matrix[0][j] = j;
387 }
388
389 for (let i = 1; i <= s2.length; i++) {
390 for (let j = 1; j <= s1.length; j++) {
391 if (s2.charAt(i - 1) === s1.charAt(j - 1)) {
392 matrix[i][j] = matrix[i - 1][j - 1];
393 } else {
394 matrix[i][j] = Math.min(
395 matrix[i - 1][j - 1] + 1,
396 matrix[i][j - 1] + 1,
397 matrix[i - 1][j] + 1
398 );
399 }
400 }
401 }
402
403 return matrix[s2.length][s1.length];
404 }
405
406 handleScroll(transcript) {
407 if (transcript.includes('up')) {
408 window.scrollBy({ top: -300, behavior: 'smooth' });
409 this.speak('Scrolling up');
410 } else if (transcript.includes('down')) {
411 window.scrollBy({ top: 300, behavior: 'smooth' });
412 this.speak('Scrolling down');
413 } else if (transcript.includes('top')) {
414 window.scrollTo({ top: 0, behavior: 'smooth' });
415 this.speak('Scrolling to top');
416 } else if (transcript.includes('bottom')) {
417 window.scrollTo({ top: document.body.scrollHeight, behavior: 'smooth' });
418 this.speak('Scrolling to bottom');
419 }
420 }
421
422 startDictation(inputComponent) {
423 // Special dictation mode for filling inputs
424 const input = inputComponent.shadowRoot.querySelector('input, textarea');
425 if (!input) return;
426
427 const dictationHandler = (event) => {
428 const results = Array.from(event.results);
429 const latestResult = results[results.length - 1];
430
431 if (latestResult.isFinal) {
432 const transcript = latestResult[0].transcript;
433 input.value = transcript;
434 inputComponent.value = transcript;
435
436 this.speak('Text entered');
437 this.recognition.removeEventListener('result', dictationHandler);
438 }
439 };
440
441 this.recognition.addEventListener('result', dictationHandler);
442 }
443
444 listCommands() {
445 const commandList = Array.from(this.commands.values())
446 .filter((cmd, idx, self) => self.indexOf(cmd) === idx) // Unique commands
447 .slice(0, 10) // Top 10
448 .map(cmd => cmd.description)
449 .join('. ');
450
451 this.speak(`Available commands: ${commandList}`);
452 }
453
454 speak(text, options = {}) {
455 if (!this.synthesis) return;
456
457 // Cancel any ongoing speech
458 this.synthesis.cancel();
459
460 // Adjust speech based on context
461 const context = this.context.context;
462
463 // Don't speak if user is busy or noise level is high
464 if (context.user.isBusy && options.urgency !== 'critical') return;
465 if (context.environment.noiseLevel > 70 && options.urgency !== 'critical') return;
466
467 const utterance = new SpeechSynthesisUtterance(text);
468
469 // Adjust rate and pitch based on urgency
470 utterance.rate = options.urgency === 'critical' ? 0.9 : 1.0;
471 utterance.pitch = options.urgency === 'critical' ? 1.2 : 1.0;
472 utterance.volume = Math.max(0.5, (100 - context.environment.noiseLevel) / 100);
473
474 this.synthesis.speak(utterance);
475 }
476
477 start() {
478 if (!this.recognition) {
479 console.warn('Speech recognition not available');
480 return;
481 }
482
483 if (this.isListening) return;
484
485 this.isListening = true;
486 this.recognition.start();
487 this.speak('Voice commands activated');
488
489 // Update context
490 this.context.setModality('voice-screen');
491
492 console.log('Voice recognition started');
493 }
494
495 stop() {
496 if (!this.recognition || !this.isListening) return;
497
498 this.isListening = false;
499 this.recognition.stop();
500 this.speak('Voice commands deactivated');
501
502 // Reset to screen modality
503 this.context.setModality('screen');
504
505 console.log('Voice recognition stopped');
506 }
507
508 toggle() {
509 if (this.isListening) {
510 this.stop();
511 } else {
512 this.start();
513 }
514 }
515}
516
517// Initialize voice system when context is ready
518if (typeof window !== 'undefined') {
519 window.addEventListener('DOMContentLoaded', () => {
520 if (window.semanticContext) {
521 window.voiceSystem = new VoiceCommandSystem(window.semanticContext);
522
523 // Add keyboard shortcut to toggle voice (Ctrl+Shift+V)
524 document.addEventListener('keydown', (e) => {
525 if (e.ctrlKey && e.shiftKey && e.key === 'V') {
526 e.preventDefault();
527 window.voiceSystem.toggle();
528 }
529 });
530
531 console.log('Voice command system initialized. Press Ctrl+Shift+V to toggle voice commands.');
532 }
533 });
534}
535
536// Export
537if (typeof module !== 'undefined' && module.exports) {
538 module.exports = VoiceCommandSystem;
539}