ttag-org / ttag

:orange_book: simple approach for javascript localization
https://ttag.js.org/
MIT License
337 stars 40 forks source link

Catching missing phrases #239

Closed kakserpom closed 8 months ago

kakserpom commented 2 years ago

Hi! πŸ‘‹

Firstly, thanks for your work on this project! πŸ™‚

Today I used patch-package to patch ttag@1.7.24 for the project I'm working on.

Here is the diff that solved my problem:

diff --git a/node_modules/ttag/dist/ttag.js b/node_modules/ttag/dist/ttag.js
index 8bb5aac..e699eea 100644
--- a/node_modules/ttag/dist/ttag.js
+++ b/node_modules/ttag/dist/ttag.js
@@ -651,6 +651,12 @@ function TTag() {
     return null;
   };

+  let missingPhraseCb;
+  function onMissingPhrase(cb) {
+    missingPhraseCb = cb;
+  }
+
+
   var findTranslation = function findTranslation(str, ctx) {
     var locales = conf.getCurrentLocales();

@@ -665,7 +671,13 @@ function TTag() {
       }
     }

-    return findTransObj(conf.getCurrentLocale(), str, ctx);
+    const res = findTransObj(conf.getCurrentLocale(), str, ctx);
+    if (!res) {
+      if (missingPhraseCb) {
+        missingPhraseCb(str)
+      }
+    }
+    return res
   };

   function setDefaultLang(lang) {
@@ -786,7 +798,8 @@ function TTag() {
     setDefaultLang: setDefaultLang,
     t: t,
     useLocale: useLocale,
-    useLocales: useLocales
+    useLocales: useLocales,
+    onMissingPhrase,
   };
 }
 var globalTTag = new TTag();

This issue body was partially generated by patch-package.

AlexMost commented 2 years ago

Hi, glad that you have liked ttag!!! Seems like a reasonable improvement, going to add this feature to lib.

kakserpom commented 2 years ago

@AlexMost

let missingPhrases = []
ttag.onMissingPhrase(async phrase => {
    if (missingPhrases.includes(phrase)) {
        return
    }
    missingPhrases.push(phrase)

    phrase = phrase.replace(/\r?\n/g, '\\n')
    await fs.promises.appendFile('locales/' + locale + '.po', `msgid "${phrase}"\nmsgstr "${phrase}"\n\n`)
})

This way we don't need to write .po entries by hand :) Just write some code, test it and then translate.

AlexMost commented 2 years ago

Interesting use case. We are using ttag-cli https://github.com/ttag-org/ttag-cli for extracting and updating .po .pot files in our projects.