UNPKG

language-observer

Version:

The LanguageObserver class provides a simple way to manage internationalization in your web application. It automates the process of applying translations and simplifies support for multiple languages.

2 lines (1 loc) 2.5 kB
(function(i,r){typeof exports=="object"&&typeof module<"u"?module.exports=r():typeof define=="function"&&define.amd?define(r):(i=typeof globalThis<"u"?globalThis:i||self).LanguageObserver=r()})(this,function(){"use strict";class i{lang="ru";observer=null;constructor(){this.initializeObserver()}static getNestedTranslation(t,e){return e.split(".").reduce((a,s)=>{if(a&&typeof a=="object"&&s in a)return a[s]},t)}safeGetTranslation(t,e){if(!t)return;const a=i.getNestedTranslation(t,e);return typeof a=="string"?a:void 0}checkInitialLanguage(){if(this.lang&&this.lang!=="ru")return;const t=this.detectLanguageFromParams();if(t)this.loadLanguage(t);else{const e=this.detectLanguageFromClass();this.loadLanguage(e)}}detectLanguageFromParams(){if(typeof window>"u")return null;const t=new URLSearchParams(window.location.search).get("land-geo");return t?(this.updateBodyClass(t),t):null}detectLanguageFromClass(){const t=Array.from(document.body.classList).find(e=>e.startsWith("locale-"));return t?t.replace("locale-",""):"ru"}updateBodyClass(t){document.body.classList.forEach(e=>{e.startsWith("locale-")&&document.body.classList.remove(e)}),document.body.classList.add(`locale-${t}`)}loadLanguage(t){const e=globalThis.translations;this.lang=e[t]?t:"ru",this.applyTranslations()}applyTranslations(){const t=globalThis.translations,e=t[this.lang],a=t.ru;e&&document.querySelectorAll("[data-i18n], [data-i18n-attr]").forEach(s=>{const l=s.getAttribute("data-i18n"),u=s.getAttribute("data-i18n-attr");if(l){let n=this.safeGetTranslation(e,l);!n&&a&&(n=this.safeGetTranslation(a,l)),n&&this.updateElementText(s,n)}if(u){let n;try{n=JSON.parse(u)}catch{return}Object.entries(n).forEach(([c,d])=>{let o=this.safeGetTranslation(e,d);!o&&a&&(o=this.safeGetTranslation(a,d)),o&&s.setAttribute(c,o)})}})}updateElementText(t,e){t.hasChildNodes()?t.childNodes.forEach(a=>{a.nodeType===Node.TEXT_NODE&&(a.textContent=e)}):t.textContent=e}initializeObserver(){this.observer=new MutationObserver(t=>{for(const e of t)if(e.type==="attributes"&&e.attributeName==="class"){const a=this.detectLanguageFromClass();a!==this.lang&&this.loadLanguage(a)}}),this.observer.observe(document.body,{attributes:!0,attributeFilter:["class"]})}init(t={}){const{lang:e}=t;e?(this.updateBodyClass(e),this.lang=e,this.loadLanguage(e)):this.checkInitialLanguage()}updateTranslations(){this.applyTranslations()}async loadTranslations(t,e){const a=await e(t);globalThis.translations[t]=a,t===this.lang&&this.applyTranslations()}}return i});