2021-07-21 18:12:33 +02:00
|
|
|
export interface PathLocale {
|
|
|
|
detectedLocale?: string
|
|
|
|
pathname: string
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* For a pathname that may include a locale from a list of locales, it
|
|
|
|
* removes the locale from the pathname returning it alongside with the
|
|
|
|
* detected locale.
|
|
|
|
*
|
|
|
|
* @param pathname A pathname that may include a locale.
|
|
|
|
* @param locales A list of locales.
|
|
|
|
* @returns The detected locale and pathname without locale
|
|
|
|
*/
|
2020-10-07 23:11:01 +02:00
|
|
|
export function normalizeLocalePath(
|
|
|
|
pathname: string,
|
|
|
|
locales?: string[]
|
2021-07-21 18:12:33 +02:00
|
|
|
): PathLocale {
|
2020-10-07 23:11:01 +02:00
|
|
|
let detectedLocale: string | undefined
|
2020-10-08 13:12:17 +02:00
|
|
|
// first item will be empty string from splitting at first char
|
|
|
|
const pathnameParts = pathname.split('/')
|
|
|
|
|
2020-10-07 23:11:01 +02:00
|
|
|
;(locales || []).some((locale) => {
|
2021-11-15 18:33:21 +01:00
|
|
|
if (
|
|
|
|
pathnameParts[1] &&
|
|
|
|
pathnameParts[1].toLowerCase() === locale.toLowerCase()
|
|
|
|
) {
|
2020-10-07 23:11:01 +02:00
|
|
|
detectedLocale = locale
|
2020-10-08 13:12:17 +02:00
|
|
|
pathnameParts.splice(1, 1)
|
|
|
|
pathname = pathnameParts.join('/') || '/'
|
2020-10-07 23:11:01 +02:00
|
|
|
return true
|
|
|
|
}
|
|
|
|
return false
|
|
|
|
})
|
|
|
|
|
|
|
|
return {
|
|
|
|
pathname,
|
|
|
|
detectedLocale,
|
|
|
|
}
|
|
|
|
}
|