studiocms
Version:
Astro Native CMS for AstroDB. Built from the ground up by the Astro community.
70 lines (69 loc) • 2.3 kB
JavaScript
import augmentTranslations from "studiocms:i18n/augment-translations";
import { $locale, $localeSettings, defaultLang } from "studiocms:i18n/client";
import pluginTranslations from "studiocms:i18n/plugin-translations";
import { createI18n } from "@nanostores/i18n";
function $pluginI18n(pluginId, componentId) {
const translations = pluginTranslations[pluginId];
if (!translations || !translations[defaultLang]) {
console.warn(`[i18n] Missing translations for plugin "${pluginId}".`);
return createI18n($locale, {
baseLocale: defaultLang,
get: async () => ({})
})(componentId, {});
}
const base = translations[defaultLang] ?? {};
const componentBase = base[componentId] ?? {};
return createI18n($locale, {
baseLocale: defaultLang,
get: async (code) => translations[code] ?? base
})(componentId, componentBase);
}
function $augmentI18n() {
const getComponents = (code) => {
const lang = augmentTranslations[code]?.augments;
const fallback = augmentTranslations[defaultLang]?.augments ?? {};
return { augments: lang ?? fallback };
};
return createI18n($locale, {
baseLocale: defaultLang,
get: async (code) => getComponents(code)
})("augments", getComponents(defaultLang).augments);
}
class PluginTranslations extends HTMLElement {
currentLang;
unsubscribeLocale;
unsubscribeTranslations;
constructor() {
super();
this.unsubscribeLocale = $localeSettings.subscribe((val) => {
this.currentLang = val;
});
}
connectedCallback() {
const pluginId = this.getAttribute("plugin");
const componentId = this.getAttribute("component");
const key = this.getAttribute("key");
if (!pluginId || !componentId || !key) {
console.error("Missing required attributes");
return;
}
const i18n = $pluginI18n(pluginId, componentId);
this.unsubscribeTranslations?.();
this.unsubscribeTranslations = i18n.subscribe((comp) => {
const translation = comp[key];
if (typeof translation === "string" && translation.trim() === "") {
return;
}
this.textContent = translation;
});
}
disconnectedCallback() {
this.unsubscribeTranslations?.();
this.unsubscribeLocale?.();
}
}
export {
$augmentI18n,
$pluginI18n,
PluginTranslations
};