Thomas-PEYROT/japanese-webtranslate / content / content.js
/**
* Japanese Web Translate — moteur furigana.
*
* Parcourt les nœuds texte de la page, segmente le japonais avec kuromoji
* et enveloppe les tokens contenant des kanji dans des <ruby> marqués
* de la classe "jwt-ruby". Le tooltip (tooltip.js) s'appuie sur les
* attributs data-jwt-w (forme de surface) et data-jwt-b (forme de base).
*
* kuromoji est chargé via window.kuromoji (voir initTokenizer).
*/
const JWT = (() => {
const RUBY_CLASS = "jwt-ruby";
const KANJI_RE = /[一-龯々〆ヵヶ]/;
const JAPANESE_RE = /[一-龯-ゟ゠-ヿ]/;
// Balises dont le contenu ne doit jamais être modifié
const SKIP_TAGS = new Set([
"SCRIPT", "STYLE", "TEXTAREA", "INPUT", "SELECT", "OPTION",
"CODE", "PRE", "KBD", "SAMP", "RUBY", "RT", "RP", "NOSCRIPT",
"IFRAME", "CANVAS", "SVG", "MATH",
]);
let tokenizer = null; // tokenizer kuromoji (lazy)
let tokenizerPromise = null; // promesse d'initialisation en cours
let observer = null;
let enabled = false;
/** Convertit une lecture katakana kuromoji en hiragana. */
function toHiragana(text) {
return text.replace(/[ァ-ヶ]/g, (c) =>
String.fromCharCode(c.charCodeAt(0) - 0x60)
);
}
function initTokenizer() {
if (tokenizerPromise) return tokenizerPromise;
const dicPath = chrome.runtime.getURL("vendor/kuromoji/dict/");
tokenizerPromise = new Promise((resolve, reject) => {
// window.kuromoji explicitement : dans Firefox, le global du sandbox des
// content scripts n'est pas window, l'identifiant nu `kuromoji` n'existe pas.
const kuromojiGlobal = window.kuromoji;
if (!kuromojiGlobal) {
reject(new Error("kuromoji is not loaded"));
return;
}
kuromojiGlobal.builder({ dicPath }).build((err, tk) => {
if (err) reject(err);
else {
tokenizer = tk;
resolve(tk);
}
});
});
return tokenizerPromise;
}
/** Renvoie true si le nœud texte est dans un contexte à ignorer. */
function isSkippable(node) {
for (let el = node.parentElement; el; el = el.parentElement) {
if (SKIP_TAGS.has(el.tagName)) return true;
if (el.isContentEditable) return true;
if (el.classList && el.classList.contains(RUBY_CLASS)) return true;
}
return false;
}
/** Collecte les nœuds texte japonais non traités sous root. */
function collectTextNodes(root) {
const nodes = [];
const walker = document.createTreeWalker(
root,
NodeFilter.SHOW_TEXT,
{
acceptNode(node) {
if (!node.nodeValue || !JAPANESE_RE.test(node.nodeValue)) {
return NodeFilter.FILTER_REJECT;
}
return isSkippable(node)
? NodeFilter.FILTER_REJECT
: NodeFilter.FILTER_ACCEPT;
},
}
);
let node;
while ((node = walker.nextNode())) nodes.push(node);
return nodes;
}
/**
* Transforme un nœud texte en fragment mêlant texte brut et <ruby>.
* Ne fait rien si aucun token ne nécessite de furigana.
*/
function processTextNode(textNode) {
const text = textNode.nodeValue;
if (!KANJI_RE.test(text)) return; // furigana uniquement sur les kanji
const tokens = tokenizer.tokenize(text);
const fragment = document.createDocumentFragment();
let changed = false;
for (const token of tokens) {
const surface = token.surface_form;
const hasKanji = KANJI_RE.test(surface);
const reading = token.reading;
if (hasKanji && reading && reading !== "*" && toHiragana(reading) !== surface) {
const ruby = document.createElement("ruby");
ruby.className = RUBY_CLASS;
ruby.dataset.jwtW = surface;
const basic = token.basic_form;
if (basic && basic !== "*" && basic !== surface) {
ruby.dataset.jwtB = basic;
}
ruby.appendChild(document.createTextNode(surface));
const rt = document.createElement("rt");
rt.textContent = toHiragana(reading);
ruby.appendChild(rt);
fragment.appendChild(ruby);
changed = true;
} else {
fragment.appendChild(document.createTextNode(surface));
}
}
if (changed && textNode.parentNode) {
textNode.parentNode.replaceChild(fragment, textNode);
}
}
/** Traite une liste de nœuds par petits lots pour ne pas geler la page. */
function processNodesBatched(nodes, done) {
const BATCH = 50;
let i = 0;
function step() {
if (!enabled) return; // désactivé entre-temps
const end = Math.min(i + BATCH, nodes.length);
for (; i < end; i++) {
try {
processTextNode(nodes[i]);
} catch (e) {
console.warn("[JWT] nœud ignoré :", e);
}
}
if (i < nodes.length) {
setTimeout(step, 0);
} else if (done) {
done();
}
}
step();
}
function processRoot(root) {
const nodes = collectTextNodes(root);
if (nodes.length > 0) processNodesBatched(nodes);
}
function startObserver() {
if (observer) return;
let pending = new Set();
let scheduled = false;
observer = new MutationObserver((mutations) => {
for (const mutation of mutations) {
for (const added of mutation.addedNodes) {
if (added.nodeType !== Node.ELEMENT_NODE) continue;
// Ignore nos propres insertions
if (added.classList && added.classList.contains(RUBY_CLASS)) continue;
pending.add(added);
}
}
if (!scheduled && pending.size > 0) {
scheduled = true;
setTimeout(() => {
const batch = [...pending];
pending = new Set();
scheduled = false;
if (enabled) {
for (const el of batch) {
if (el.isConnected) processRoot(el);
}
}
}, 200);
}
});
observer.observe(document.body, { childList: true, subtree: true });
}
function stopObserver() {
if (observer) {
observer.disconnect();
observer = null;
}
}
/** Retire tous les <ruby> insérés et restaure le texte original. */
function removeFurigana() {
stopObserver();
for (const ruby of document.querySelectorAll(`ruby.${RUBY_CLASS}`)) {
const original = ruby.dataset.jwtW || ruby.firstChild.textContent;
ruby.parentNode.replaceChild(document.createTextNode(original), ruby);
}
// Fusionne les nœuds texte adjacents restaurés
document.body.normalize();
}
async function enable() {
if (enabled || !document.body) return;
enabled = true;
try {
await initTokenizer();
} catch (e) {
enabled = false;
console.error("[JWT] échec du chargement de kuromoji :", e);
return;
}
if (!enabled) return; // désactivé pendant le chargement
processRoot(document.body);
startObserver();
}
function disable() {
enabled = false;
removeFurigana();
}
// Messages du popup
chrome.runtime.onMessage.addListener((msg) => {
if (msg.type === "jwt-toggle") {
if (msg.enabled) enable();
else disable();
}
});
// État persistant : traite automatiquement si le domaine est activé
chrome.storage.sync.get({ jwtDomains: {} }, ({ jwtDomains }) => {
if (location.hostname && jwtDomains[location.hostname]) {
if (document.body) enable();
else document.addEventListener("DOMContentLoaded", enable, { once: true });
}
});
return { enable, disable };
})();
void JWT;