File size: 24,496 Bytes
7d19761 | 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 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 | // ============================================================
// UmkhoAI Classroom Translator - Main Application Script
// ============================================================
// --- Language Data ---
const SA_LANGUAGES = [
{ code: 'af', name: 'Afrikaans', flag: 'πΏπ¦' },
{ code: 'en', name: 'English', flag: 'πΏπ¦' },
{ code: 'nr', name: 'isiNdebele', flag: 'πΏπ¦' },
{ code: 'xh', name: 'isiXhosa', flag: 'πΏπ¦' },
{ code: 'zu', name: 'isiZulu', flag: 'πΏπ¦' },
{ code: 'nso', name: 'Northern Sotho', flag: 'πΏπ¦' },
{ code: 'st', name: 'Sesotho', flag: 'πΏπ¦' },
{ code: 'tn', name: 'Setswana', flag: 'πΏπ¦' },
{ code: 'ss', name: 'siSwati', flag: 'πΏπ¦' },
{ code: 've', name: 'Tshivenda', flag: 'πΏπ¦' },
{ code: 'ts', name: 'Xitsonga', flag: 'πΏπ¦' },
];
// --- Simulated Translation Dictionary ---
// In production, this would call the UmkhoAI offline translation engine.
// For this demo, we use a phrase-based simulation with realistic output.
const TRANSLATIONS = {
af: {
greeting: 'Welkom by die les',
students: 'studente',
teacher: 'onderwyser',
classroom: 'klaskamer',
lesson: 'les',
question: 'vraag',
answer: 'antwoord',
read: 'lees',
write: 'skryf',
learn: 'leer',
numbers: 'getalle',
water: 'water',
sun: 'son',
earth: 'aarde',
plant: 'plant',
animal: 'dier',
history: 'geskiedenis',
freedom: 'vryheid',
democracy: 'demokrasie',
rights: 'regte',
today: 'vandag',
important: 'belangrik',
remember: 'onthou',
example: 'voorbeeld',
chapter: 'hoofstuk',
},
nr: {
greeting: 'Wamukelekile esifundweni',
students: 'abafundi',
teacher: 'uthisha',
classroom: 'ikilasi',
lesson: 'isifundo',
question: 'umbuzo',
answer: 'imphendulo',
read: 'funda',
write: 'bhala',
learn: 'funda',
numbers: 'amanombolo',
water: 'amanzi',
sun: 'ilanga',
earth: 'umhlaba',
plant: 'isitshalo',
animal: 'isilwane',
history: 'umlando',
freedom: 'inkululeko',
democracy: 'intando yeningi',
rights: 'amalungelo',
today: 'namuhla',
important: 'kubalulekile',
remember: 'khumbula',
example: 'isibonelo',
chapter: 'isahluko',
},
xh: {
greeting: 'Wamkelekile kwisifundo',
students: 'abafundi',
teacher: 'uthishabhala',
classroom: 'klasi',
lesson: 'isifundo',
question: 'umbuzo',
answer: 'impendulo',
read: 'funda',
write: 'bhala',
learn: 'funda',
numbers: 'amanani',
water: 'amanzi',
sun: 'ilanga',
earth: 'umhlaba',
plant: 'isityalo',
animal: 'isilwanyana',
history: 'imbali',
freedom: 'inkululeko',
democracy: 'intando yeningi',
rights: 'amalungelo',
today: 'namhlanje',
important: 'kubalulekile',
remember: 'khumbula',
example: 'umzekelo',
chapter: 'isahluko',
},
zu: {
greeting: 'Siyakwamukela esifundweni',
students: 'abafundi',
teacher: 'thisha',
classroom: 'klasini',
lesson: 'isifundo',
question: 'umbuzo',
answer: 'impendulo',
read: 'funda',
write: 'bhala',
learn: 'funda',
numbers: 'amanombolo',
water: 'amanzi',
sun: 'ilanga',
earth: 'umhlaba',
plant: 'isitshalo',
animal: 'isilwane',
history: 'umlando',
freedom: 'inkululeko',
democracy: 'intando yeningi',
rights: 'amalungelo',
today: 'namuhla',
important: 'kubalulekile',
remember: 'khumbula',
example: 'isibonelo',
chapter: 'isahluko',
},
nso: {
greeting: 'O amogela go ya lesong',
students: 'bahi',
teacher: 'morutΕ‘i',
classroom: 'klaseng',
lesson: 'leso',
question: 'potsiso',
answer: 'karabo',
read: 'bala',
write: 'ngwala',
learn: 'ithuta',
numbers: 'dinomoro',
water: 'metsi',
sun: 'letsatsi',
earth: 'lefase',
plant: 'setshedi',
animal: 'phoofolo',
history: 'histori',
freedom: 'tokologo',
democracy: 'demokerasi',
rights: 'ditokelo',
today: 'lehono',
important: 'kgolo',
remember: 'gopola',
example: 'mohlala',
chapter: 'kgaolo',
},
st: {
greeting: 'O amohetseng thutong',
students: 'baithuti',
teacher: 'moruti',
classroom: 'kalaseng',
lesson: 'thuto',
question: 'potso',
answer: 'karabo',
read: 'bala',
write: 'ngola',
learn: 'ithuta',
numbers: 'dinomoro',
water: 'metsi',
sun: 'letsatsi',
earth: 'lefatshe',
plant: 'setshedi',
animal: 'phoofolo',
history: 'histori',
freedom: 'tokoloho',
democracy: 'demokrasi',
rights: 'ditokelo',
today: 'kajeno',
important: 'kgolo',
remember: 'hopola',
example: 'mohlala',
chapter: 'kara',
},
tn: {
greeting: 'O amogela mo thutong',
students: 'baithuti',
teacher: 'morutabana',
classroom: 'kalaseng',
lesson: 'thuto',
question: 'potso',
answer: 'karabo',
read: 'bala',
write: 'kwala',
learn: 'ithuta',
numbers: 'dinomoro',
water: 'metsi',
sun: 'letsatsi',
earth: 'lefatshe',
plant: 'setshedi',
animal: 'phoofolo',
history: 'tiri',
freedom: 'boipuso',
democracy: 'demokerasi',
rights: 'ditokelo',
today: 'gompieno',
important: 'botlhokwa',
remember: 'gopola',
example: 'mohlala',
chapter: 'karolo',
},
ss: {
greeting: 'Siyakwemukela esifundweni',
students: 'bafundi',
teacher: 'thisha',
classroom: 'kilasini',
lesson: 'sifundo',
question: 'umbuzo',
answer: 'imphendvuto',
read: 'fundza',
write: 'bhala',
learn: 'funda',
numbers: 'emanombolo',
water: 'emanti',
sun: 'ilanga',
earth: 'umhlaba',
plant: 'sitjalo',
animal: 'silwane',
history: 'umlandvo',
freedom: 'inkululeko',
democracy: 'intandvo yeningi',
rights: 'emalungelo',
today: 'namuhla',
important: 'kubalulekile',
remember: 'khumbula',
example: 'sicatsetse',
chapter: 'sichatsi',
},
ve: {
greeting: 'Vhuedzedzani ha thendelo',
students: 'vhadidini',
teacher: 'mugudisi',
classroom: 'kilasini',
lesson: 'thendelo',
question: 'mubvumo',
answer: 'phendulo',
read: 'vhala',
write: 'nwala',
learn: 'guda',
numbers: 'mimanomboro',
water: 'madi',
sun: 'dzimu',
earth: 'shango',
plant: 'muri',
animal: 'phukha',
history: 'divhazwakale',
freedom: 'tshiphiri',
democracy: 'demokirasi',
rights: 'zwitouwa',
today: 'nuvhini',
important: 'zwithu zwikulu',
remember: 'humbula',
example: 'tsiere',
chapter: 'tshitanga',
},
ts: {
greeting: 'U amukeriwa eka dyondzo',
students: 'vadyondzi',
teacher: 'tisara',
classroom: 'kilasini',
lesson: 'dyondzo',
question: 'xivutiso',
answer: 'nxaviso',
read: 'hlaya',
write: 'tsala',
learn: 'dyondza',
numbers: 'tinomboro',
water: 'matti',
sun: 'dzuha',
earth: 'misava',
plant: 'mbuma',
animal: 'xiharhi',
history: 'xisiko',
freedom: 'ntshuxeko',
democracy: 'demokirasi',
rights: 'switshovo',
today: 'namuntlha',
important: 'nkoka',
remember: 'khumbula',
example: 'xilandza',
chapter: 'kavanyisa',
},
en: {
greeting: 'Welcome to the lesson',
students: 'students',
teacher: 'teacher',
classroom: 'classroom',
lesson: 'lesson',
question: 'question',
answer: 'answer',
read: 'read',
write: 'write',
learn: 'learn',
numbers: 'numbers',
water: 'water',
sun: 'sun',
earth: 'earth',
plant: 'plant',
animal: 'animal',
history: 'history',
freedom: 'freedom',
democracy: 'democracy',
rights: 'rights',
today: 'today',
important: 'important',
remember: 'remember',
example: 'example',
chapter: 'chapter',
}
};
// --- Sample Lessons ---
const SAMPLES = {
maths: `Today we are learning about numbers. In this lesson, students will learn to count from 1 to 100. The teacher will show examples of addition and subtraction. Remember: numbers are important in our daily life. Question: What is 5 + 3? Answer: 8. Chapter 1 is about whole numbers.`,
science: `Welcome to the lesson on water and the sun. In this chapter, students will learn how water is important for plants and animals on earth. The teacher will explain how the sun helps plants grow. Question: Why is water important? Answer: All living things need water to survive. Remember: the sun gives energy to the earth.`,
history: `Today we are learning about freedom and democracy in South Africa. In this lesson, students will learn about the history of our country. The teacher will explain the rights of all people. Question: What is democracy? Answer: Democracy means the people have the power. Remember: freedom is important for everyone. Chapter 3 is about our rights.`,
literacy: `Welcome to the lesson! Today students will read and write new words. The teacher will help you learn to read short stories. In this chapter, we practice writing sentences. Question: Can you write your name? Answer: Yes, I can write my name! Remember: reading and writing are important skills for every student.`,
};
// --- State ---
let selectedLangs = new Set();
let translationHistory = JSON.parse(localStorage.getItem('umkho_history') || '[]');
// --- Initialize ---
document.addEventListener('DOMContentLoaded', () => {
renderLangGrid();
updateCharCount();
checkOnlineStatus();
// Character count listener
document.getElementById('sourceText').addEventListener('input', updateCharCount);
// Online/offline listeners
window.addEventListener('online', checkOnlineStatus);
window.addEventListener('offline', checkOnlineStatus);
// Register service worker
if ('serviceWorker' in navigator) {
// In production, this would register sw.js
// navigator.serviceWorker.register('sw.js');
}
});
// --- Render Language Grid ---
function renderLangGrid() {
const grid = document.getElementById('langGrid');
const sourceLang = document.getElementById('sourceLang').value;
grid.innerHTML = SA_LANGUAGES
.filter(lang => lang.code !== sourceLang)
.map(lang => `
<button class="lang-chip ${selectedLangs.has(lang.code) ? 'selected' : ''}"
onclick="toggleLang('${lang.code}')"
aria-pressed="${selectedLangs.has(lang.code)}"
aria-label="Select ${lang.name}">
<span class="check-icon">
${selectedLangs.has(lang.code) ? '<svg xmlns="http://www.w3.org/2000/svg" class="w-3 h-3" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="3"><polyline points="20 6 9 17 4 12"/></svg>' : ''}
</span>
<span>${lang.flag} ${lang.name}</span>
</button>
`).join('');
document.getElementById('langCount').textContent = `${selectedLangs.size} selected`;
}
// --- Toggle Language Selection ---
function toggleLang(code) {
if (selectedLangs.has(code)) {
selectedLangs.delete(code);
} else {
selectedLangs.add(code);
}
renderLangGrid();
}
function selectAllLangs() {
const sourceLang = document.getElementById('sourceLang').value;
SA_LANGUAGES.forEach(l => { if (l.code !== sourceLang) selectedLangs.add(l.code); });
renderLangGrid();
}
function deselectAllLangs() {
selectedLangs.clear();
renderLangGrid();
}
// --- Update source language and refresh grid ---
document.addEventListener('DOMContentLoaded', () => {
document.getElementById('sourceLang').addEventListener('change', () => {
// Remove source lang from selected targets
const src = document.getElementById('sourceLang').value;
if (selectedLangs.has(src)) selectedLangs.delete(src);
renderLangGrid();
});
});
// --- Character Count ---
function updateCharCount() {
const text = document.getElementById('sourceText').value;
document.getElementById('charCount').textContent = `${text.length} characters`;
}
// --- Clear Source ---
function clearSource() {
document.getElementById('sourceText').value = '';
updateCharCount();
document.getElementById('resultsSection').classList.add('hidden');
}
// --- Paste from Clipboard ---
async function pasteFromClipboard() {
try {
const text = await navigator.clipboard.readText();
document.getElementById('sourceText').value = text;
updateCharCount();
showToast('Text pasted from clipboard');
} catch (err) {
showToast('Cannot access clipboard β please paste manually');
}
}
// --- File Upload ---
function handleFileUpload(event) {
const file = event.target.files[0];
if (!file) return;
if (file.name.endsWith('.txt')) {
const reader = new FileReader();
reader.onload = (e) => {
document.getElementById('sourceText').value = e.target.result;
updateCharCount();
showToast(`Loaded: ${file.name}`);
};
reader.readAsText(file);
} else {
showToast('Please upload a .txt file');
}
event.target.value = '';
}
// --- Load Sample ---
function loadSample(type) {
document.getElementById('sourceText').value = SAMPLES[type] || '';
updateCharCount();
showToast('Sample lesson loaded');
}
// --- Simulated Translation Engine ---
// This simulates the UmkhoAI offline translation engine.
// In production, this would call the actual on-device model.
function simulateTranslation(text, targetCode) {
const dict = TRANSLATIONS[targetCode];
if (!dict) return `[${targetCode}] ` + text;
// Smart word-by-word replacement with some phrase detection
let result = text;
// Sort keys by length (longest first) for better matching
const keys = Object.keys(TRANSLATIONS.en).sort((a, b) => b.length - a.length);
const srcDict = TRANSLATIONS[document.getElementById('sourceLang').value] || TRANSLATIONS.en;
keys.forEach(key => {
const englishWord = TRANSLATIONS.en[key];
const targetWord = dict[key];
if (englishWord && targetWord) {
// Case-insensitive whole word replacement
const regex = new RegExp(`\\b${englishWord}\\b`, 'gi');
result = result.replace(regex, targetWord);
}
});
// Add language-specific prefix to indicate it's translated
const langName = SA_LANGUAGES.find(l => l.code === targetCode)?.name || targetCode;
result = `γ${langName}γ\n` + result;
return result;
}
// --- Main Translate Function ---
async function translateText() {
const sourceText = document.getElementById('sourceText').value.trim();
const sourceLang = document.getElementById('sourceLang').value;
if (!sourceText) {
showToast('Please enter lesson text to translate');
return;
}
if (selectedLangs.size === 0) {
showToast('Please select at least one target language');
return;
}
// Show loading
const btn = document.getElementById('translateBtn');
btn.disabled = true;
const loading = document.getElementById('loadingIndicator');
const progressBar = document.getElementById('progressBar');
const loadingMsg = document.getElementById('loadingMsg');
loading.classList.remove('hidden');
loading.classList.add('flex', 'justify-center');
document.getElementById('resultsSection').classList.add('hidden');
const langs = Array.from(selectedLangs);
const speed = document.getElementById('speedSelect')?.value || 'balanced';
const delay = speed === 'fast' ? 200 : speed === 'accurate' ? 600 : 350;
const results = [];
for (let i = 0; i < langs.length; i++) {
const langCode = langs[i];
const langName = SA_LANGUAGES.find(l => l.code === langCode)?.name || langCode;
loadingMsg.textContent = `Translating to ${langName}... (${i + 1}/${langs.length})`;
progressBar.style.width = `${((i + 0.5) / langs.length) * 100}%`;
// Simulate processing delay
await new Promise(r => setTimeout(r, delay));
const translated = simulateTranslation(sourceText, langCode);
results.push({ code: langCode, name: langName, text: translated });
progressBar.style.width = `${((i + 1) / langs.length) * 100}%`;
}
// Done
loading.classList.add('hidden');
loading.classList.remove('flex', 'justify-center');
btn.disabled = false;
// Render results
renderResults(results);
// Save to history
if (document.getElementById('autoSave')?.checked !== false) {
saveToHistory(sourceText, results, sourceLang);
}
showToast(`Translated to ${results.length} language${results.length > 1 ? 's' : ''}!`);
}
// --- Render Results ---
function renderResults(results) {
const container = document.getElementById('resultsContainer');
const section = document.getElementById('resultsSection');
container.innerHTML = results.map(r => {
const langInfo = SA_LANGUAGES.find(l => l.code === r.code);
return `
<div class="result-card">
<div class="result-header bg-sa-greenPale">
<span class="font-bold text-sa-green flex items-center gap-2">
${langInfo?.flag || 'πΏπ¦'} ${r.name}
</span>
<div class="flex gap-1 no-print">
<button onclick="copyTranslation('${r.code}')" class="p-1.5 hover:bg-green-200 rounded-lg transition" title="Copy translation" aria-label="Copy ${r.name} translation">
<svg xmlns="http://www.w3.org/2000/svg" class="w-4 h-4 text-sa-green" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><rect x="9" y="9" width="13" height="13" rx="2" ry="2"/><path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"/></svg>
</button>
<button onclick="speakTranslation('${r.code}')" class="p-1.5 hover:bg-green-200 rounded-lg transition" title="Read aloud" aria-label="Read ${r.name} translation aloud">
<svg xmlns="http://www.w3.org/2000/svg" class="w-4 h-4 text-sa-green" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><polygon points="11 5 6 9 2 9 2 15 6 15 11 19 11 5"/><path d="M19.07 4.93a10 10 0 0 1 0 14.14"/><path d="M15.54 8.46a5 5 0 0 1 0 7.07"/></svg>
</button>
</div>
</div>
<div class="result-body" id="result-${r.code}">${escapeHtml(r.text)}</div>
</div>
`;
}).join('');
section.classList.remove('hidden');
section.scrollIntoView({ behavior: 'smooth', block: 'start' });
}
// --- Store current results for copy/speak ---
let currentResults = [];
const originalRenderResults = renderResults;
// Override to also store results
renderResults = function(results) {
currentResults = results;
originalRenderResults(results);
};
// --- Copy Single Translation ---
function copyTranslation(code) {
const result = currentResults.find(r => r.code === code);
if (result) {
navigator.clipboard.writeText(result.text).then(() => {
showToast(`${result.name} translation copied!`);
});
}
}
// --- Copy All Translations ---
function copyAllTranslations() {
const all = currentResults.map(r => `=== ${r.name} ===\n${r.text}`).join('\n\n');
navigator.clipboard.writeText(all).then(() => {
showToast('All translations copied!');
});
}
// --- Speak Translation ---
function speakTranslation(code) {
const result = currentResults.find(r => r.code === code);
if (!result) return;
if ('speechSynthesis' in window) {
window.speechSynthesis.cancel();
const utterance = new SpeechSynthesisUtterance(result.text.replace(/γ[^γ]+γ\n?/, ''));
utterance.lang = code === 'af' ? 'af-ZA' :
code === 'zu' ? 'zu-ZA' :
code === 'xh' ? 'xh-ZA' :
code === 'st' ? 'st-ZA' :
code === 'tn' ? 'tn-ZA' :
code === 'ts' ? 'ts-ZA' :
code === 'ss' ? 'ss-ZA' :
code === 've' ? 've-ZA' :
code === 'nr' ? 'nr-ZA' :
code === 'nso' ? 'nso-ZA' :
'en-ZA';
utterance.rate = 0.85;
window.speechSynthesis.speak(utterance);
showToast(`Reading in ${result.name}...`);
} else {
showToast('Speech not supported on this device');
}
}
// --- Print Translations ---
function printTranslations() {
window.print();
}
// --- Save to History ---
function saveToHistory(sourceText, results, sourceLang) {
const entry = {
id: Date.now(),
date: new Date().toLocaleString('en-ZA'),
sourceLang,
sourceText: sourceText.substring(0, 100) + (sourceText.length > 100 ? '...' : ''),
targetLangs: results.map(r => r.name),
translations: results,
};
translationHistory.unshift(entry);
if (translationHistory.length > 50) translationHistory.pop();
localStorage.setItem('umkho_history', JSON.stringify(translationHistory));
}
// --- Clear History ---
function clearHistory() {
translationHistory = [];
localStorage.removeItem('umkho_history');
renderHistoryList();
showToast('History cleared');
}
// --- Render History List ---
function renderHistoryList() {
const list = document.getElementById('historyList');
const empty = document.getElementById('historyEmpty');
if (translationHistory.length === 0) {
list.innerHTML = '';
empty.classList.remove('hidden');
return;
}
empty.classList.add('hidden');
list.innerHTML = translationHistory.map(h => `
<div class="history-item" onclick="loadFromHistory(${h.id})">
<div class="flex items-center justify-between">
<span class="text-xs text-gray-400">${h.date}</span>
<span class="text-xs px-2 py-0.5 bg-sa-greenPale text-sa-green rounded-full font-semibold">${h.targetLangs.length} lang${h.targetLangs.length > 1 ? 's' : ''}</span>
</div>
<p class="text-sm font-semibold text-gray-700 mt-1 truncate">${escapeHtml(h.sourceText)}</p>
<p class="text-xs text-gray-400 mt-0.5">${h.targetLangs.join(', ')}</p>
</div>
`).join('');
}
// --- Load from History ---
function loadFromHistory(id) {
const entry = translationHistory.find(h => h.id === id);
if (!entry) return;
document.getElementById('sourceLang').value = entry.sourceLang;
// We can't fully restore source text (it was truncated), but show translations
renderResults(entry.translations);
toggleHistory();
showToast('Loaded from history');
}
// --- Toggle Modals ---
function toggleHelp() {
const modal = document.getElementById('helpModal');
modal.classList.toggle('hidden');
if (!modal.classList.contains('hidden')) {
modal.querySelector('div').classList.add('modal-enter');
}
}
function toggleHistory() {
const modal = document.getElementById('historyModal');
modal.classList.toggle('hidden');
if (!modal.classList.contains('hidden')) {
renderHistoryList();
modal.querySelector('div').classList.add('modal-enter');
}
}
function toggleSettings() {
const modal = document.getElementById('settingsModal');
modal.classList.toggle('hidden');
if (!modal.classList.contains('hidden')) {
modal.querySelector('div').classList.add('modal-enter');
}
}
// --- Change Font Size ---
function changeFontSize(size) {
document.getElementById('fontSizeLabel').textContent = `${size}px`;
document.getElementById('sourceText').style.fontSize = `${size}px`;
document.querySelectorAll('.result-body').forEach(el => {
el.style.fontSize = `${size}px`;
});
}
// --- Online/Offline Status ---
function checkOnlineStatus() {
const banner = document.getElementById('offlineBanner');
if (!navigator.onLine) {
banner.classList.remove('hidden');
} else {
banner.classList.add('hidden');
}
}
// --- Toast Notification ---
function showToast(message) {
const toast = document.getElementById('toast');
const msg = document.getElementById('toastMsg');
msg.textContent = message;
toast.classList.remove('hidden');
// Force re-animation
toast.style.animation = 'none';
toast.offsetHeight; // trigger reflow
toast.style.animation = '';
clearTimeout(toast._timeout);
toast._timeout = setTimeout(() => {
toast.classList.add('hidden');
}, 3000);
}
// --- Escape HTML ---
function escapeHtml(str) {
const div = document.createElement('div');
div.textContent = str;
return div.innerHTML;
}
// --- Keyboard Shortcut ---
document.addEventListener('keydown', (e) => {
if ((e.ctrlKey || e.metaKey) && e.key === 'Enter') {
e.preventDefault();
translateText();
}
if (e.key === 'Escape') {
document.getElementById('helpModal').classList.add('hidden');
document.getElementById('historyModal').classList.add('hidden');
document.getElementById('settingsModal').classList.add('hidden');
}
}); |