-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcontent.js
More file actions
567 lines (489 loc) · 16.7 KB
/
Copy pathcontent.js
File metadata and controls
567 lines (489 loc) · 16.7 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
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
// Voice Claude - Content Script
// Injects voice functionality into claude.ai
console.log('Voice Claude: Content script loaded');
// State
let isListening = false;
let isSpeaking = false;
let recognition = null;
let synthesis = window.speechSynthesis;
let responseObserver = null;
let lastResponseText = '';
let lastResponseTime = 0;
let pendingResponseText = ''; // Store current response for button clicks
let responseTimeout = null;
let autoSpeak = false;
// Initialize speech recognition
function initSpeechRecognition() {
if (!('webkitSpeechRecognition' in window) && !('SpeechRecognition' in window)) {
console.error('Voice Claude: Speech recognition not supported');
return null;
}
const SpeechRecognition = window.SpeechRecognition || window.webkitSpeechRecognition;
const recognizer = new SpeechRecognition();
recognizer.continuous = false;
recognizer.interimResults = true;
recognizer.lang = 'en-US';
recognizer.onstart = () => {
console.log('Voice Claude: Recognition started');
isListening = true;
updateMicButtonState(true);
showTranscriptOverlay();
};
recognizer.onresult = (event) => {
let interimTranscript = '';
let finalTranscript = '';
for (let i = event.resultIndex; i < event.results.length; i++) {
const transcript = event.results[i][0].transcript;
if (event.results[i].isFinal) {
finalTranscript += transcript;
} else {
interimTranscript += transcript;
}
}
// Show in transcript overlay
const currentText = interimTranscript || finalTranscript;
updateTranscriptOverlay(currentText, !interimTranscript);
// If final, update the textarea
if (finalTranscript) {
const textarea = findPromptTextarea();
if (textarea) {
// For contenteditable divs, use textContent or innerText
if (textarea.contentEditable === 'true') {
textarea.textContent = finalTranscript;
// Trigger input event for React
textarea.dispatchEvent(new Event('input', { bubbles: true }));
textarea.dispatchEvent(new Event('change', { bubbles: true }));
} else {
// For regular textareas
textarea.value = finalTranscript;
textarea.dispatchEvent(new Event('input', { bubbles: true }));
}
textarea.focus();
console.log('Voice Claude: Inserted text:', finalTranscript);
}
}
};
recognizer.onerror = (event) => {
console.error('Voice Claude: Recognition error:', event.error);
isListening = false;
updateMicButtonState(false);
showNotification('Voice input error: ' + event.error, 'error');
};
recognizer.onend = () => {
console.log('Voice Claude: Recognition ended');
isListening = false;
updateMicButtonState(false);
hideTranscriptOverlay();
};
return recognizer;
}
// Find the prompt textarea on claude.ai
function findPromptTextarea() {
// Claude.ai uses different selectors, try multiple approaches
const selectors = [
'div[contenteditable="true"]',
'textarea',
'[role="textbox"]',
'.ProseMirror'
];
for (const selector of selectors) {
const element = document.querySelector(selector);
if (element) {
console.log('Voice Claude: Found textarea with selector:', selector);
return element;
}
}
console.warn('Voice Claude: Could not find prompt textarea');
return null;
}
// Find the send button
function findSendButton() {
// Try to find the send button
const selectors = [
'button[aria-label*="Send"]',
'button[type="submit"]',
'button svg',
];
for (const selector of selectors) {
const button = document.querySelector(selector);
if (button) {
// If it's an SVG, get the parent button
if (button.tagName === 'svg') {
return button.closest('button');
}
return button;
}
}
return null;
}
// Create and inject mic button
function injectMicButton() {
// Check if already injected
if (document.getElementById('voice-claude-mic')) {
console.log('Voice Claude: Mic button already exists');
return;
}
// Find the input area to inject near
const textarea = findPromptTextarea();
if (!textarea) {
console.log('Voice Claude: Textarea not found, will retry');
setTimeout(injectMicButton, 1000);
return;
}
// Create mic button
const micButton = document.createElement('button');
micButton.id = 'voice-claude-mic';
micButton.className = 'voice-claude-mic-btn';
micButton.innerHTML = `
<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
<path d="M12 1a3 3 0 0 0-3 3v8a3 3 0 0 0 6 0V4a3 3 0 0 0-3-3z"></path>
<path d="M19 10v2a7 7 0 0 1-14 0v-2"></path>
<line x1="12" y1="19" x2="12" y2="23"></line>
<line x1="8" y1="23" x2="16" y2="23"></line>
</svg>
`;
micButton.title = 'Voice input (click to speak)';
micButton.addEventListener('click', (e) => {
e.preventDefault();
e.stopPropagation();
handleMicClick();
});
// Inject directly into body to avoid React conflicts
// This ensures React won't remove our button when it re-renders
document.body.appendChild(micButton);
console.log('Voice Claude: Mic button injected into body (fixed position)');
// Store reference to textarea for later use
micButton.dataset.textareaFound = 'true';
}
// Handle mic button click
function handleMicClick() {
if (isListening) {
recognition?.stop();
} else {
if (!recognition) {
recognition = initSpeechRecognition();
}
if (recognition) {
try {
recognition.start();
} catch (error) {
console.error('Voice Claude: Failed to start recognition:', error);
showNotification('Failed to start voice input', 'error');
}
} else {
showNotification('Speech recognition not available', 'error');
}
}
}
// Update mic button visual state
function updateMicButtonState(listening) {
const micButton = document.getElementById('voice-claude-mic');
if (micButton) {
if (listening) {
micButton.classList.add('listening');
} else {
micButton.classList.remove('listening');
}
}
}
// Show notification banner
function showNotification(message, type = 'info') {
// Remove existing notification
const existing = document.getElementById('voice-claude-notification');
if (existing) {
existing.remove();
}
// Create notification
const notification = document.createElement('div');
notification.id = 'voice-claude-notification';
notification.className = `voice-claude-notification ${type}`;
notification.innerHTML = `
<div class="notification-content">
<span>${message}</span>
<button class="notification-close">×</button>
</div>
`;
document.body.appendChild(notification);
// Close button
notification.querySelector('.notification-close').addEventListener('click', () => {
notification.remove();
});
// Auto-remove after 5 seconds
setTimeout(() => {
if (notification.parentElement) {
notification.remove();
}
}, 5000);
}
// Show response notification with TTS option
function showResponseNotification(responseText) {
// Remove existing notification
const existing = document.getElementById('voice-claude-notification');
if (existing) {
existing.remove();
}
// Store response text for button click
pendingResponseText = responseText;
// Create notification
const notification = document.createElement('div');
notification.id = 'voice-claude-notification';
notification.className = 'voice-claude-notification response';
notification.innerHTML = `
<div class="notification-content">
<span>Claude has responded - want to hear it?</span>
<div class="notification-actions">
<button class="notification-btn yes">Yes, let's hear</button>
<button class="notification-btn no">No thanks</button>
</div>
</div>
`;
document.body.appendChild(notification);
// Yes button - play TTS (call directly to preserve user gesture)
notification.querySelector('.yes').addEventListener('click', () => {
notification.remove();
// Call TTS directly without setTimeout to preserve user gesture
speakTextImmediate(pendingResponseText);
});
// No button - close
notification.querySelector('.no').addEventListener('click', () => {
notification.remove();
pendingResponseText = '';
});
// Auto-remove after 10 seconds
setTimeout(() => {
if (notification.parentElement) {
notification.remove();
pendingResponseText = '';
}
}, 10000);
}
// Text-to-speech (immediate, for button clicks)
function speakTextImmediate(text) {
if (!text || text.length === 0) {
console.error('Voice Claude: No text to speak');
return;
}
console.log('Voice Claude: Starting TTS immediately, text length:', text.length);
// Stop any ongoing speech
if (isSpeaking) {
console.log('Voice Claude: Canceling previous speech');
synthesis.cancel();
}
// Check if voices are available
const voices = synthesis.getVoices();
console.log('Voice Claude: Available voices:', voices.length);
if (voices.length === 0) {
console.warn('Voice Claude: No voices available yet, waiting...');
// Wait for voices to load
setTimeout(() => {
const retryVoices = synthesis.getVoices();
console.log('Voice Claude: Voices after wait:', retryVoices.length);
if (retryVoices.length === 0) {
showNotification('No TTS voices available in browser', 'error');
return;
}
speakTextImmediate(text);
}, 100);
return;
}
const utterance = new SpeechSynthesisUtterance(text);
utterance.rate = 1.0;
utterance.pitch = 1.0;
utterance.volume = 1.0;
// Don't set voice - let browser use default
console.log('Voice Claude: Using default voice (not setting utterance.voice)');
utterance.onstart = () => {
console.log('Voice Claude: Speaking started');
isSpeaking = true;
showNotification('Speaking...', 'speaking');
};
utterance.onend = () => {
console.log('Voice Claude: Speaking ended');
isSpeaking = false;
pendingResponseText = '';
const existing = document.getElementById('voice-claude-notification');
if (existing) {
existing.remove();
}
};
utterance.onerror = (event) => {
console.error('Voice Claude: TTS error:', event.error);
isSpeaking = false;
if (event.error !== 'canceled' && event.error !== 'interrupted') {
showNotification('Error speaking response: ' + event.error, 'error');
}
};
console.log('Voice Claude: Calling synthesis.speak()...');
synthesis.speak(utterance);
console.log('Voice Claude: synthesis.speak() called, pending:', synthesis.pending, 'speaking:', synthesis.speaking);
}
// Text-to-speech (with delay, for auto-speak)
function speakText(text) {
// For auto-speak, use small delay to allow previous speech to cancel
setTimeout(() => speakTextImmediate(text), 100);
}
// Show transcript overlay
function showTranscriptOverlay() {
// Remove existing overlay
const existing = document.getElementById('voice-claude-transcript-overlay');
if (existing) {
existing.remove();
}
// Create overlay
const overlay = document.createElement('div');
overlay.id = 'voice-claude-transcript-overlay';
overlay.className = 'voice-claude-transcript-overlay';
overlay.innerHTML = `
<div class="transcript-header">
<div class="listening-indicator">
<span class="pulse-dot"></span>
<span>Listening...</span>
</div>
</div>
<div class="transcript-text" id="voice-claude-transcript-text">
Start speaking...
</div>
`;
document.body.appendChild(overlay);
}
// Update transcript overlay
function updateTranscriptOverlay(text, isFinal) {
const overlay = document.getElementById('voice-claude-transcript-overlay');
if (!overlay) return;
const textElement = document.getElementById('voice-claude-transcript-text');
if (textElement) {
if (text) {
textElement.textContent = text;
if (isFinal) {
textElement.classList.add('final');
} else {
textElement.classList.remove('final');
}
} else {
textElement.textContent = 'Start speaking...';
textElement.classList.remove('final');
}
}
}
// Hide transcript overlay
function hideTranscriptOverlay() {
const overlay = document.getElementById('voice-claude-transcript-overlay');
if (overlay) {
overlay.classList.add('fade-out');
setTimeout(() => overlay.remove(), 300);
}
}
// Detect when Claude responds
function observeResponses() {
// Find the chat container
const chatContainer = document.querySelector('main') || document.body;
responseObserver = new MutationObserver((mutations) => {
try {
// Look for new messages from Claude
for (const mutation of mutations) {
if (!mutation.addedNodes) continue;
for (const node of mutation.addedNodes) {
if (!node || node.nodeType !== 1) continue;
// Skip our own extension elements
if (node.id && node.id.includes('voice-claude')) {
continue;
}
if (node.className && typeof node.className === 'string' &&
node.className.includes('voice-claude')) {
continue;
}
// Try to find Claude response elements
let responseElement = null;
// Strategy 1: Check if node matches Claude response patterns
if (node.matches) {
if (node.matches('[data-role="assistant"]') ||
node.matches('[class*="font-claude"]') ||
node.matches('[class*="claude-response"]')) {
responseElement = node;
}
}
// Strategy 2: Look for response elements within the node
if (!responseElement && node.querySelectorAll) {
const found = node.querySelector('[data-role="assistant"], [class*="font-claude"], [class*="claude-response"]');
if (found) {
responseElement = found;
}
}
if (responseElement) {
const responseText = responseElement.textContent?.trim() || '';
const now = Date.now();
// Debounce: Only process if enough time has passed or text is significantly different
const timeSinceLastResponse = now - lastResponseTime;
const textChanged = responseText !== lastResponseText;
const significantChange = Math.abs(responseText.length - lastResponseText.length) > 50;
// Filter out incomplete responses and ensure it's new
if (responseText &&
textChanged &&
responseText.length > 20 &&
(timeSinceLastResponse > 3000 || significantChange) &&
!responseText.includes('Thinking') &&
!responseText.includes('Pondering') &&
!responseText.includes('stand by')) {
console.log('Voice Claude: New response detected, length:', responseText.length);
lastResponseText = responseText;
lastResponseTime = now;
// Clear any pending notification
if (responseTimeout) {
clearTimeout(responseTimeout);
}
// Wait for response to fully render
responseTimeout = setTimeout(() => {
try {
if (autoSpeak) {
speakText(lastResponseText);
} else {
showResponseNotification(lastResponseText);
}
} catch (err) {
console.error('Voice Claude: Error handling response:', err);
}
}, 1500); // Longer wait to ensure complete response
}
}
}
}
} catch (err) {
console.error('Voice Claude: Error in mutation observer:', err);
}
});
try {
responseObserver.observe(chatContainer, {
childList: true,
subtree: true
});
console.log('Voice Claude: Response observer initialized');
} catch (err) {
console.error('Voice Claude: Error starting observer:', err);
}
}
// Initialize extension
function initialize() {
console.log('Voice Claude: Initializing...');
// Inject mic button
injectMicButton();
// Start observing for responses
observeResponses();
// Load settings
chrome.storage.local.get(['autoSpeak'], (result) => {
autoSpeak = result.autoSpeak || false;
console.log('Voice Claude: Auto-speak:', autoSpeak);
});
}
// Wait for page to load
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', initialize);
} else {
initialize();
}
// Listen for settings changes
chrome.storage.onChanged.addListener((changes) => {
if (changes.autoSpeak) {
autoSpeak = changes.autoSpeak.newValue;
console.log('Voice Claude: Auto-speak changed to:', autoSpeak);
}
});