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: fall back if translation is missing #3312

Open
wants to merge 6 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
75 changes: 75 additions & 0 deletions src/client/app/router.ts
Expand Up @@ -152,13 +152,88 @@ export function createRouter(
} catch (e) {}
}

if (siteDataRef.value.localesFallback) {
await loadFallback()
}

if (latestPendingPath === pendingPath) {
latestPendingPath = null
route.path = inBrowser ? pendingPath : withBase(pendingPath)
route.component = fallbackComponent ? markRaw(fallbackComponent) : null
route.data = notFoundPageData
}
}

async function loadFallback() {
const locales = siteDataRef.value.locales

for (const [key, value] of Object.entries(locales)) {
if (!value.fallback) continue
if (value.fallback === 'root') {
throw new Error(
`Invalid VitePress Config: A locale (${key}), cannot fall back to (root).`
)
}
if (key === value.fallback) {
throw new Error(
`Invalid VitePress Config: A locale (${key}), cannot have a fallback to itself.`
)
}
if (!Object.keys(locales).includes(value.fallback)) {
throw new Error(
`Invalid VitePress Config: A locale (${key}), cannot have a fallback to a non existing locale.`
)
}
}

// If the length is less than 2, it means there are no alternative locales to fallback to.
if (!locales || Object.keys(locales).length < 2) {
return
}

const nonRootLocales = Object.fromEntries(
Object.entries(locales).filter(([name]) => name !== 'root')
)

const failedLocaleKey =
Object.keys(nonRootLocales).find(
(lang) =>
pendingPath === `/${lang}` || pendingPath.startsWith(`/${lang}/`)
) || 'root'

if (failedLocaleKey !== 'root') {
const fallbackLang =
locales[failedLocaleKey].fallback ?? getCustomFallbackLang()

await loadPage(
pendingPath.replace(
`/${failedLocaleKey}`,
fallbackLang ? `/${fallbackLang}` : ''
),
scrollPosition,
true
)
} else {
const fallbackPath = getRootLocaleFallbackPath()
if (!fallbackPath) return
await loadPage(fallbackPath, scrollPosition, true)
}

function getCustomFallbackLang() {
const customFallbackLang = siteDataRef.value.localesDefaultFallback
if (customFallbackLang && customFallbackLang !== failedLocaleKey) {
return customFallbackLang
}
}

function getRootLocaleFallbackPath() {
const fallbackLang = locales['root'].fallback
if (!fallbackLang) return
if (pendingPath === '/') return `/${fallbackLang}`
const pathDivider = pendingPath.startsWith('/') ? '' : '/'
return `/${fallbackLang}${pathDivider}${pendingPath}`
}
}
}

if (inBrowser) {
Expand Down
2 changes: 2 additions & 0 deletions src/node/config.ts
Expand Up @@ -252,6 +252,8 @@ export async function resolveSiteData(
appearance: userConfig.appearance ?? true,
themeConfig: userConfig.themeConfig || {},
locales: userConfig.locales || {},
localesFallback: userConfig.localesFallback ?? true,
localesDefaultFallback: userConfig.localesDefaultFallback,
scrollOffset: userConfig.scrollOffset ?? 134,
cleanUrls: !!userConfig.cleanUrls,
contentProps: userConfig.contentProps
Expand Down
10 changes: 10 additions & 0 deletions src/node/siteConfig.ts
Expand Up @@ -69,6 +69,16 @@ export interface UserConfig<ThemeConfig = any>

locales?: LocaleConfig<ThemeConfig>

/**
* If a page isn't found in the current language, allow switching to another language as a backup.
*/
localesFallback?: boolean

/**
* Use a custom locale key to be used as a default fallback for all locales. Default is root.
*/
localesDefaultFallback?: string

router?: {
prefetchLinks?: boolean
}
Expand Down
17 changes: 16 additions & 1 deletion types/shared.d.ts
Expand Up @@ -124,6 +124,14 @@ export interface SiteData<ThemeConfig = any> {
| string[]
| { selector: string | string[]; padding: number }
locales: LocaleConfig<ThemeConfig>
/**
* If a page isn't found in the current language, allow switching to another language as a backup.
*/
localesFallback?: boolean
/**
* Use a custom locale key to be used as a default fallback for all locales. Default is root.
*/
localesDefaultFallback?: string
localeIndex?: string
contentProps?: Record<string, any>
router: {
Expand Down Expand Up @@ -156,7 +164,14 @@ export interface LocaleSpecificConfig<ThemeConfig = any> {

export type LocaleConfig<ThemeConfig = any> = Record<
string,
LocaleSpecificConfig<ThemeConfig> & { label: string; link?: string }
LocaleSpecificConfig<ThemeConfig> & {
label: string
link?: string
/**
* If the requested page isn't found in this language, switch to the same page in the specified language as a backup.
*/
fallback?: string
}
>

// Manually declaring all properties as rollup-plugin-dts
Expand Down