// ==UserScript== // @name Hebrew Live Dictation - הקלדה קולית חיה // @namespace https://local.example/hebrew-live-dictation // @version 0.4.0 // @description Hebrew voice typing with clickable controls inside modal dialogs and concise voice punctuation commands. // @match https://*/* // @match http://localhost/* // @match http://127.0.0.1/* // @run-at document-idle // @noframes // @grant none // ==/UserScript== (() => { 'use strict'; const SpeechRecognition = window.SpeechRecognition || window.webkitSpeechRecognition; if (!SpeechRecognition || document.getElementById('hebrew-voice-dictation')) return; let target = null; let recognition = null; let wantsToListen = false; let isRunning = false; let isApplyingText = false; let finalizedIndex = 0; let draft = null; // {kind, element, start, end, range, text} let restartTimer = null; let overlapFinalSpeech = ''; let overlapChecksRemaining = 0; let echoResultIndex = -1; // Isolate the floating controls from the site's CSS. const host = document.createElement('div'); host.id = 'hebrew-voice-dictation'; // Popover API puts the microphone in the browser's top layer, above ordinary // overlays and modal backdrops (unlike z-index alone). host.setAttribute('popover', 'manual'); host.style.cssText = 'all:initial;display:block;position:fixed;top:auto;left:auto;right:20px;bottom:20px;z-index:2147483647;margin:0;padding:0;border:0;background:transparent;overflow:visible;pointer-events:auto;'; const root = host.attachShadow({mode: 'open'}); root.innerHTML = `
`; document.documentElement.appendChild(host); try { if (typeof host.showPopover === 'function') host.showPopover(); } catch (_) { /* Keep the high-z-index fallback if Popover API is unavailable. */ } const button = root.querySelector('button'); const tip = root.querySelector('.tip'); let infoTimer = null; function showInfo(message, hideAfter = 3500) { tip.textContent = message; tip.classList.add('show'); clearTimeout(infoTimer); if (hideAfter) infoTimer = setTimeout(() => tip.classList.remove('show'), hideAfter); } function updateButton() { button.classList.toggle('on', wantsToListen); button.setAttribute('aria-label', wantsToListen ? 'הפסק הכתבה קולית' : 'התחל הכתבה קולית'); button.textContent = wantsToListen ? '⏹' : '🎙️'; } function isTextField(el) { if (!el || !(el instanceof HTMLElement)) return false; if (el instanceof HTMLTextAreaElement) return !el.disabled && !el.readOnly; if (el instanceof HTMLInputElement) { return ['text', 'search', 'email', 'url', 'tel'].includes(el.type) && !el.disabled && !el.readOnly; } if (el.getAttribute('role') === 'textbox') { return el.getAttribute('aria-disabled') !== 'true' && el.getAttribute('aria-readonly') !== 'true'; } return el.isContentEditable; } function findEditor(from) { if (!(from instanceof Element)) return null; const field = from.closest('textarea,input,[contenteditable=""],[contenteditable="true"],[role="textbox"]'); if (!field || !isTextField(field)) return null; // For nested contenteditables, find the nearest editable root. if (field.isContentEditable && !(field instanceof HTMLInputElement) && !(field instanceof HTMLTextAreaElement)) { let current = field; while (current.parentElement && current.parentElement.isContentEditable) current = current.parentElement; return current; } return field; } // Search the composed event path as well as event.target. This also detects // inputs inside a site's open Shadow DOM. function findEditorFromEvent(event) { const path = typeof event.composedPath === 'function' ? event.composedPath() : [event.target]; for (const node of path) { const found = findEditor(node); if (found) return found; } return findEditor(event.target); } let raiseTimer = null; function containingModal(element) { // Native modal makes everything outside it inert. Merely displaying // our popover above the dialog does NOT make its button clickable. Place the // controls inside the modal's DOM subtree so pointer events can reach it. for (let node = element; node;) { if (node instanceof Element && ( (node.matches('dialog[open]') && node.matches(':modal')) || node.matches('[aria-modal="true"]') )) return node; const parent = node.parentNode; node = parent instanceof ShadowRoot ? parent.host : parent; } return null; } function moveControlsIntoActiveModal(editor) { const destination = containingModal(editor) || document.documentElement; const changedParent = host.parentNode !== destination; try { if (changedParent && host.matches(':popover-open')) host.hidePopover(); if (changedParent) destination.appendChild(host); // After a dialog opens, the microphone must also be in front of it in // the top layer. Hide/show updates the stacking order without extra UI. if (typeof host.showPopover === 'function') { if (host.matches(':popover-open')) host.hidePopover(); host.showPopover(); } } catch (_) { /* Keep the button usable even without Popover API. */ } } function raiseMicrophoneAboveDialog(editor) { clearTimeout(raiseTimer); raiseTimer = setTimeout(() => moveControlsIntoActiveModal(editor), 0); } // When a modal closes, return the controls to the page. Watching the current // modal (rather than every DOM mutation on the page) avoids disrupting sites. const modalObserver = new MutationObserver(() => { const parent = host.parentElement; if (!parent || parent === document.documentElement) return; if (!parent.isConnected || (parent.matches('dialog') && (!parent.open || !parent.matches(':modal'))) || (parent.hasAttribute('aria-modal') && parent.getAttribute('aria-modal') !== 'true')) { const editor = target?.isConnected && containingModal(target) ? target : null; moveControlsIntoActiveModal(editor); } }); modalObserver.observe(document.documentElement, { subtree: true, childList: true, attributes: true, attributeFilter: ['open', 'aria-modal'] }); document.addEventListener('focusin', event => { const newTarget = findEditorFromEvent(event); if (newTarget && newTarget !== target && !host.contains(newTarget)) { draft = null; target = newTarget; } if (newTarget) raiseMicrophoneAboveDialog(newTarget); }, true); document.addEventListener('pointerdown', event => { const newTarget = findEditorFromEvent(event); if (newTarget && newTarget !== target) { draft = null; target = newTarget; } if (newTarget) raiseMicrophoneAboveDialog(newTarget); }, true); // Do not move focus away from the editor when clicking the microphone. button.addEventListener('pointerdown', event => event.preventDefault()); button.addEventListener('click', toggle); document.addEventListener('keydown', event => { if (event.altKey && event.shiftKey && event.code === 'KeyM' && !event.ctrlKey && !event.metaKey) { event.preventDefault(); toggle(); } }, true); function getDeepActiveElement() { let active = document.activeElement; while (active?.shadowRoot?.activeElement) active = active.shadowRoot.activeElement; return active; } function findTarget() { if (target?.isConnected && isTextField(target)) return target; const active = findEditor(getDeepActiveElement()); if (active) target = active; return active; } // We use the native value setter so React-controlled inputs also receive an input event. function setPlainValue(element, value) { const proto = element instanceof HTMLTextAreaElement ? HTMLTextAreaElement.prototype : HTMLInputElement.prototype; const setter = Object.getOwnPropertyDescriptor(proto, 'value')?.set; if (setter) setter.call(element, value); else element.value = value; element.dispatchEvent(new InputEvent('input', { bubbles: true, composed: true, inputType: 'insertText', data: null })); } function textOffsetToPoint(element, offset) { const walker = document.createTreeWalker(element, NodeFilter.SHOW_TEXT); let last = null; while (walker.nextNode()) { const node = walker.currentNode; last = node; if (offset <= node.textContent.length) return {node, offset}; offset -= node.textContent.length; } return last ? {node: last, offset: last.textContent.length} : null; } // Return a live Range around previously inserted provisional text. // Some editors (React, ProseMirror, etc.) rebuild their DOM between interim // updates. If they do, recover the range by its content rather than blindly // appending the same first word a second time. function locateDraftRange(element, previousText) { if (!previousText) return null; const existing = draft?.range; try { if (existing && existing.toString() === previousText && element.contains(existing.startContainer) && element.contains(existing.endContainer)) { return existing; } } catch (_) {} const fullText = element.textContent || ''; const offset = fullText.lastIndexOf(previousText); if (offset < 0) return null; const from = textOffsetToPoint(element, offset); const to = textOffsetToPoint(element, offset + previousText.length); if (!from || !to) return null; const r = document.createRange(); r.setStart(from.node, from.offset); r.setEnd(to.node, to.offset); return r.toString() === previousText ? r : null; } function getInsertedRange(element, insertedLength) { const selection = window.getSelection(); if (!selection || !selection.rangeCount) return null; const cursor = selection.getRangeAt(0); if (!element.contains(cursor.endContainer)) return null; const before = document.createRange(); before.selectNodeContents(element); before.setEnd(cursor.endContainer, cursor.endOffset); const endOffset = before.cloneContents().textContent.length; const start = textOffsetToPoint(element, Math.max(0, endOffset - insertedLength)); const end = textOffsetToPoint(element, endOffset); if (!start || !end) return null; const range = document.createRange(); range.setStart(start.node, start.offset); range.setEnd(end.node, end.offset); return range; } function previousCharacter() { if (!target) return ''; if (target instanceof HTMLInputElement || target instanceof HTMLTextAreaElement) { const offset = draft?.start ?? target.selectionStart ?? 0; return target.value.slice(Math.max(0, offset - 1), offset); } const selection = window.getSelection(); const anchor = draft?.range || (selection?.rangeCount ? selection.getRangeAt(0) : null); if (!anchor || !target.contains(anchor.startContainer)) return ''; const prefix = document.createRange(); prefix.selectNodeContents(target); prefix.setEnd(anchor.startContainer, anchor.startOffset); return prefix.toString().slice(-1); } // When a punctuation command is its own recognition segment, remove the // trailing space inserted by the preceding segment ("שלום " + "?" -> "שלום?"). function extendRangeOverWhitespace(element, range) { const leading = document.createRange(); leading.selectNodeContents(element); leading.setEnd(range.startContainer, range.startOffset); const before = leading.toString(); const whitespace = before.match(/[ \t\u00a0]+$/u)?.[0] || ''; if (!whitespace) return range; const point = textOffsetToPoint(element, before.length - whitespace.length); if (point) range.setStart(point.node, point.offset); return range; } // Voice commands are interpreted only when the recognizer marks the phrase // final. Interim results remain ordinary live text until Google settles on // the spoken words. That also avoids repeated DOM line breaks while speaking. const VOICE_COMMANDS = [ {words: ['פסקה', 'חדשה'], value: '\n\n'}, {words: ['שורה', 'חדשה'], value: '\n'}, {words: ['רד', 'שורה'], value: '\n'}, {words: ['ירידת', 'שורה'], value: '\n'}, {words: ['סימן', 'שאלה'], value: '?'}, {words: ['סימן', 'קריאה'], value: '!'}, {words: ['סימן', 'נקודה'], value: '.'}, {words: ['נקודה', 'פסיק'], value: ';'}, {words: ['פתח', 'סוגריים'], value: '('}, {words: ['סגור', 'סוגריים'], value: ')'}, {words: ['נקודתיים'], value: ':'}, {words: ['נקודה'], value: '.'}, {words: ['פסיק'], value: ','}, {words: ['מקף'], value: ' – '}, ]; function spokenWordsToText(raw) { const words = raw.trim().split(/\s+/u).filter(Boolean); let output = ''; for (let i = 0; i < words.length;) { const normalized = word => word.replace(/^[.,!?;:״"'“”]+|[.,!?;:״"'“”]+$/gu, ''); const command = VOICE_COMMANDS.find(({words: phrase}) => phrase.every((part, index) => normalized(words[i + index] || '') === part)); if (command) { const value = command.value; if (value.startsWith('\n')) { output = output.replace(/[ \t\u00a0]+$/u, '') + value; } else if (/^[.,!?;:)]$/u.test(value)) { output = output.replace(/[ \t\u00a0]+$/u, '') + value; } else if (value === '(') { output += output && !/[\s(]$/u.test(output) ? ' (' : '('; } else { output += output && !/\s$/u.test(output) ? ' – ' : '– '; } i += command.words.length; } else { const word = words[i++]; const addSpace = output && !/[\s(]$/u.test(output) && !/^[.,!?;:)]/u.test(word); output += (addSpace ? ' ' : '') + word; } } return output; } function removeFinalEcho(interim, previousFinal) { const raw = interim.trim(); const oldWords = previousFinal.trim().split(/\s+/u).filter(Boolean); const newWords = raw.split(/\s+/u).filter(Boolean); const norm = s => s.replace(/[.,!?;:]+$/u, ''); for (let n = Math.min(oldWords.length, newWords.length, 12); n > 0; n--) { const suffix = oldWords.slice(-n).map(norm); const prefix = newWords.slice(0, n).map(norm); if (suffix.every((w, i) => w === prefix[i])) return newWords.slice(n).join(' '); } return raw; } function setDraft(raw, final = false) { if (!target?.isConnected) return; const content = final ? spokenWordsToText(raw) : raw.trim(); if (!content) return; if (!draft || draft.element !== target) { const plain = target instanceof HTMLInputElement || target instanceof HTMLTextAreaElement; draft = plain ? {kind: 'plain', element: target, start: target.selectionStart ?? 0, end: target.selectionEnd ?? 0, text: ''} : {kind: 'rich', element: target, range: null, text: ''}; } // Keep single-line input elements single-line, and leave textarea/editor // line breaks intact. Punctuation attaches directly to the preceding word. const plainInput = target instanceof HTMLInputElement; const rendered = plainInput ? content.replace(/\n+/g, ' ') : content; const before = previousCharacter(); const leadingSeparator = final && /^[.,!?;:\n)]/u.test(rendered); const prefix = before && !/\s/u.test(before) && !/^[.,!?;:\n)]/u.test(rendered) ? ' ' : ''; const replacement = prefix + rendered + (final && !/[\n\s]$/u.test(rendered) ? ' ' : ''); if (replacement === draft.text) { if (final) draft = null; return; } isApplyingText = true; try { if (draft.kind === 'plain') { const current = target.value; if (draft.text && current.slice(draft.start, draft.end) !== draft.text) { const possible = current.lastIndexOf(draft.text); if (possible >= 0) { draft.start = possible; draft.end = possible + draft.text.length; } else { draft = null; return; } // Never append a duplicated live phrase. } let beforeDraft = current.slice(0, draft.start); if (leadingSeparator) { beforeDraft = beforeDraft.replace(/[ \t\u00a0]+$/u, ''); draft.start = beforeDraft.length; } const next = beforeDraft + replacement + current.slice(draft.end); setPlainValue(target, next); draft.end = draft.start + replacement.length; target.setSelectionRange(draft.end, draft.end); } else { target.focus(); let replaceRange = null; if (draft.text) { replaceRange = locateDraftRange(target, draft.text); if (!replaceRange) { // An editor may have already committed the interim update itself. // Avoid a second insertion if its range cannot be recovered. if (final) draft = null; return; } } else if (leadingSeparator) { const selection = window.getSelection(); if (selection?.rangeCount && target.contains(selection.anchorNode)) { replaceRange = selection.getRangeAt(0).cloneRange(); } } if (replaceRange) { if (leadingSeparator) extendRangeOverWhitespace(target, replaceRange); const selection = window.getSelection(); selection.removeAllRanges(); selection.addRange(replaceRange); } if (!document.execCommand('insertText', false, replacement)) { showInfo('האתר הזה חוסם הקלדה אוטומטית בשדה שנבחר', 4500); return; } // A final can contain line breaks. There will be no further replacement // of that segment, so we intentionally do not track a range for it. draft.range = final ? null : getInsertedRange(target, replacement.length); } draft.text = replacement; } finally { isApplyingText = false; } if (final) draft = null; } function handleResults(event) { if (!target) return; let latestInterim = ''; for (let index = finalizedIndex; index < event.results.length; index++) { const result = event.results[index]; const transcript = result[0]?.transcript || ''; if (result.isFinal) { // If this result's interim already echoed an earlier final phrase, // remove the same echo from its final version as well. const finalText = index === echoResultIndex ? removeFinalEcho(transcript, overlapFinalSpeech) : transcript; if (finalText.trim()) setDraft(finalText, true); finalizedIndex = index + 1; overlapFinalSpeech = finalText.trim() || overlapFinalSpeech; overlapChecksRemaining = 3; if (index === echoResultIndex) echoResultIndex = -1; } else { latestInterim += transcript; } } if (latestInterim.trim()) { // Web Speech may emit a finalized first word and also repeat that word // as the prefix of the next interim. Remove only this near-boundary echo. const cleaned = overlapChecksRemaining > 0 ? removeFinalEcho(latestInterim, overlapFinalSpeech) : latestInterim.trim(); if (cleaned !== latestInterim.trim()) { echoResultIndex = event.results.length - 1; } if (overlapChecksRemaining > 0) overlapChecksRemaining--; if (cleaned.trim()) setDraft(cleaned, false); } } function stop() { wantsToListen = false; clearTimeout(restartTimer); updateButton(); tip.classList.remove('show'); try { recognition?.stop(); } catch (_) {} } function startRecognition() { if (!wantsToListen || isRunning) return; recognition = new SpeechRecognition(); recognition.lang = 'he-IL'; recognition.continuous = true; recognition.interimResults = true; recognition.maxAlternatives = 1; finalizedIndex = 0; overlapChecksRemaining = 0; echoResultIndex = -1; recognition.onstart = () => { isRunning = true; updateButton(); tip.classList.remove('show'); }; recognition.onresult = handleResults; recognition.onerror = (event) => { if (['not-allowed', 'service-not-allowed', 'audio-capture', 'network', 'language-not-supported'].includes(event.error)) { wantsToListen = false; updateButton(); showInfo('שגיאת מיקרופון/זיהוי: ' + event.error, 6500); } }; recognition.onend = () => { isRunning = false; // Do not delete interim text: Chrome can stop without sending a final event. draft = null; if (wantsToListen) restartTimer = setTimeout(startRecognition, 500); else updateButton(); }; try { recognition.start(); } catch (error) { wantsToListen = false; updateButton(); showInfo('לא ניתן להתחיל זיהוי קול: ' + error.message, 6000); } } function toggle() { if (wantsToListen) return stop(); if (!findTarget()) { showInfo('קודם לחץ על שדה כתיבה, ואז הפעל את המיקרופון', 5000); return; } wantsToListen = true; draft = null; overlapFinalSpeech = ''; overlapChecksRemaining = 0; echoResultIndex = -1; updateButton(); startRecognition(); } })();