78 lines
2.9 KiB
JavaScript
78 lines
2.9 KiB
JavaScript
import { isValidLocale } from './helpers.js';
|
|
/**
|
|
* Builds a locale-prefixed path for a document in a target locale.
|
|
*
|
|
* Always prefixes the locale: /{locale} or /{locale}/{slug}. The home slug
|
|
* collapses to the locale root. Returns undefined if the document has no slug
|
|
* in the target locale (caller decides fallback behavior).
|
|
*
|
|
* @example
|
|
* buildLocalizedPath({ slugs: { pl: 'strona-glowna', en: 'home' }, locale: 'en', config })
|
|
* // → '/en' (home slug collapses to root)
|
|
*
|
|
* buildLocalizedPath({ slugs: { pl: 'o-nas', en: 'about' }, locale: 'en', config })
|
|
* // → '/en/about'
|
|
*
|
|
* buildLocalizedPath({
|
|
* slugs: { pl: 'moj-post', en: 'my-post' },
|
|
* prefix: { pl: 'artykuly', en: 'articles' },
|
|
* locale: 'en',
|
|
* config,
|
|
* })
|
|
* // → '/en/articles/my-post'
|
|
*/ export function buildLocalizedPath({ config, homeSlug = 'home', locale, prefix, slugs }) {
|
|
if (!isValidLocale(locale, config)) {
|
|
return undefined;
|
|
}
|
|
const slug = slugs[locale];
|
|
if (!slug) {
|
|
return undefined;
|
|
}
|
|
// Single-locale sites have no /pl, /en prefix — the language segment is
|
|
// dropped entirely (path is /o-nas, not /pl/o-nas). Detected automatically:
|
|
// one configured locale means one language, so no prefix is needed. The
|
|
// project's folder structure matches (app/[[...slug]] without [locale]).
|
|
const singleLocale = config.locales.length === 1;
|
|
const localeSegment = singleLocale ? '' : `/${locale}`;
|
|
if (prefix) {
|
|
const segment = prefix[locale];
|
|
// No archive slug in this locale means the entry is unreachable there —
|
|
// there's no path to point at, so hreflang should omit it rather than
|
|
// invent /en/moj-post.
|
|
if (!segment) {
|
|
return undefined;
|
|
}
|
|
return `${localeSegment}/${segment}/${slug}`;
|
|
}
|
|
if (slug === homeSlug) {
|
|
// Home collapses to the root: '/' for single-locale, '/pl' otherwise.
|
|
return localeSegment || '/';
|
|
}
|
|
return `${localeSegment}/${slug}`;
|
|
}
|
|
/**
|
|
* Resolves the equivalent path for the same document in a different locale —
|
|
* the language-switcher use case (/pl/strona-glowna → /en/home).
|
|
*
|
|
* Never dead-ends on a 404. When the document has no slug in the target locale,
|
|
* falls back to the archive it belongs to (/en/articles) if there is one, and
|
|
* to the locale root otherwise — the closest place the visitor would want.
|
|
*/ export function switchLocalePath({ config, homeSlug = 'home', prefix, slugs, targetLocale }) {
|
|
const path = buildLocalizedPath({
|
|
config,
|
|
homeSlug,
|
|
locale: targetLocale,
|
|
prefix,
|
|
slugs
|
|
});
|
|
if (path) {
|
|
return path;
|
|
}
|
|
const archiveSegment = prefix?.[targetLocale];
|
|
if (archiveSegment) {
|
|
return `/${targetLocale}/${archiveSegment}`;
|
|
}
|
|
return `/${targetLocale}`;
|
|
}
|
|
|
|
//# sourceMappingURL=localizedPath.js.map
|