Core & UI: Improve createRelativeLink and getPageByHref for i18n usage

This commit is contained in:
Fuma Nama
2025-05-22 17:37:51 +08:00
parent ef944c99b4
commit 7d78bc5bc4
3 changed files with 23 additions and 16 deletions
+6
View File
@@ -0,0 +1,6 @@
---
'fumadocs-core': patch
'fumadocs-ui': patch
---
Improve `createRelativeLink` and `getPageByHref` for i18n usage
+13 -15
View File
@@ -92,6 +92,8 @@ export interface LoaderOutput<Config extends LoaderConfig> {
getPageByHref: (
href: string,
options?: {
language?: string;
/**
* resolve relative file paths in `href` from specified dirname, must be a virtual path.
*/
@@ -299,30 +301,26 @@ function createOutput(options: LoaderOptions): LoaderOutput<LoaderConfig> {
set pageTree(v) {
pageTree = v;
},
getPageByHref(href, { dir = '' } = {}) {
const pages = Array.from(walker.pages.values());
getPageByHref(href, { dir = '', language } = {}) {
const pages = this.getPages(language);
const [value, hash] = href.split('#', 2);
let target;
if (
value.startsWith('.') &&
(value.endsWith('.md') || value.endsWith('.mdx'))
) {
const hrefPath = joinPath(dir, value);
const target = pages.find((item) => item.file.path === hrefPath);
if (target)
return {
page: target,
hash,
};
target = pages.find((item) => item.file.path === hrefPath);
} else {
target = pages.find((item) => item.url === value);
}
const target = pages.find((item) => item.url === value);
if (target)
return {
page: target,
hash,
};
if (!target) return;
return {
page: target,
hash,
};
},
getPages(language = options.i18n?.defaultLanguage ?? '') {
const pages: Page[] = [];
+4 -1
View File
@@ -17,7 +17,10 @@ export function createRelativeLink(
return async function RelativeLink({ href, ...props }) {
// resolve relative href
if (href && href.startsWith('.')) {
const target = source.getPageByHref(href, { dir: page.file.dirname });
const target = source.getPageByHref(href, {
dir: page.file.dirname,
language: page.locale,
});
if (target) {
href = target.hash