SVGHMI: Add "lang" permament persistent HMI_LOCAL variable to reflect selected language, apply stored language choice at startup and make it always subscribed to a pseudo widget (as for hearbeat) that apply language choice when it changes. svghmi
authorEdouard Tisserant <edouard.tisserant@gmail.com>
Tue, 09 Feb 2021 07:55:16 +0100
branchsvghmi
changeset 3129 f2709923c82c
parent 3128 32a4675af377
child 3130 bdd81e12e7b5
SVGHMI: Add "lang" permament persistent HMI_LOCAL variable to reflect selected language, apply stored language choice at startup and make it always subscribed to a pseudo widget (as for hearbeat) that apply language choice when it changes.
svghmi/hmi_tree.ysl2
svghmi/svghmi.js
--- a/svghmi/hmi_tree.ysl2	Tue Feb 09 07:46:02 2021 +0100
+++ b/svghmi/hmi_tree.ysl2	Tue Feb 09 07:55:16 2021 +0100
@@ -143,7 +143,14 @@
     }
 }
 
-const "_parsed_widgets" apply "$hmi_elements", mode="parselabel";
+const "_parsed_widgets" {
+    widget type="VarInitPersistent" {
+        arg value="0";
+        path value="lang";
+    }
+    apply "$hmi_elements", mode="parselabel";
+}
+
 const "parsed_widgets","exsl:node-set($_parsed_widgets)";
 
 def "func:widget" {
--- a/svghmi/svghmi.js	Tue Feb 09 07:46:02 2021 +0100
+++ b/svghmi/svghmi.js	Tue Feb 09 07:55:16 2021 +0100
@@ -204,6 +204,39 @@
     }
 });
 
+var translated = false;
+
+function switch_langnum(langnum) {
+    if(langnum == current_lang) {
+        return;
+    }
+
+    if (!translated) {
+        translated = true;
+        for (let translation of translations) {
+            let [objs] = translation;
+            translation.push(Array.prototype.map.call(objs[0].children, x=>x.textContent).join("\\\\n")); 
+        }
+    }
+
+    for (let translation of translations) {
+        let [objs, msgs, orig] = translation;
+        let msg = langnum == 0 ? orig : msgs[langnum - 1];
+        for (let obj of objs) {
+            msg.split('\\\\n').map((line,i) => {obj.children[i].textContent = line;});
+        }
+    }
+    current_lang = langnum;
+}
+var lang_local_index = hmi_local_index("lang");
+subscribers(lang_local_index).add({
+    indexes: [lang_local_index],
+    new_hmi_value: function(index, value, oldval) {
+        switch_langnum(value);
+    }
+});
+var current_lang = 0;
+switch_langnum(cache[lang_local_index]);
 
 function update_subscriptions() {
     let delta = [];
@@ -472,18 +505,3 @@
     current_modal = undefined;
 };
 
-function switch_lang(lang) {
-    langnum = langs.indexOf(lang);
-    if(langnum == -1) {
-        console.log("Unknown language: "+lang+", return to original");
-        location.reload(true);
-    }
-
-    for (let translation of translations) {
-        let [objs, msgs] = translation;
-        let msg = msgs[langnum];
-        for (let obj of objs) {
-            msg.split('\\\\n').map((line,i) => {obj.children[i].textContent = line;});
-        }
-    }
-}