// ==UserScript==
// @name Hebrew Live Dictation - הקלדה קולית חיה
// @namespace https://local.example/hebrew-live-dictation
// @version 0.1.0
// @description Live Hebrew voice typing inside input, textarea and contenteditable fields using Chrome SpeechRecognition.
// @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;
// Isolate the floating controls from the site's CSS.
const host = document.createElement('div');
host.id = 'hebrew-voice-dictation';
host.style.cssText = 'all:initial;position:fixed;bottom:20px;right:20px;z-index:2147483647;';
const root = host.attachShadow({mode: 'open'});
root.innerHTML = `
`;
document.documentElement.appendChild(host);
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;
}
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;
}
document.addEventListener('focusin', event => {
const newTarget = findEditor(event.target);
if (newTarget && newTarget !== target && !host.contains(newTarget)) {
draft = null;
target = newTarget;
}
}, true);
document.addEventListener('pointerdown', event => {
const newTarget = findEditor(event.target);
if (newTarget && newTarget !== target) {
draft = null;
target = 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 findTarget() {
if (target?.isConnected && isTextField(target)) return target;
const active = findEditor(document.activeElement);
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;
}
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);
}
function setDraft(raw, final = false) {
if (!target?.isConnected) return;
const content = 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: ''};
}
// Insert a single space between speech segments and existing text when needed.
const before = previousCharacter();
const prefix = before && !/\s/.test(before) && !/^[.,!?;:،.!?]/.test(content) ? ' ' : '';
// Prefix is already part of the previous live draft; avoid stacking spaces.
const value = draft.text ? draft.text.match(/^\s/)?.[0] || '' : prefix;
const replacement = value + content + (final ? ' ' : '');
if (replacement === draft.text) return;
isApplyingText = true;
try {
if (draft.kind === 'plain') {
const current = target.value;
const next = current.slice(0, draft.start) + replacement + current.slice(draft.end);
setPlainValue(target, next);
draft.end = draft.start + replacement.length;
target.setSelectionRange(draft.end, draft.end);
} else {
target.focus();
if (draft.range) {
const selection = window.getSelection();
selection.removeAllRanges();
selection.addRange(draft.range);
}
if (!document.execCommand('insertText', false, replacement)) {
// Some editors block browser insertion; do not insert duplicate interim text.
showInfo('האתר הזה חוסם הקלדה אוטומטית בשדה שנבחר', 4500);
return;
}
draft.range = 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) {
setDraft(transcript, true);
finalizedIndex = index + 1;
} else {
latestInterim += transcript;
}
}
if (latestInterim.trim()) setDraft(latestInterim, false);
}
function stop() {
wantsToListen = false;
clearTimeout(restartTimer);
updateButton();
showInfo('ההכתבה הופסקה');
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;
recognition.onstart = () => {
isRunning = true;
updateButton();
showInfo('מקשיב… אפשר לדבר בעברית', 1800);
};
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;
updateButton();
startRecognition();
}
})();