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