diff options
| author | ivarlovlie <git@ivarlovlie.no> | 2023-02-11 23:37:12 +0100 |
|---|---|---|
| committer | ivarlovlie <git@ivarlovlie.no> | 2023-02-11 23:37:12 +0100 |
| commit | 9b2c63d92ff77ebce0f90a7be05437504422bf45 (patch) | |
| tree | 682447cde9d3eed555973ff1aff369b4443da07f /src/components/locale-switcher.svelte | |
| parent | 23ab0a24ba82004fa449491b4e08698a1de9e6a0 (diff) | |
| download | auroraklinikken.no-9b2c63d92ff77ebce0f90a7be05437504422bf45.tar.xz auroraklinikken.no-9b2c63d92ff77ebce0f90a7be05437504422bf45.zip | |
feat: Render localized content from sanity
Diffstat (limited to 'src/components/locale-switcher.svelte')
| -rw-r--r-- | src/components/locale-switcher.svelte | 46 |
1 files changed, 46 insertions, 0 deletions
diff --git a/src/components/locale-switcher.svelte b/src/components/locale-switcher.svelte new file mode 100644 index 0000000..938d18a --- /dev/null +++ b/src/components/locale-switcher.svelte @@ -0,0 +1,46 @@ +<script lang="ts"> + import { browser } from "$app/environment"; + import { invalidateAll } from "$app/navigation"; + import { page } from "$app/stores"; + import { setLocale, locale } from "$i18n/i18n-svelte"; + import type { Locales } from "$i18n/i18n-types"; + import { locales } from "$i18n/i18n-util"; + import { loadLocaleAsync } from "$i18n/i18n-util.async"; + import { replaceLocaleInUrl } from "$lib/utils"; + + 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); + if (updateHistoryState) { + // update url to reflect locale changes + history.pushState({ locale: newLocale }, "", replaceLocaleInUrl($page.url, newLocale)); + } + // run the `load` function again + invalidateAll(); + }; + // 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); + history.replaceState({ ...history.state, locale: lang }, "", replaceLocaleInUrl($page.url, lang)); + } +</script> + +<svelte:window on:popstate={handlePopStateEvent} /> + +<ul> + {#each locales as l} + <li> + <a class:active={l === $locale} href={`${replaceLocaleInUrl($page.url, l)}`}> + {l} + </a> + </li> + {/each} +</ul> |
