aboutsummaryrefslogtreecommitdiffstats
path: root/src/components/locale-switcher.svelte
blob: aa4e0c4b2099355ee07e47ecb3250a497c6e1d6c (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
<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} />

{#if $locale == "en"}
	<a href={replaceLocaleInUrl($page.url, "nb")}>Norsk Bokmål</a>
{:else if $locale == "nb"}
	<a href={replaceLocaleInUrl($page.url, "en")}>English</a>
{/if}