feat(i18n): add reactive Alpine $t() magic and fix storefront language variable
Some checks failed
Some checks failed
- Register Alpine magic $t() for reactive translations in templates - Dispatch i18n:ready event when translations load - Fix base.html to use current_language instead of storefront_language Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -11,9 +11,13 @@
|
||||
* // Or load modules later
|
||||
* await I18n.loadModule('inventory');
|
||||
*
|
||||
* // Translate
|
||||
* // Translate (in JS)
|
||||
* const message = I18n.t('catalog.messages.product_created');
|
||||
* const withVars = I18n.t('common.welcome', { name: 'John' });
|
||||
*
|
||||
* // Translate (in Alpine templates — reactive, updates when translations load)
|
||||
* // <span x-text="$t('catalog.messages.product_created')"></span>
|
||||
* // <span x-text="$t('common.welcome', {name: user})"></span>
|
||||
*/
|
||||
|
||||
// Create logger for i18n module (with silent fallback if LogConfig not yet loaded)
|
||||
@@ -43,6 +47,7 @@ const I18n = {
|
||||
if (modules && modules.length > 0) {
|
||||
await Promise.all(modules.map(m => this.loadModule(m)));
|
||||
}
|
||||
this._notifyReady();
|
||||
},
|
||||
|
||||
/**
|
||||
@@ -159,12 +164,44 @@ const I18n = {
|
||||
await this.loadModule(module);
|
||||
}
|
||||
}
|
||||
this._notifyReady();
|
||||
} catch (e) {
|
||||
i18nLog.error('Failed to change language:', e);
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* Notify Alpine (and other listeners) that translations are ready.
|
||||
* Bumps the Alpine store version so reactive $t() bindings re-evaluate.
|
||||
*/
|
||||
_notifyReady() {
|
||||
this._ready = true;
|
||||
// Bump Alpine store version if available (triggers $t() re-evaluation)
|
||||
if (typeof Alpine !== 'undefined' && Alpine.store) {
|
||||
const store = Alpine.store('i18n');
|
||||
if (store) store._v++;
|
||||
}
|
||||
document.dispatchEvent(new CustomEvent('i18n:ready'));
|
||||
}
|
||||
};
|
||||
|
||||
// Register Alpine magic $t() — reactive wrapper around I18n.t()
|
||||
// Works across all frontends (merchant, admin, store, storefront)
|
||||
document.addEventListener('alpine:init', () => {
|
||||
// Store with a reactive version counter
|
||||
Alpine.store('i18n', { _v: 0 });
|
||||
|
||||
// $t('key', {vars}) — use in x-text, x-html, or any Alpine expression
|
||||
// Before translations load, returns the key (which matches fallback text);
|
||||
// after _notifyReady() bumps _v, Alpine re-evaluates with loaded translations.
|
||||
Alpine.magic('t', (el) => {
|
||||
return (key, vars) => {
|
||||
void Alpine.store('i18n')._v; // reactive dependency
|
||||
return I18n.t(key, vars);
|
||||
};
|
||||
});
|
||||
});
|
||||
|
||||
// Export for module usage
|
||||
if (typeof window !== 'undefined') {
|
||||
window.I18n = I18n;
|
||||
|
||||
Reference in New Issue
Block a user