Skip to content

Commit

Permalink
fix(lyrics-plus/Translator): Correct wait-and-retry logic
Browse files Browse the repository at this point in the history
  • Loading branch information
pan93412 committed Aug 11, 2023
1 parent cc1c46b commit e71d12d
Showing 1 changed file with 26 additions and 16 deletions.
42 changes: 26 additions & 16 deletions CustomApps/lyrics-plus/Translator.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,15 +7,15 @@ const dictPath = "https:/cdn.jsdelivr.net/npm/[email protected]/dict";

class Translator {
constructor(lang) {
this.applyKuromojiFix();
this.injectExternals(lang);
this.createTranslator(lang);

this.finished = {
ja: false,
ko: false,
zh: false
};

this.applyKuromojiFix();
this.injectExternals(lang);
this.createTranslator(lang);
}

includeExternal(url) {
Expand Down Expand Up @@ -63,8 +63,8 @@ class Translator {
case "ja":
if (this.kuroshiro) return;
if (typeof Kuroshiro === "undefined" || typeof KuromojiAnalyzer === "undefined") {
setTimeout(this.createTranslator.bind(this), 50, lang);
return;
await Translator.#wait(50);
return this.createTranslator(lang);
}

this.kuroshiro = new Kuroshiro.default();
Expand All @@ -78,8 +78,8 @@ class Translator {
case "ko":
if (this.Aromanize) return;
if (typeof Aromanize === "undefined") {
setTimeout(this.createTranslator.bind(this), 50, lang);
return;
await Translator.#wait(50);
return this.createTranslator(lang);
}

this.Aromanize = Aromanize;
Expand All @@ -88,8 +88,8 @@ class Translator {
case "zh":
if (this.OpenCC) return;
if (typeof OpenCC === "undefined") {
setTimeout(this.createTranslator.bind(this), 50, lang);
return;
await Translator.#wait(50);
return this.createTranslator(lang);
}

this.OpenCC = OpenCC;
Expand All @@ -98,10 +98,20 @@ class Translator {
}
}

/**
* Async wrapper of `setTimeout`.
*
* @param {number} ms
* @returns {Promise<void>}
*/
static async #wait(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}

async romajifyText(text, target = "romaji", mode = "spaced") {
if (!this.finished.ja) {
setTimeout(this.romajifyText.bind(this), 100, text, target, mode);
return;
await Translator.#wait(100);
return this.romajifyText(text, target, mode);
}

return this.kuroshiro.convert(text, {
Expand All @@ -112,8 +122,8 @@ class Translator {

async convertToRomaja(text, target) {
if (!this.finished.ko) {
setTimeout(this.convertToRomaja.bind(this), 100, text, target);
return;
await Translator.#wait(100);
return this.convertToRomaja(text, target);
}

if (target === "hangul") return text;
Expand All @@ -122,8 +132,8 @@ class Translator {

async convertChinese(text, from, target) {
if (!this.finished.zh) {
setTimeout(this.convertChinese.bind(this), 100, text, target);
return;
await Translator.#wait(100);
return this.convertChinese(text, from, target);
}

const converter = this.OpenCC.Converter({
Expand Down

0 comments on commit e71d12d

Please sign in to comment.