Skip to content

Commit b056a20

Browse files
committed
feat: enhance MDXContent component with improved relative link handling
1 parent 82c311a commit b056a20

1 file changed

Lines changed: 24 additions & 9 deletions

File tree

app/[...slug]/page.tsx

Lines changed: 24 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,10 @@ export default async function Page(props: {
2929
<DocsDescription>{page.data.description}</DocsDescription>
3030
<DocsBody>
3131
<MDXContent
32-
components={getMDXComponents()}
32+
components={getMDXComponents({
33+
// this allows you to link to other pages with relative file paths
34+
a: createRelativeLinkWithFilenameOnly(source, page),
35+
})}
3336
/>
3437
</DocsBody>
3538
</DocsPage>
@@ -53,16 +56,28 @@ export async function generateMetadata(props: {
5356
};
5457
}
5558

59+
type InferSource = typeof source;
60+
type InferPage = NonNullable<ReturnType<typeof source.getPage>>;
61+
5662
function createRelativeLinkWithFilenameOnly(
57-
source: LoaderOutput<LoaderConfig>,
58-
page: Page,
63+
sourceInst: InferSource,
64+
page: InferPage,
5965
): FC<ComponentProps<'a'>> {
60-
return async function RelativeLink({href, ...props}) {
61-
const relativeLink = createRelativeLink(source, page)
62-
// support filename-only links
63-
if (href && (!href.startsWith('http') && href.endsWith('.md'))) {
64-
return relativeLink({href: `./${href}`, ...props});
66+
const RelativeLinkBase = createRelativeLink(sourceInst, page);
67+
68+
return function RelativeLink({ href, ...props }) {
69+
if (!href || href.startsWith('http')) {
70+
return <RelativeLinkBase {...props} href={href} />;
6571
}
66-
return relativeLink({href, ...props});
72+
73+
let finalHref = href;
74+
75+
const [path, hash] = href.split('#');
76+
77+
if (path.endsWith('.md')) {
78+
finalHref = `./${path}${hash ? `#${hash.toLowerCase()}` : ''}`;
79+
}
80+
81+
return <RelativeLinkBase {...props} href={finalHref} />;
6782
};
6883
}

0 commit comments

Comments
 (0)