Commit 4df3d7e0 authored by Jimmy Lai's avatar Jimmy Lai

Simplify generateMarkdown helpers

parent 331d26a3
......@@ -142,14 +142,12 @@ Use `generateMarkdown` when you want to wrap, replace, or post-process the defau
<AppOnly>
Pages receive the same props as the route component, plus a `renderDefault` helper:
Pages receive the same props as the route component, plus the default serialized `content`:
```jsx filename="app/products/[id]/page.js"
export const markdown = true
export async function generateMarkdown(props, { renderDefault }) {
const content = await renderDefault()
export function generateMarkdown(props, { content }) {
return ['# Product export', content].join('\n\n')
}
......@@ -158,13 +156,13 @@ export default function Page({ params }) {
}
```
Layouts can compose child Markdown with the `children` helper:
Layouts can compose child Markdown with the `children` value:
```jsx filename="app/products/layout.js"
export const markdown = true
export async function generateMarkdown(_props, { children }) {
return ['catalog-start', await children, 'catalog-end'].join('\n')
export function generateMarkdown(_props, { children }) {
return ['catalog-start', children, 'catalog-end'].join('\n')
}
export default function Layout({ children }) {
......@@ -181,9 +179,7 @@ Pages receive a `context` object containing the resolved page props and query:
```jsx filename="pages/products/[id].js"
export const markdown = true
export async function generateMarkdown(context, { renderDefault }) {
const content = await renderDefault()
export function generateMarkdown(context, { content }) {
return [
`product:${context.props.product.id}`,
`query:${context.query.id}`,
......
......@@ -36,11 +36,9 @@ export const markdown = true
export async function generateMarkdown(
props: PageProps<'/blog/[slug]'>,
helpers: { renderDefault(): Promise<string> }
helpers: { content: string }
) {
const content = await helpers.renderDefault()
return ['# Blog export', content].join('\n\n')
return ['# Blog export', helpers.content].join('\n\n')
}
export default function Page() {
......@@ -51,9 +49,7 @@ export default function Page() {
```jsx filename="app/blog/[slug]/page.js" switcher
export const markdown = true
export async function generateMarkdown(props, { renderDefault }) {
const content = await renderDefault()
export function generateMarkdown(props, { content }) {
return ['# Blog export', content].join('\n\n')
}
......@@ -62,13 +58,13 @@ export default function Page() {
}
```
Layouts also receive a `children` helper containing the Markdown generated by nested segments:
Layouts also receive `children`, which contains the Markdown generated by nested segments:
```jsx filename="app/blog/layout.js"
export const markdown = true
export async function generateMarkdown(_props, { children }) {
return ['layout-start', await children, 'layout-end'].join('\n')
export function generateMarkdown(_props, { children }) {
return ['layout-start', children, 'layout-end'].join('\n')
}
export default function Layout({ children }) {
......@@ -79,8 +75,8 @@ export default function Layout({ children }) {
#### Parameters
- `props`: The same props passed to the route segment during rendering.
- `helpers.renderDefault()`: Returns the default Markdown for the current segment.
- `helpers.children`: Layout-only helper that resolves to the Markdown generated by child segments.
- `helpers.content`: The default Markdown for the current segment.
- `helpers.children`: Layout-only Markdown generated by child segments.
</AppOnly>
......@@ -98,11 +94,9 @@ export async function generateMarkdown(
props: { title: string }
query: { slug?: string | string[] }
},
helpers: { renderDefault(): Promise<string> }
helpers: { content: string }
) {
const content = await helpers.renderDefault()
return [`title:${context.props.title}`, content].join('\n')
return [`title:${context.props.title}`, helpers.content].join('\n')
}
export default function Page({ title }: { title: string }) {
......@@ -113,9 +107,7 @@ export default function Page({ title }: { title: string }) {
```jsx filename="pages/blog/[slug].js" switcher
export const markdown = true
export async function generateMarkdown(context, { renderDefault }) {
const content = await renderDefault()
export function generateMarkdown(context, { content }) {
return [`title:${context.props.title}`, content].join('\n')
}
......@@ -128,7 +120,7 @@ export default function Page({ title }) {
- `context.props`: The resolved page props.
- `context.query`: The request query, including dynamic route params.
- `helpers.renderDefault()`: Returns the default Markdown for the page.
- `helpers.content`: The default Markdown for the page.
</PagesOnly>
......@@ -147,7 +139,7 @@ export default function Page({ title }) {
- In Pages Router, `generateMarkdown` is supported in pages only. `_app` and `_document` are not part of Markdown generation.
- `generateMarkdown` is not supported in the Edge runtime.
- If you do not export `generateMarkdown`, Next.js uses the default serializer.
- `helpers.renderDefault()` uses the currently merged Markdown component overrides for that segment.
- `helpers.content` uses the currently merged Markdown component overrides for that segment.
## Version History
......
......@@ -143,8 +143,8 @@ export type MarkdownSegmentDefinition = {
render?: (
props: any,
helpers: {
children: Promise<string>
renderDefault: () => Promise<string>
content: string
children: string
}
) => string | Promise<string> | null | undefined
}
......@@ -518,9 +518,6 @@ export async function renderHtmlToMarkdown(
components: mergedComponents,
}
const renderDefault = async () =>
serializeBlocks(node.childNodes, segmentState)
const childrenPromise = Promise.all(
getDirectChildSegments(node.childNodes).map((child) =>
composeSegment(child, segmentState)
......@@ -528,16 +525,21 @@ export async function renderHtmlToMarkdown(
).then((children) => children.filter(Boolean).join('\n\n'))
const promise = (async () => {
const [content, children] = await Promise.all([
serializeBlocks(node.childNodes, segmentState),
childrenPromise,
])
if (typeof segment.render === 'function') {
const result = await segment.render(segment.props, {
children: childrenPromise,
renderDefault,
content,
children,
})
return result == null ? '' : String(result).trim()
}
return renderDefault()
return content
})()
segmentCache.set(segmentId, promise)
......
......@@ -62,6 +62,14 @@ type SegmentParams<T extends Object = any> = T extends Record<string, any>
? { [K in keyof T]: T[K] extends string ? string | string[] | undefined : never }
: T
type MarkdownPageHelpers = {
content: string
}
type MarkdownLayoutHelpers = MarkdownPageHelpers & {
children: string
}
// Check that the entry is a valid entry
checkFields<Diff<{
${
......@@ -161,7 +169,9 @@ if ('generateMarkdown' in entry) {
checkFields<Diff<${
options.type === 'page' ? 'PageProps' : 'LayoutProps'
}, FirstArg<MaybeField<TEntry, 'generateMarkdown'>>, 'generateMarkdown'>>()
checkFields<Diff<any, SecondArg<MaybeField<TEntry, 'generateMarkdown'>>, 'generateMarkdown'>>()
checkFields<Diff<${
options.type === 'page' ? 'MarkdownPageHelpers' : 'MarkdownLayoutHelpers'
}, SecondArg<MaybeField<TEntry, 'generateMarkdown'>>, 'generateMarkdown'>>()
}
// Check the arguments and return type of the generateViewport function
......
......@@ -2768,7 +2768,7 @@ async function renderToHTMLOrFlightImpl(
formState,
postponedState,
metadata,
devFallbackParams
fallbackParams
)
return createMarkdownRenderResult(ctx, metadata, markdown)
......
......@@ -496,6 +496,18 @@ export function generateValidatorFile(
// Build type definitions based on what's actually used
let typeDefinitions = ''
if (appPageValidations || layoutValidations || pagesRouterPageValidations) {
typeDefinitions += `type MarkdownPageHelpers = {
content: string
}
type MarkdownLayoutHelpers = MarkdownPageHelpers & {
children: string
}
`
}
if (appPageValidations) {
typeDefinitions += `type AppPageConfig<Route extends AppRoutes = AppRoutes> = {
default: React.ComponentType<{ params: Promise<ParamMap[Route]> } & any> | ((props: { params: Promise<ParamMap[Route]> } & any) => React.ReactNode | Promise<React.ReactNode> | never | void | Promise<void>)
......@@ -506,7 +518,7 @@ export function generateValidatorFile(
) => Promise<any> | any
generateMarkdown?: (
props: { params: Promise<ParamMap[Route]> } & any,
parent: any
helpers: MarkdownPageHelpers
) => Promise<any> | any
generateViewport?: (
props: { params: Promise<ParamMap[Route]> } & any,
......@@ -527,7 +539,7 @@ export function generateValidatorFile(
getStaticPaths?: (context: any) => Promise<any> | any
getServerSideProps?: (context: any) => Promise<any> | any
getInitialProps?: (context: any) => Promise<any> | any
generateMarkdown?: (...args: any[]) => Promise<any> | any
generateMarkdown?: (context: any, helpers: MarkdownPageHelpers) => Promise<any> | any
markdown?: any
/**
* Segment configuration for legacy Pages Router pages.
......@@ -553,7 +565,7 @@ export function generateValidatorFile(
) => Promise<any> | any
generateMarkdown?: (
props: { params: Promise<ParamMap[Route]> } & any,
parent: any
helpers: MarkdownLayoutHelpers
) => Promise<any> | any
generateViewport?: (
props: { params: Promise<ParamMap[Route]> } & any,
......@@ -743,6 +755,18 @@ export function generateValidatorFileStrict(
// Build type definitions based on what's actually used
let typeDefinitions = ''
if (appPageValidations || layoutValidations || pagesRouterPageValidations) {
typeDefinitions += `type MarkdownPageHelpers = {
content: string
}
type MarkdownLayoutHelpers = MarkdownPageHelpers & {
children: string
}
`
}
if (appPageValidations) {
typeDefinitions += `type AppPageConfig<Route extends AppRoutes = AppRoutes> = {
default: React.JSXElementConstructor<PageProps<Route>>
......@@ -753,7 +777,7 @@ export function generateValidatorFileStrict(
) => Promise<any> | any
generateMarkdown?: (
props: { params: Promise<ParamMap[Route]> } & any,
parent: any
helpers: MarkdownPageHelpers
) => Promise<any> | any
generateViewport?: (
props: PageProps<Route>,
......@@ -774,7 +798,7 @@ export function generateValidatorFileStrict(
getStaticPaths?: (context: any) => Promise<any> | any
getServerSideProps?: (context: any) => Promise<any> | any
getInitialProps?: (context: any) => Promise<any> | any
generateMarkdown?: (...args: any[]) => Promise<any> | any
generateMarkdown?: (context: any, helpers: MarkdownPageHelpers) => Promise<any> | any
markdown?: any
/**
* Segment configuration for legacy Pages Router pages.
......@@ -800,7 +824,7 @@ export function generateValidatorFileStrict(
) => Promise<any> | any
generateMarkdown?: (
props: { params: Promise<ParamMap[Route]> } & any,
parent: any
helpers: MarkdownLayoutHelpers
) => Promise<any> | any
generateViewport?: (
props: { params: Promise<ParamMap[Route]> } & any,
......
......@@ -175,8 +175,8 @@ describe('markdown renderer', () => {
return `layout:${children}`
},
},
async render(_props, { children }) {
return `layout-start\n${await children}\nlayout-end`
render(_props, { children }) {
return `layout-start\n${children}\nlayout-end`
},
},
],
......@@ -190,8 +190,8 @@ describe('markdown renderer', () => {
return `page:${children}`
},
},
render(_props, { renderDefault }) {
return renderDefault()
render(_props, { content }) {
return content
},
},
],
......
......@@ -1312,14 +1312,14 @@ export async function renderToHTMLImpl(
props: {},
components: markdownConfig.components,
render: generateMarkdown
? async (pageProps, { renderDefault }) =>
? async (pageProps, { content }) =>
generateMarkdown(
{
props: pageProps,
query,
},
{
renderDefault,
content,
}
)
: undefined,
......
......@@ -72,7 +72,7 @@ export type PagesUserlandModule = {
*/
readonly generateMarkdown?: (
context: { props: any; query: ParsedUrlQuery },
helpers: { renderDefault(): Promise<string> }
helpers: { content: string }
) => Promise<string> | string
}
......
......@@ -6,8 +6,8 @@ export const markdown = {
},
}
export async function generateMarkdown(_props, { children }) {
return `inner-start\n${await children}\ninner-end`
export function generateMarkdown(_props, { children }) {
return `inner-start\n${children}\ninner-end`
}
export default function InnerLayout({ children }) {
......
......@@ -7,8 +7,8 @@ export const markdown = {
}
export const dynamic = 'force-dynamic'
export async function generateMarkdown(_props, { renderDefault }) {
return renderDefault()
export function generateMarkdown(_props, { content }) {
return content
}
export default function AppComposedPage() {
......
......@@ -6,8 +6,8 @@ export const markdown = {
},
}
export async function generateMarkdown(_props, { children }) {
return `outer-start\n${await children}\nouter-end`
export function generateMarkdown(_props, { children }) {
return `outer-start\n${children}\nouter-end`
}
export default function OuterLayout({ children }) {
......
......@@ -8,14 +8,12 @@ export async function getServerSideProps(context) {
}
}
export async function generateMarkdown(context, { renderDefault }) {
const defaultMarkdown = await renderDefault()
export function generateMarkdown(context, { content }) {
return [
'custom-start',
`message:${context.props.message}`,
`query:${context.query.id}`,
`default:${defaultMarkdown}`,
`default:${content}`,
'custom-end',
].join('\n')
}
......
......@@ -6,8 +6,8 @@ export function getServerSideProps() {
}
}
export async function generateMarkdown(_context, { renderDefault }) {
return renderDefault()
export function generateMarkdown(_context, { content }) {
return content
}
export default function Page(props) {
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment