Skip to content

Commit

Permalink
perf: setup locale sync once
Browse files Browse the repository at this point in the history
  • Loading branch information
arildm committed Oct 9, 2024
1 parent f797aeb commit bd9fc80
Showing 1 changed file with 21 additions and 14 deletions.
35 changes: 21 additions & 14 deletions src/i18n/locale.composable.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,33 +2,40 @@ import { computed, watch } from "vue";
import { useI18n } from "vue-i18n";
import { filesize } from "filesize";
import { useStorage } from "@vueuse/core";
import { once } from "lodash";
import type { Ref } from "vue";
import type { ByLang, SvEn, SweEng } from "@/util.types";

const storedLocale = useStorage<SvEn | "">("locale", "");

export default function useLocale() {
const { locale } = useI18n();

const exportLocale = () => {
document.querySelector("html")?.setAttribute("lang", locale.value);
};

// The ISO 639-3 code is used in many parts of the Språkbanken infrastructure.
const locale3 = computed<SweEng>(() =>
locale.value == "en" ? "eng" : "swe",
);

/** Set up locale sync */
const setupLocale = once((locale: Ref<string>) => {
// Sync from storage once, if present
if (storedLocale.value) {
locale.value = storedLocale.value;
}
exportLocale();
exportLocale(locale.value);

// Then sync from switcher continually
watch(locale, () => {
storedLocale.value = (locale.value as SvEn) || "";
exportLocale();
exportLocale(locale.value);
});
});

const exportLocale = (lang: string) =>
document.querySelector("html")?.setAttribute("lang", lang);

/** Set up locale sync and provide helpers */
export default function useLocale() {
const { locale } = useI18n();

setupLocale(locale);

// The ISO 639-3 code is used in many parts of the Språkbanken infrastructure.
const locale3 = computed<SweEng>(() =>
locale.value == "en" ? "eng" : "swe",
);

/** Translate here - picks the current language out of a strings-by-language object. */
function th(map?: ByLang | string): string | undefined {
Expand Down

0 comments on commit bd9fc80

Please sign in to comment.