lingator
Version:
A plug-and-play npm package to auto-translate webpages using Google's Gemini AI.
47 lines (38 loc) • 1.48 kB
JavaScript
import { getAllTextNodes } from "./dom-scanner.js";
import { translateText } from "./translator.js";
let originalTexts = [];
/**
* Initialize Lingo with chosen languages
* @param {string[]} languages - List of supported languages (e.g. ['en', 'hi', 'mr'])
*/
export function initLingo(languages = []) {
try {
const nodes = getAllTextNodes();
originalTexts = nodes.map(node => node.nodeValue);
console.log("✅ Lingo initialized with languages:", languages);
// Optional: Developers can dynamically create buttons in their app
// Example usage:
// <button onclick="translatePage('hi')">Hindi</button>
} catch (error) {
console.error("❌ Failed to initialize Lingo:", error);
}
}
/**
* Translate the entire page to a specific language
* @param {string} lang - Target language code (e.g. 'hi', 'mr')
*/
export async function translatePage(lang) {
try {
const nodes = getAllTextNodes();
for (let i = 0; i < nodes.length; i++) {
const originalText = originalTexts[i];
if (!originalText || typeof originalText !== "string" || !originalText.trim()) continue;
const translated = await translateText(originalText, lang);
nodes[i].nodeValue = translated || originalText;
}
console.log(`✅ Page translated to: ${lang}`);
} catch (error) {
console.error("❌ Translation failed:", error);
alert("Translation failed. Please try again.");
}
}