aboutsummaryrefslogtreecommitdiffstats
path: root/apps/kit/src/lib/components/locale-switcher.svelte
diff options
context:
space:
mode:
authorivarlovlie <git@ivarlovlie.no>2022-09-20 09:24:27 +0200
committerivarlovlie <git@ivarlovlie.no>2022-09-20 09:24:27 +0200
commita9072370ca1eb9a5cce928b1d487db0f307edea6 (patch)
tree59c3c23df930a8b5f888dc7813923abf4ceefed4 /apps/kit/src/lib/components/locale-switcher.svelte
parent56fa963a1d63cbe0bf28e29e717cceaa417c45c1 (diff)
downloadgreatoffice-a9072370ca1eb9a5cce928b1d487db0f307edea6.tar.xz
greatoffice-a9072370ca1eb9a5cce928b1d487db0f307edea6.zip
feat: Move old apps into it's own directory
Diffstat (limited to 'apps/kit/src/lib/components/locale-switcher.svelte')
-rw-r--r--apps/kit/src/lib/components/locale-switcher.svelte52
1 files changed, 52 insertions, 0 deletions
diff --git a/apps/kit/src/lib/components/locale-switcher.svelte b/apps/kit/src/lib/components/locale-switcher.svelte
new file mode 100644
index 0000000..39d6168
--- /dev/null
+++ b/apps/kit/src/lib/components/locale-switcher.svelte
@@ -0,0 +1,52 @@
+<script lang="ts">
+ import {browser} from "$app/environment";
+ import {page} from "$app/stores";
+ import {setLocale, locale} from "$lib/i18n/i18n-svelte";
+ import type {Locales} from "$lib/i18n/i18n-types";
+ import {locales} from "$lib/i18n/i18n-util";
+ import {loadLocaleAsync} from "$lib/i18n/i18n-util.async";
+
+ const switchLocale = async (
+ newLocale: Locales,
+ updateHistoryState = true,
+ ) => {
+ if (!newLocale || $locale === newLocale) return;
+
+ // load new dictionary from server
+ await loadLocaleAsync(newLocale);
+
+ // select locale
+ setLocale(newLocale);
+
+ // update `lang` attribute
+ document.querySelector("html")?.setAttribute("lang", newLocale);
+
+ //TODO set cookie that persists the locale
+ };
+
+ // update locale when navigating via browser back/forward buttons
+ const handlePopStateEvent = async ({state}: PopStateEvent) =>
+ switchLocale(state.locale, false);
+
+ // update locale when page store changes
+ $: if (browser) {
+ const lang = $page.params.lang as Locales;
+ switchLocale(lang, false);
+ }
+</script>
+
+<svelte:window on:popstate={handlePopStateEvent}/>
+
+<ul>
+ {#each locales as l}
+ <li>
+ <button
+ type="button"
+ class:active={l === $locale}
+ on:click={() => switchLocale(l)}
+ >
+ {l}
+ </button>
+ </li>
+ {/each}
+</ul>