Spaces:
Running
Running
| function swapLanguages() { | |
| const sourceLang = document.getElementById('sourceLang'); | |
| const targetLang = document.getElementById('targetLang'); | |
| const temp = sourceLang.value; | |
| sourceLang.value = targetLang.value; | |
| targetLang.value = temp; | |
| } | |
| async function postRequest(sourceLang, targetLang, inputText, outputText, loading, translateBtn, endpoint) { | |
| try { | |
| const response = await fetch(endpoint, { | |
| method: 'POST', | |
| headers: { | |
| 'Content-Type': 'application/json' | |
| }, | |
| body: JSON.stringify({ | |
| sourceLangCode: sourceLang, | |
| targetLangCode: targetLang, | |
| textArray: [inputText] | |
| }) | |
| }); | |
| if (!response.ok) { | |
| throw new Error('Translation failed'); | |
| } | |
| const data = await response.json(); | |
| const translation = data.data.translationArray[0]; | |
| outputText.textContent = translation; | |
| } catch (error) { | |
| outputText.textContent = 'Error: ' + error.message; | |
| } finally { | |
| loading.classList.remove('visible'); | |
| translateBtn.disabled = false; | |
| } | |
| } | |
| async function doTranslate() { | |
| const inputText = document.getElementById('inputText').value.trim(); | |
| if (!inputText) { | |
| return; | |
| } | |
| let sourceLang = document.getElementById('sourceLang').value; | |
| const targetLang = document.getElementById('targetLang').value; | |
| if (targetLang === 'bn_NG') { | |
| sourceLang = 'en_XX'; | |
| } | |
| const outputText = document.getElementById('outputText'); | |
| const loading = document.getElementById('loading'); | |
| const translateBtn = document.getElementById('translateBtn'); | |
| // Show loading state | |
| loading.classList.add('visible'); | |
| translateBtn.disabled = true; | |
| outputText.classList.remove('empty'); | |
| outputText.textContent = ''; | |
| postRequest(sourceLang, targetLang, inputText, outputText, loading, translateBtn, '/api/translate'); | |
| } | |
| // Allow Ctrl+Enter to translate | |
| document.addEventListener('DOMContentLoaded', () => { | |
| document.getElementById('inputText').addEventListener('keydown', function (e) { | |
| if (e.ctrlKey && e.key === 'Enter') { | |
| doTranslate(); | |
| } | |
| }); | |
| }); | |