-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathdictation.js
More file actions
535 lines (463 loc) · 19.9 KB
/
dictation.js
File metadata and controls
535 lines (463 loc) · 19.9 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
// dictation.js
import * as idb from './lib/idb-keyval-wrapper.js';
import { detectLanguage } from './lib/detect-language.js';
document.addEventListener('DOMContentLoaded', () => {
// --- Constants ---
const DB_PREFIX = 'dictation-';
const DB_CONFIG_KEY = 'dictation-config';
const SESSION_STORAGE_KEY = 'dictation-session';
// --- DOM Elements ---
const textSelect = document.getElementById('text-select');
const newTextBtn = document.getElementById('new-text-btn');
const deleteTextBtn = document.getElementById('delete-text-btn');
const textDisplay = document.getElementById('text-display');
const writingInput = document.getElementById('writing-input');
const speedSlider = document.getElementById('speed-slider');
const fontSizeSelect = document.getElementById('font-size-select');
const fontFamilySelect = document.getElementById('font-family-select');
const hideTextCheckbox = document.getElementById('hide-text-checkbox');
const readNextCheckbox = document.getElementById('read-next-checkbox');
const readOnCorrectCheckbox = document.getElementById('read-on-correct-checkbox');
const ignoreAccentsCheckbox = document.getElementById('ignore-accents-checkbox');
const ignorePunctuationCheckbox = document.getElementById('ignore-punctuation-checkbox');
const ignoreCaseCheckbox = document.getElementById('ignore-case-checkbox');
const waitForSpaceCheckbox = document.getElementById('wait-for-space-checkbox');
const textTitleInput = document.getElementById('text-title-input');
const textContentTextarea = document.getElementById('text-content-textarea');
const saveTextBtn = document.getElementById('save-text-btn');
const repeatWordBtn = document.getElementById('repeat-word-btn');
const toggleHiddenBtn = document.getElementById('toggle-hidden-btn');
const resetSettingsBtn = document.getElementById('reset-settings-btn');
const notificationArea = document.getElementById('notification-area');
const configPanel = document.getElementById('config-panel');
const menuToggleBtn = document.getElementById('menu-toggle-btn');
// --- App State ---
let texts = {};
let sourceWords = [];
let currentWordIndex = 0;
let originalTitle = null; // Used for editing/renaming texts
let tabKeyPressCount = 0;
let speechQueue = [];
// --- Function Declarations (ordered to prevent no-use-before-define) ---
// ** Level 1: No Dependencies **
const stripPunctuation = (str) => str.replace(/[\p{P}]/gu, '');
const showNotification = (message, duration = 3000) => {
notificationArea.textContent = message;
notificationArea.classList.remove('hidden');
setTimeout(() => {
notificationArea.classList.add('hidden');
}, duration);
};
const saveSession = () => {
if (textSelect.value) {
const sessionData = {
title: textSelect.value,
userInput: writingInput.value
};
sessionStorage.setItem(SESSION_STORAGE_KEY, JSON.stringify(sessionData));
}
};
const loadSession = () => {
const session = sessionStorage.getItem(SESSION_STORAGE_KEY);
return session ? JSON.parse(session) : null;
};
const updateTextList = () => {
const selectedValue = textSelect.value;
textSelect.innerHTML = '';
Object.keys(texts).forEach(title => {
const option = document.createElement('option');
option.value = title;
option.textContent = title;
textSelect.appendChild(option);
});
if (selectedValue) {
textSelect.value = selectedValue;
}
};
const clearEditor = () => {
textSelect.value = '';
textTitleInput.value = '';
textContentTextarea.value = '';
originalTitle = null;
textTitleInput.focus();
};
const normalizeWord = (word) => {
let normalized = word;
if (ignoreCaseCheckbox.checked) {
normalized = normalized.toLowerCase();
}
if (ignoreAccentsCheckbox.checked) {
normalized = normalized.normalize("NFD").replace(/[\u0300-\u036f]/g, "");
}
if (ignorePunctuationCheckbox.checked) {
normalized = normalized.replace(/[\p{P}]/gu, '');
}
return normalized;
};
const createDiffHtml = (actual, expected) => {
const diff = Diff.diffChars(actual, expected);
const fragment = document.createDocumentFragment();
diff.forEach((part) => {
const span = document.createElement('span');
span.className = part.added ? 'diff-added' : part.removed ? 'diff-removed' : 'diff-correct';
span.appendChild(document.createTextNode(part.value));
fragment.appendChild(span);
});
return fragment;
};
const obscureWord = (word) => {
// Replaces letters and numbers with black boxes, preserves punctuation.
return word.replace(/[\p{L}\p{N}]/gu, '■');
};
// ** Level 2: Dependencies on Level 1 **
let isSpeaking = false;
const processSpeechQueue = () => {
if (isSpeaking || speechQueue.length === 0) {
return;
}
isSpeaking = true;
const { word, rate } = speechQueue.shift();
console.log(`Speaking: ${word}`);
const utterance = new SpeechSynthesisUtterance(word);
utterance.lang = textDisplay.lang || 'en';
utterance.rate = rate;
utterance.onend = () => {
isSpeaking = false;
processSpeechQueue();
};
speechSynthesis.speak(utterance);
};
const speakWord = (word, rate) => {
if (!('speechSynthesis' in window)) return;
speechQueue.push({ word, rate: rate || parseFloat(speedSlider.value) });
processSpeechQueue();
};
const speakImmediately = (word, rate) => {
if (!('speechSynthesis' in window)) return;
speechQueue = []; // Clear the queue
speechSynthesis.cancel(); // Stop any current speech
isSpeaking = false;
speakWord(word, rate);
};
const loadTexts = async () => {
const keys = await idb.keys();
const dictationKeys = keys.filter(key => key.startsWith(DB_PREFIX) && key !== DB_CONFIG_KEY);
const entries = await Promise.all(
dictationKeys.map(async (key) => {
const title = key.substring(DB_PREFIX.length);
const content = await idb.get(key);
return [title, content];
})
);
texts = Object.fromEntries(entries);
updateTextList();
};
// ** Level 3: Dependencies on Level 2 **
const speakNextWord = () => {
if (currentWordIndex < sourceWords.length) {
speakWord(stripPunctuation(sourceWords[currentWordIndex]));
}
};
const repeatCurrentWord = () => {
if (currentWordIndex < sourceWords.length) {
const speed = 1.0 - (0.2 * tabKeyPressCount++);
speakImmediately(stripPunctuation(sourceWords[currentWordIndex]), Math.max(0.2, speed));
}
};
const speakText = () => {
if (!sourceWords.length || !('speechSynthesis' in window)) return;
const fullText = sourceWords.join(' ');
speakImmediately(fullText, parseFloat(speedSlider.value));
};
const flashIncorrect = () => {
writingInput.classList.add('input-incorrect-flash');
setTimeout(() => {
writingInput.classList.remove('input-incorrect-flash');
}, 300);
};
const handleContinuousInput = () => {
const sourceSpans = Array.from(textDisplay.querySelectorAll('.word-span'));
const inputValue = writingInput.value;
const inputTokens = inputValue.match(/\S+\s*/g) || [];
const isHiddenMode = hideTextCheckbox.checked;
let lastCorrectIndex = -1;
// Part 1: Determine correctness of each word
sourceSpans.forEach(span => span.classList.remove('correct', 'incorrect', 'current'));
sourceSpans.forEach((span, index) => {
if (index < inputTokens.length) {
const token = inputTokens[index];
const inputWord = token.trim();
const wordIsFinishedBySpace = token.length > inputWord.length;
const isLastToken = index === inputTokens.length - 1;
const normalizedSource = normalizeWord(sourceWords[index]);
const normalizedInput = normalizeWord(inputWord);
let isIncorrect = false;
const isWordInteractionComplete = !isLastToken || wordIsFinishedBySpace;
if (isWordInteractionComplete) {
if (normalizedInput !== normalizedSource) isIncorrect = true;
} else {
if (!normalizedSource.startsWith(normalizedInput)) isIncorrect = true;
}
if (isIncorrect) {
if (waitForSpaceCheckbox.checked && !isWordInteractionComplete) {
flashIncorrect();
} else {
span.classList.add('incorrect');
if (isHiddenMode) {
const diffHtml = createDiffHtml(inputWord, sourceWords[index]);
span.innerHTML = ''; // Clear the black boxes
span.appendChild(diffHtml);
}
}
} else {
if (isWordInteractionComplete) {
span.classList.add('correct');
if (isHiddenMode) {
// If it was previously incorrect (showing a diff) or just completed,
// reveal the correct word permanently.
span.textContent = sourceWords[index];
}
lastCorrectIndex = index;
}
}
} else if (isHiddenMode) {
// For words not yet typed in hidden mode, ensure they are black boxes
span.textContent = obscureWord(sourceWords[index]);
}
});
// Part 2: Update current word index, handle audio, and save session
const newWordIndex = lastCorrectIndex + 1;
const hasAdvanced = newWordIndex > currentWordIndex;
currentWordIndex = newWordIndex;
if (hasAdvanced) {
if (readOnCorrectCheckbox.checked && currentWordIndex > 0) {
speakWord(stripPunctuation(sourceWords[currentWordIndex - 1]));
}
if (readNextCheckbox.checked) {
speakNextWord();
}
// Save session only when a word has been successfully entered
saveSession();
}
if (currentWordIndex < sourceWords.length) {
sourceSpans[currentWordIndex].classList.add('current');
}
if (writingInput.value.trim() === sourceWords.join(' ')) {
showNotification('Dictation complete!', 5000);
sessionStorage.removeItem(SESSION_STORAGE_KEY);
}
};
// ** Level 4: Dependencies on Level 3 **
const renderText = () => {
if (!sourceWords.length) {
textDisplay.innerHTML = '';
return;
}
const isHidden = hideTextCheckbox.checked;
// Render words, obscuring if in hidden mode.
const wordsToRender = isHidden ? sourceWords.map(obscureWord) : sourceWords;
textDisplay.innerHTML = wordsToRender.map(word => `<span class="word-span">${word}</span>`).join(' ');
};
const displayText = async (savedInput = '') => {
const title = textSelect.value;
if (title && texts[title]) {
sourceWords = texts[title].split(' ').filter(w => w.length > 0);
currentWordIndex = 0;
tabKeyPressCount = 0;
writingInput.value = savedInput;
renderText(); // Use the helper to render the initial text display
const lang = await detectLanguage(texts[title]);
textDisplay.lang = lang;
writingInput.lang = lang;
handleContinuousInput();
if (!savedInput) {
speakNextWord();
}
}
};
const saveText = async () => {
const newTitle = textTitleInput.value.trim();
const content = textContentTextarea.value.trim();
if (newTitle && content) {
if (originalTitle && originalTitle !== newTitle) {
await idb.del(`${DB_PREFIX}${originalTitle}`);
}
await idb.set(`${DB_PREFIX}${newTitle}`, content);
await loadTexts();
textSelect.value = newTitle;
displayText();
}
};
const deleteText = async () => {
const title = textSelect.value;
if (title && confirm(`Are you sure you want to delete "${title}"?`)) {
await idb.del(`${DB_PREFIX}${title}`);
textDisplay.innerHTML = '';
writingInput.value = '';
clearEditor();
await loadTexts();
}
};
const toggleHideText = () => {
renderText(); // Re-render the text display based on the new checkbox state
handleContinuousInput(); // Re-apply styles and reveal any existing errors
if (hideTextCheckbox.checked) {
writingInput.focus();
speakNextWord();
}
};
const applyConfig = (config) => {
const classesToRemove = (element) => {
const toRemove = [];
element.classList.forEach(c => {
if (c.startsWith('font-size-') || c.startsWith('font-family-')) {
toRemove.push(c);
}
});
return toRemove;
};
classesToRemove(writingInput).forEach(c => writingInput.classList.remove(c));
classesToRemove(textDisplay).forEach(c => textDisplay.classList.remove(c));
// Add the new classes
if (config.fontSize) {
writingInput.classList.add(config.fontSize);
textDisplay.classList.add(config.fontSize);
}
if (config.fontFamily) {
writingInput.classList.add(config.fontFamily);
textDisplay.classList.add(config.fontFamily);
}
};
const saveConfig = async () => {
const config = {
fontSize: fontSizeSelect.value,
fontFamily: fontFamilySelect.value,
hideText: hideTextCheckbox.checked,
speed: speedSlider.value,
readNext: readNextCheckbox.checked,
readOnCorrect: readOnCorrectCheckbox.checked,
ignoreAccents: ignoreAccentsCheckbox.checked,
ignorePunctuation: ignorePunctuationCheckbox.checked,
ignoreCase: ignoreCaseCheckbox.checked,
waitForSpace: waitForSpaceCheckbox.checked,
};
await idb.set(DB_CONFIG_KEY, config);
};
const loadConfig = async () => {
const config = await idb.get(DB_CONFIG_KEY) || {};
fontSizeSelect.value = config.fontSize || 'font-size-28';
fontFamilySelect.value = config.fontFamily || 'font-family-arial';
speedSlider.value = config.speed || '1';
hideTextCheckbox.checked = config.hideText || false;
readNextCheckbox.checked = config.readNext !== false;
readOnCorrectCheckbox.checked = config.readOnCorrect !== false;
ignoreAccentsCheckbox.checked = config.ignoreAccents !== false;
ignorePunctuationCheckbox.checked = config.ignorePunctuation !== false;
ignoreCaseCheckbox.checked = config.ignoreCase !== false;
waitForSpaceCheckbox.checked = config.waitForSpace !== false;
applyConfig({ fontSize: fontSizeSelect.value, fontFamily: fontFamilySelect.value });
toggleHideText();
};
const handleConfigChange = () => {
applyConfig({ fontSize: fontSizeSelect.value, fontFamily: fontFamilySelect.value });
saveConfig();
};
const resetSettings = () => {
// Set UI elements to default values
fontSizeSelect.value = 'font-size-28';
fontFamilySelect.value = 'font-family-arial';
speedSlider.value = '1';
hideTextCheckbox.checked = false;
readNextCheckbox.checked = true;
readOnCorrectCheckbox.checked = true;
ignoreAccentsCheckbox.checked = true;
ignorePunctuationCheckbox.checked = true;
ignoreCaseCheckbox.checked = true;
// Apply visual changes
applyConfig({
fontSize: fontSizeSelect.value,
fontFamily: fontFamilySelect.value,
});
toggleHideText();
// Save the new default config and notify the user
saveConfig();
showNotification('Display settings have been reset.');
};
// --- Event Listeners & Initial Load ---
resetSettingsBtn.addEventListener('click', resetSettings);
newTextBtn.addEventListener('click', clearEditor);
deleteTextBtn.addEventListener('click', deleteText);
saveTextBtn.addEventListener('click', saveText);
textSelect.addEventListener('change', () => {
const title = textSelect.value;
if (title && texts[title]) {
textTitleInput.value = title;
textContentTextarea.value = texts[title];
originalTitle = title;
displayText();
}
});
writingInput.addEventListener('input', handleContinuousInput);
repeatWordBtn.addEventListener('click', repeatCurrentWord);
textDisplay.addEventListener('click', (event) => {
if (event.target.tagName === 'SPAN') {
const word = event.target.textContent;
const sourceLang = textDisplay.lang || 'auto';
const targetLang = 'en';
const url = `https://translate.google.com/?sl=${sourceLang}&tl=${targetLang}&text=${encodeURIComponent(word)}&op=translate`;
window.open(url, '_blank');
}
});
fontSizeSelect.addEventListener('change', handleConfigChange);
fontFamilySelect.addEventListener('change', handleConfigChange);
speedSlider.addEventListener('input', saveConfig);
hideTextCheckbox.addEventListener('change', () => {
toggleHideText();
saveConfig();
});
readNextCheckbox.addEventListener('change', saveConfig);
readOnCorrectCheckbox.addEventListener('change', saveConfig);
ignoreAccentsCheckbox.addEventListener('change', saveConfig);
ignorePunctuationCheckbox.addEventListener('change', saveConfig);
ignoreCaseCheckbox.addEventListener('change', saveConfig);
waitForSpaceCheckbox.addEventListener('change', saveConfig);
writingInput.addEventListener('keydown', (event) => {
if (event.key === 'Tab') {
event.preventDefault();
repeatCurrentWord();
}
});
const toggleHiddenTextMode = () => {
hideTextCheckbox.checked = !hideTextCheckbox.checked;
toggleHideText();
saveConfig();
};
document.addEventListener('keydown', (event) => {
if (event.ctrlKey && event.key.toLowerCase() === 's') {
event.preventDefault();
speakText();
} else if (event.key === 'Escape') {
event.preventDefault();
toggleHiddenTextMode();
}
});
toggleHiddenBtn.addEventListener('click', toggleHiddenTextMode);
menuToggleBtn.addEventListener('click', () => {
configPanel.classList.toggle('config-panel-visible');
});
writingInput.addEventListener('focus', () => {
configPanel.classList.remove('config-panel-visible');
});
const initializeApp = async () => {
await loadConfig();
await loadTexts();
// Restore the previous session if it exists
const savedSession = loadSession();
if (savedSession && texts[savedSession.title]) {
textSelect.value = savedSession.title;
// Directly call displayText with the saved user input to restore the state
await displayText(savedSession.userInput);
}
};
initializeApp();
});