Newer
Older
gnexus-book / ui / src / i18n / index.js
@Eugene Sukhodolskiy Eugene Sukhodolskiy 1 day ago 1 KB feat(ui): add en/uk/ru localization
import { ref, watch } from "vue";
import en from "./messages/en.js";
import uk from "./messages/uk.js";
import ru from "./messages/ru.js";

export const SUPPORTED_LOCALES = ["en", "uk", "ru"];
export const localeOptions = [
  { value: "en", label: "English" },
  { value: "uk", label: "Українська" },
  { value: "ru", label: "Русский" }
];

const dictionaries = { en, uk, ru };
export const locale = ref("en");

export function normalizeLocale(value) {
  const tag = String(value || "en")
    .toLowerCase()
    .split("-", 1)[0];
  return SUPPORTED_LOCALES.includes(tag) ? tag : "en";
}

export function savedLocale() {
  try {
    return localStorage.getItem("gnb.locale");
  } catch {
    return null;
  }
}

export function setLocale(next, { persist = true } = {}) {
  const normalized = normalizeLocale(next);
  locale.value = normalized;
  if (persist) {
    try {
      localStorage.setItem("gnb.locale", normalized);
    } catch {
      /* storage may be unavailable */
    }
  }
}

export function t(slug, params = {}) {
  const dictionary = dictionaries[locale.value] || en;
  const text = dictionary[slug] ?? en[slug] ?? slug;
  return String(text).replace(/\{(\w+)\}/g, (_, key) =>
    params[key] === undefined || params[key] === null ? `{${key}}` : String(params[key])
  );
}

watch(
  locale,
  value => {
    if (typeof document !== "undefined") {
      document.documentElement.lang = value;
      document.title = t("app.title");
    }
  },
  { immediate: true }
);