@@ -5,7 +5,7 @@ import { TagFilter } from '../components/TagFilter'
55import PostCard from ' ../components/PostCard.astro'
66import { getPublishedPosts , getPostHref , getPostLocale , getLocales , getAllTags , getReadingTime } from ' ../lib/posts'
77import { getAuthor } from ' ../lib/authors'
8- import { defaultLang } from ' ../i18n/ui'
8+ import { defaultLang , ui } from ' ../i18n/ui'
99import { useTranslations } from ' ../i18n/utils'
1010
1111const allPosts = await getCollection (' posts' )
@@ -20,7 +20,8 @@ const t = useTranslations(locale)
2020 <!-- Page header -->
2121 <section class =" mb-8" >
2222 <h1 class =" text-4xl md:text-5xl font-bold tracking-tight" >
23- { t (' index.heading.prefix' )} <span class =" text-primary" >{ t (' index.heading.highlight' )} </span >
23+ <span data-i18n =" index.heading.prefix" >{ t (' index.heading.prefix' )} </span >{ ' ' }
24+ <span class =" text-primary" data-i18n =" index.heading.highlight" >{ t (' index.heading.highlight' )} </span >
2425 </h1 >
2526 </section >
2627
@@ -57,20 +58,32 @@ const t = useTranslations(locale)
5758
5859</Base >
5960
60- <script define:vars ={ { supportedLocales: locales , fallbackLocale: locale }} >
61- function filterByLocale () {
62- const match = document.cookie.match(/(?:^|; )locale=([^;]*)/)
63- const cookieLocale = match ? match[1] : null
64- const browserLang = (navigator.language || '').split('-')[0]
65- const detected = (cookieLocale && supportedLocales.includes(cookieLocale))
61+ <script define:vars ={ { supportedLocales: locales , fallbackLocale: locale , translations: ui }} >
62+ function detectLocale () {
63+ var match = document.cookie.match(/(?:^|; )locale=([^;]*)/)
64+ var cookieLocale = match ? match[1] : null
65+ var browserLang = (navigator.language || '').split('-')[0]
66+ return (cookieLocale && supportedLocales.includes(cookieLocale))
6667 ? cookieLocale
6768 : supportedLocales.includes(browserLang) ? browserLang : fallbackLocale
69+ }
6870
71+ function applyLocale(detected) {
72+ window.__detectedLocale = detected
6973 document.querySelectorAll('[data-locale]').forEach(function (el) {
7074 el.style.display = el.dataset.locale === detected ? '' : 'none'
7175 })
76+ window.dispatchEvent(new CustomEvent('locale:change', { detail: { locale: detected } }))
7277 }
7378
74- filterByLocale()
75- document.addEventListener('astro:after-swap', filterByLocale)
79+ window.addEventListener('locale:change', function (e) {
80+ var t = translations[e.detail.locale] || translations[fallbackLocale]
81+ document.querySelectorAll('[data-i18n]').forEach(function (el) {
82+ var key = el.dataset.i18n
83+ if (t[key] !== undefined) el.textContent = t[key]
84+ })
85+ })
86+
87+ applyLocale(detectLocale())
88+ document.addEventListener('astro:after-swap', function () { applyLocale(detectLocale()) })
7689</script >
0 commit comments