Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(theme): find best locale match to format last update #4360

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 31 additions & 2 deletions src/client/theme-default/components/VPDocFooterLastUpdated.vue
Original file line number Diff line number Diff line change
Expand Up @@ -9,13 +9,42 @@ const date = computed(
)
const isoDatetime = computed(() => date.value.toISOString())
const datetime = ref('')
const timeRef = ref<HTMLTimeElement>()

// set time on mounted hook to avoid hydration mismatch due to
// potential differences in timezones of the server and clients
onMounted(() => {
const defaultLocale = Intl.DateTimeFormat().resolvedOptions().locale
function findBestLocaleMatch(pageLocale: string) {
const lang = navigator.languages.find((userLang) => {
if (pageLocale === userLang)
return true

// Edge browser: case for ca-valencia
if (pageLocale === 'ca-valencia' && userLang === 'ca-Es-VALENCIA')
return true

// add iso-639 support for Latin America
if (userLang.startsWith('es-') && userLang !== 'es-ES' && pageLocale === 'es-419')
return true

return userLang.startsWith(pageLocale)
}) ?? defaultLocale

if (lang !== pageLocale) {
timeRef.value?.setAttribute('lang', lang)
}
else {
timeRef.value?.removeAttribute('lang')
}

return lang
}
watchEffect(() => {
datetime.value = new Intl.DateTimeFormat(
theme.value.lastUpdated?.formatOptions?.forceLocale ? lang.value : undefined,
theme.value.lastUpdated?.formatOptions?.forceLocale
? lang.value
: findBestLocaleMatch(lang.value),
theme.value.lastUpdated?.formatOptions ?? {
dateStyle: 'short',
timeStyle: 'short'
Expand All @@ -28,7 +57,7 @@ onMounted(() => {
<template>
<p class="VPLastUpdated">
{{ theme.lastUpdated?.text || theme.lastUpdatedText || 'Last updated' }}:
<time :datetime="isoDatetime">{{ datetime }}</time>
<time ref="timeRef" :datetime="isoDatetime">{{ datetime }}</time>
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

use lang attr via ref value here instead element ref

</p>
</template>

Expand Down