Core: Support generating static params automatically with Source API

This commit is contained in:
fuma-nama
2024-09-05 19:09:30 +08:00
parent b33aff0bc8
commit daa66d248e
3 changed files with 37 additions and 2 deletions
+5
View File
@@ -0,0 +1,5 @@
---
'fumadocs-core': patch
---
Support generating static params automatically with Source API
+6 -2
View File
@@ -16,6 +16,11 @@ export interface VirtualFile {
*/
path: string;
type: 'page' | 'meta';
/**
* Specified Slugs for page
*/
slugs?: string[];
data: unknown;
}
@@ -37,8 +42,7 @@ export function loadFiles(files: VirtualFile[], options: LoadOptions): Storage {
const relativePath = normalizedPath.slice(rootDir.length);
if (file.type === 'page') {
const parsedPath = parseFilePath(relativePath);
const slugs = options.getSlugs(parsedPath);
const slugs = file.slugs ?? options.getSlugs(parseFilePath(relativePath));
storage.write(relativePath, file.type, {
slugs,
+26
View File
@@ -115,6 +115,17 @@ export interface LoaderOutput<Config extends LoaderConfig> {
slugs: string[] | undefined,
language?: string,
) => Page<Config['source']['pageData']> | undefined;
/**
* generate static params for Next.js SSG
*/
generateParams: <
TSlug extends string = 'slug',
TLang extends string = 'lang',
>(
slug?: TSlug,
lang?: TLang,
) => (Record<TSlug, string[]> & Record<TLang, string>)[];
}
function buildPageMap(
@@ -259,6 +270,21 @@ function createOutput({
getPage(slugs = [], language = i18n?.defaultLanguage ?? '') {
return i18nMap.get(language)?.get(slugs.join('/'));
},
// @ts-expect-error -- ignore this
generateParams(slug, lang) {
if (i18n) {
return this.getLanguages().flatMap((entry) =>
entry.pages.map((page) => ({
[slug ?? 'slug']: page.slugs,
[lang ?? 'lang']: entry.language,
})),
);
}
return Array.from(i18nMap.get('')?.values() ?? []).map((page) => ({
[slug ?? 'slug']: page.slugs,
}));
},
};
}