Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 21 additions & 8 deletions src/plugins/translate/TranslationManager.js
Original file line number Diff line number Diff line change
Expand Up @@ -101,12 +101,16 @@ export class TranslationManager {
*/

getTranslation = async (fromLang, toLang, pageIndex, paragraphIndex, text, priority) => {
this.active = true;
if (fromLang == toLang || !fromLang || !toLang) {
return;
}
if (!this.translator) { //Ensure translator is initialized before use
await this.initWorker();
}
if (fromLang == toLang || !fromLang || !toLang) {
return "";
}
this.active = true; //Moved active = true after validation to avoid setting active when no translation is performed (prevents infinite loading state).

const key = `${fromLang}${toLang}-${pageIndex}:${paragraphIndex}`;
const cachedEntry = this.alreadyTranslated.entries.find(x => x.index == key);
const cachedEntry = this.alreadyTranslated.entries.find(x => x.index == key); //If Cache supports .get() method, better use that.

if (cachedEntry) {
return cachedEntry.response;
Expand All @@ -129,10 +133,11 @@ export class TranslationManager {
reject: _reject,
};

if (!text) {
if (!text) { //Handle empty text safely
this.currentlyTranslating[key].reject("No text was provided");
delete this.currentlyTranslating[key];
return promise;
}
}
this.translator.translate({
to: toLang,
from: fromLang,
Expand All @@ -143,7 +148,15 @@ export class TranslationManager {
const response = resp;
this.currentlyTranslating[key].resolve(response.target.text);
this.alreadyTranslated.add({index: key, response: response.target.text});
delete this.currentlyTranslating[key];
}).catch((error) => {
console.error("Translation failed:", error);
this.currentlyTranslating[key].reject(error);
})
.finally(() => { //Proper cleanup after translation completes
delete this.currentlyTranslating[key];
if (Object.keys(this.currentlyTranslating).length === 0) {
this.active = false;
}
});

return promise;
Expand Down