Skip to content

Commit 3feb355

Browse files
fix(jsx): allow a function component to return an array (#5179)
* fix(jsx): allow a function component to return an array A function component returning an array threw "str.search is not a function" during server-side rendering. The return value did not match any branch in JSXFunctionNode.toStringToBuffer() and fell through to escapeToBuffer(), which expects a string. Handle arrays with childrenToStringToBuffer(), the same path already used for array children. JSX.ElementType is also added so that the type layer accepts components returning any renderable value, matching what hono/jsx/dom already supports at runtime. * fix(jsx): accept an array return in the type layer The runtime already renders a function component that returns an array, but the type layer still rejected it. Add `Child[]` to the call signature of `FC`, and define `JSX.ElementType` with the same return type. Without `JSX.ElementType`, TypeScript checks the return type against `JSX.Element` and reports TS2786. Both types now accept exactly the same set of return values, so nothing beyond arrays becomes newly valid. * fix(jsx): render an array resolved from a promise An async function component returning an array produced escaped, comma-joined text instead of markup, because the resolved array reached the string buffer as-is and was stringified by `String()`. Wrap a resolved array in a fragment so it is rendered like any other node. `Child` now carries `Promise<string | Child[]>`, which surfaced the same hole for children: a child promise resolving to an array took the same path. Both call sites share `resolveArrayToFragment()`, which also attaches the suspended context, so the promise branch of `JSXFunctionNode` no longer needs its own `then()` chain. * fix(jsx): scope promised arrays to component results * fix(jsx-renderer): accept array component results * fix(jsx): preserve callbacks in component arrays * refactor(jsx): remove obsolete suspended context state --------- Co-authored-by: Taku Amano <[email protected]>
1 parent 5d911d2 commit 3feb355

8 files changed

Lines changed: 239 additions & 26 deletions

File tree

‎src/jsx/base.ts‎

Lines changed: 41 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -25,8 +25,13 @@ import {
2525

2626
// eslint-disable-next-line @typescript-eslint/no-explicit-any
2727
export type Props = Record<string, any>
28+
type FunctionComponentResult =
29+
| HtmlEscapedString
30+
| Child[]
31+
| Promise<HtmlEscapedString | Child[]>
32+
| null
2833
export type FC<P = Props> = {
29-
(props: P): HtmlEscapedString | Promise<HtmlEscapedString> | null
34+
(props: P): FunctionComponentResult
3035
defaultProps?: Partial<P> | undefined
3136
displayName?: string | undefined
3237
}
@@ -35,6 +40,7 @@ export type DOMAttributes = HonoJSX.HTMLAttributes
3540
// eslint-disable-next-line @typescript-eslint/no-namespace
3641
export namespace JSX {
3742
export type Element = HtmlEscapedString | Promise<HtmlEscapedString>
43+
export type ElementType = string | ((props: never) => FunctionComponentResult)
3844
export interface ElementChildrenAttribute {
3945
children: Child
4046
}
@@ -105,6 +111,27 @@ export const booleanAttributes = [
105111
'selected',
106112
]
107113

114+
type SuspendedContext = <T>(callback: () => T) => T
115+
116+
const resolveFunctionComponentResult = (
117+
result: Promise<string | JSXNode | Child[]>,
118+
suspendedContext?: SuspendedContext
119+
): Promise<string> =>
120+
result.then((resolved) => {
121+
if (!Array.isArray(resolved) && !(resolved instanceof JSXNode)) {
122+
return resolved
123+
}
124+
const children = Array.isArray(resolved) ? resolved : [resolved]
125+
const render = () => {
126+
const buffer: StringBufferWithCallbacks = [''] as StringBufferWithCallbacks
127+
childrenToStringToBuffer(children, buffer)
128+
return buffer.length === 1
129+
? raw(buffer[0], buffer.callbacks)
130+
: stringBufferToString(buffer, buffer.callbacks)
131+
}
132+
return suspendedContext ? suspendedContext(render) : runWithRenderContext(render)
133+
})
134+
108135
const childrenToStringToBuffer = (children: Child[], buffer: StringBufferWithCallbacks): void => {
109136
for (let i = 0, len = children.length; i < len; i++) {
110137
const child = children[i]
@@ -114,11 +141,15 @@ const childrenToStringToBuffer = (children: Child[], buffer: StringBufferWithCal
114141
continue
115142
} else if (child instanceof JSXNode) {
116143
child.toStringToBuffer(buffer)
117-
} else if (
118-
typeof child === 'number' ||
119-
(child as unknown as { isEscaped: boolean }).isEscaped
120-
) {
144+
} else if (typeof child === 'number') {
121145
;(buffer[0] as string) += child
146+
} else if ((child as unknown as HtmlEscaped).isEscaped) {
147+
;(buffer[0] as string) += child
148+
const callbacks = (child as unknown as HtmlEscapedString).callbacks
149+
if (callbacks) {
150+
buffer.callbacks ||= []
151+
buffer.callbacks.push(...callbacks)
152+
}
122153
} else if (child instanceof Promise) {
123154
buffer.unshift('', child)
124155
} else {
@@ -143,7 +174,6 @@ export class JSXNode implements HtmlEscaped {
143174
key?: string
144175
children: Child[]
145176
isEscaped: true = true as const
146-
suspendedContext?: <T>(callback: () => T) => T
147177
constructor(tag: string | Function, props: Props, children: Child[]) {
148178
if (typeof tag !== 'function' && !isValidTagName(tag)) {
149179
throw new Error(`Invalid JSX tag name: ${tag}`)
@@ -173,7 +203,7 @@ export class JSXNode implements HtmlEscaped {
173203
: buffer[0]
174204
: stringBufferToString(buffer, buffer.callbacks)
175205
}
176-
return this.suspendedContext ? this.suspendedContext(render) : runWithRenderContext(render)
206+
return runWithRenderContext(render)
177207
}
178208

179209
toStringToBuffer(buffer: StringBufferWithCallbacks): void {
@@ -267,22 +297,15 @@ class JSXFunctionNode extends JSXNode {
267297
return
268298
} else if (res instanceof Promise) {
269299
if (globalContexts.length === 0) {
270-
buffer.unshift('', res)
300+
buffer.unshift('', resolveFunctionComponentResult(res))
271301
} else {
272302
// save the current context state for resuming the suspended subtree
273-
const suspendedContext = captureRenderContext()
274-
buffer.unshift(
275-
'',
276-
res.then((childRes) => {
277-
if (childRes instanceof JSXNode) {
278-
childRes.suspendedContext = suspendedContext
279-
}
280-
return childRes
281-
})
282-
)
303+
buffer.unshift('', resolveFunctionComponentResult(res, captureRenderContext()))
283304
}
284305
} else if (res instanceof JSXNode) {
285306
res.toStringToBuffer(buffer)
307+
} else if (Array.isArray(res)) {
308+
childrenToStringToBuffer(res, buffer)
286309
} else if (typeof res === 'number' || (res as HtmlEscaped).isEscaped) {
287310
buffer[0] += res
288311
if (res.callbacks) {

‎src/jsx/dom/index.test.tsx‎

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -374,6 +374,30 @@ describe('DOM', () => {
374374
expect(Child).toBeCalledTimes(3)
375375
})
376376

377+
it('returning an array', async () => {
378+
const App = () => {
379+
const [count, setCount] = useState(0)
380+
return [<div>{count}</div>, <button onClick={() => setCount(count + 1)}>+</button>]
381+
}
382+
render(<App />, root)
383+
expect(root.innerHTML).toBe('<div>0</div><button>+</button>')
384+
root.querySelector('button')?.click()
385+
await Promise.resolve()
386+
expect(root.innerHTML).toBe('<div>1</div><button>+</button>')
387+
})
388+
389+
it('typed as FC returning an array', async () => {
390+
const App: FC = () => {
391+
const [count, setCount] = useState(0)
392+
return [<div>{count}</div>, <button onClick={() => setCount(count + 1)}>+</button>]
393+
}
394+
render(<App />, root)
395+
expect(root.innerHTML).toBe('<div>0</div><button>+</button>')
396+
root.querySelector('button')?.click()
397+
await Promise.resolve()
398+
expect(root.innerHTML).toBe('<div>1</div><button>+</button>')
399+
})
400+
377401
it('multiple children', async () => {
378402
const Child = ({ name }: { name: string }) => {
379403
const [count, setCount] = useState(0)

‎src/jsx/dom/render.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -284,7 +284,7 @@ const invokeTag = (context: Context, node: NodeObject): Child[] => {
284284
}
285285
: node.props
286286
try {
287-
return [func.call(null, props)]
287+
return [func.call(null, props) as Child]
288288
} finally {
289289
buildDataStack.pop()
290290
}

‎src/jsx/index.test.tsx‎

Lines changed: 95 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
/** @jsxImportSource ./ */
22
/* eslint-disable @typescript-eslint/no-explicit-any */
3-
import { html } from '../helper/html'
3+
import { html, raw } from '../helper/html'
44
import { Hono } from '../hono'
55
import { DOM_MEMO } from './constants'
66
import { captureRenderContext } from './context'
@@ -172,6 +172,68 @@ describe('render to string', () => {
172172
expect(template.toString()).toBe('<p><span>a</span><span>b</span></p>')
173173
})
174174

175+
it('Component returning an array', () => {
176+
const Item = ({ x }: { x: number }) => <span>{x}</span>
177+
const Items = () => [0, 1].map((x) => <Item key={x} x={x} />)
178+
const template = <Items />
179+
expect(template.toString()).toBe('<span>0</span><span>1</span>')
180+
})
181+
182+
it('Component returning a nested array', () => {
183+
const Items = () => [['a', 'b'], [<span>c</span>], null]
184+
const template = <Items />
185+
expect(template.toString()).toBe('ab<span>c</span>')
186+
})
187+
188+
it('Component returning an array preserves escaped string callbacks', () => {
189+
const Items = () => [
190+
raw('a', [
191+
({ buffer }) => {
192+
if (buffer) {
193+
buffer[0] += 'b'
194+
}
195+
},
196+
]),
197+
]
198+
expect((<Items />).toString()).toBe('ab')
199+
})
200+
201+
it('Component returning an array escapes strings', async () => {
202+
const SyncItems = () => ['<script>alert(1)</script>']
203+
const AsyncItems = async () => ['<script>alert(1)</script>']
204+
const expected = '&lt;script&gt;alert(1)&lt;/script&gt;'
205+
206+
expect((<SyncItems />).toString()).toBe(expected)
207+
expect((await (<AsyncItems />).toString()).toString()).toBe(expected)
208+
})
209+
210+
it('Component returning an array including async components', async () => {
211+
const AsyncItem = async ({ x }: { x: number }) => <span>{x}</span>
212+
const Items = () => [0, 1].map((x) => <AsyncItem key={x} x={x} />)
213+
const template = <Items />
214+
expect((await template.toString()).toString()).toBe('<span>0</span><span>1</span>')
215+
})
216+
217+
it('Component typed as FC returning an array', () => {
218+
const Item: FC<{ x: number }> = ({ x }) => <span>{x}</span>
219+
const Items: FC = () => [0, 1].map((x) => <Item key={x} x={x} />)
220+
const template = <Items />
221+
expect(template.toString()).toBe('<span>0</span><span>1</span>')
222+
})
223+
224+
it('Async component returning an array', async () => {
225+
const AsyncItems = async () => [<span>a</span>, <span>b</span>]
226+
const template = <AsyncItems />
227+
expect((await template.toString()).toString()).toBe('<span>a</span><span>b</span>')
228+
})
229+
230+
it('Async component returning an array of async components', async () => {
231+
const AsyncItem = async ({ x }: { x: number }) => <span>{x}</span>
232+
const AsyncItems = async () => [<AsyncItem key={0} x={0} />, <AsyncItem key={1} x={1} />]
233+
const template = <AsyncItems />
234+
expect((await template.toString()).toString()).toBe('<span>0</span><span>1</span>')
235+
})
236+
175237
it('Empty elements are rended without closing tag', () => {
176238
const template = <input />
177239
expect(template.toString()).toBe('<input/>')
@@ -1252,6 +1314,38 @@ d.replaceWith(c.content)
12521314
expect((await template.toString()).toString()).toBe('<span>dark</span>')
12531315
})
12541316

1317+
it('returning an array', async () => {
1318+
const ArrayConsumer = async () => {
1319+
await new Promise((resolve) => setTimeout(resolve, 10))
1320+
return [<span>{useContext(ThemeContext)}</span>, <span>x</span>]
1321+
}
1322+
const template = (
1323+
<ThemeContext.Provider value='dark'>
1324+
<ArrayConsumer />
1325+
</ThemeContext.Provider>
1326+
)
1327+
expect((await template.toString()).toString()).toBe('<span>dark</span><span>x</span>')
1328+
})
1329+
1330+
it('isolates a shared async result between providers', async () => {
1331+
const sharedResult = Promise.resolve(<Consumer />)
1332+
const SharedConsumer = () => sharedResult
1333+
const [dark, black] = await Promise.all([
1334+
(
1335+
<ThemeContext.Provider value='dark'>
1336+
<SharedConsumer />
1337+
</ThemeContext.Provider>
1338+
).toString(),
1339+
(
1340+
<ThemeContext.Provider value='black'>
1341+
<SharedConsumer />
1342+
</ThemeContext.Provider>
1343+
).toString(),
1344+
])
1345+
expect(dark.toString()).toBe('<span>dark</span>')
1346+
expect(black.toString()).toBe('<span>black</span>')
1347+
})
1348+
12551349
it('nested', async () => {
12561350
const template = (
12571351
<ThemeContext.Provider value='dark'>

‎src/jsx/intrinsic-element/components.test.tsx‎

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
/** @jsxImportSource ../ */
22
import { useActionState } from '../'
3+
import { HtmlEscapedCallbackPhase, resolveCallback } from '../../utils/html'
34

45
describe('intrinsic element', () => {
56
describe('document metadata', () => {
@@ -18,6 +19,23 @@ describe('intrinsic element', () => {
1819
'<html><head><title>Hello</title></head><body><h1>World</h1></body></html>'
1920
)
2021
})
22+
23+
it('should hoist a title from an async component array', async () => {
24+
const Metadata = async () => [<title>Hello</title>]
25+
const template = (
26+
<html>
27+
<head></head>
28+
<body>
29+
<Metadata />
30+
<h1>World</h1>
31+
</body>
32+
</html>
33+
)
34+
const rendered = await template.toString()
35+
expect(await resolveCallback(rendered, HtmlEscapedCallbackPhase.Stringify, false, {})).toBe(
36+
'<html><head><title>Hello</title></head><body><h1>World</h1></body></html>'
37+
)
38+
})
2139
})
2240

2341
describe('link element', () => {

‎src/jsx/streaming.test.tsx‎

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,46 @@ describe('Streaming', () => {
3030
suspenseCounter++
3131
})
3232

33+
it('Suspense / async component returning an array', async () => {
34+
const Content = async () => {
35+
await new Promise((resolve) => setTimeout(resolve, 10))
36+
return [<h1>Hello</h1>, <h2>World</h2>]
37+
}
38+
39+
const stream = renderToReadableStream(
40+
<Suspense fallback={<p>Loading...</p>}>
41+
<Content />
42+
</Suspense>
43+
)
44+
45+
const chunks = []
46+
const textDecoder = new TextDecoder()
47+
for await (const chunk of stream as any) {
48+
chunks.push(textDecoder.decode(chunk))
49+
}
50+
51+
expect(chunks[0]).toBe(
52+
`<template id="H:${suspenseCounter}"></template><p>Loading...</p><!--/$-->`
53+
)
54+
expect(chunks[1]).toContain(
55+
`<template data-hono-target="H:${suspenseCounter}"><h1>Hello</h1><h2>World</h2></template>`
56+
)
57+
})
58+
59+
it('preserves callbacks in a streamed async component array', async () => {
60+
const phases: number[] = []
61+
const Content = async () => [
62+
raw('Hello', [({ phase }) => void phases.push(phase)]),
63+
<span>World</span>,
64+
]
65+
66+
const html = await drainStream(renderToReadableStream(<Content />))
67+
68+
expect(html).toBe('Hello<span>World</span>')
69+
expect(phases).toEqual([HtmlEscapedCallbackPhase.BeforeStream, HtmlEscapedCallbackPhase.Stream])
70+
suspenseCounter--
71+
})
72+
3373
it('Suspense / renderToReadableStream', async () => {
3474
let contentEvaluatedCount = 0
3575
const Content = () => {

‎src/middleware/jsx-renderer/index.test.tsx‎

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -55,6 +55,22 @@ describe('JSX renderer', () => {
5555
)
5656
})
5757

58+
it('accepts an array result', async () => {
59+
const app = new Hono()
60+
app.use(jsxRenderer(({ children }) => [<header>Header</header>, <main>{children}</main>]))
61+
app.get('/', (c) => c.render(<h1>Hello</h1>, { title: 'Hello' }))
62+
63+
const res = await app.request('/')
64+
expect(await res.text()).toBe(
65+
'<!DOCTYPE html><header>Header</header><main><h1>Hello</h1></main>'
66+
)
67+
})
68+
69+
it('does not accept a null result', () => {
70+
// @ts-expect-error A JSX renderer component must produce renderable content.
71+
jsxRenderer(() => null)
72+
})
73+
5874
it('Should get the context object as a 2nd arg', async () => {
5975
const app = new Hono()
6076
app.use(

‎src/middleware/jsx-renderer/index.ts‎

Lines changed: 4 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,6 @@ import { Fragment, createContext, jsx, useContext } from '../../jsx'
1010
import type { FC, Context as JSXContext, JSXNode, PropsWithChildren } from '../../jsx'
1111
import { renderToReadableStream } from '../../jsx/streaming'
1212
import type { Env, Input, MiddlewareHandler } from '../../types'
13-
import type { HtmlEscapedString } from '../../utils/html'
1413

1514
export const RequestContext: JSXContext<Context<any, any, {}> | null> =
1615
createContext<Context | null>(null)
@@ -20,15 +19,14 @@ type RendererOptions = {
2019
stream?: boolean | Record<string, string>
2120
}
2221

23-
type Component = (
24-
props: PropsForRenderer & { Layout: FC },
25-
c: Context
26-
) => HtmlEscapedString | Promise<HtmlEscapedString>
22+
type ComponentResult = Exclude<ReturnType<FC>, null>
23+
24+
type Component = (props: PropsForRenderer & { Layout: FC }, c: Context) => ComponentResult
2725

2826
type ComponentWithChildren = (
2927
props: PropsWithChildren<PropsForRenderer & { Layout: FC }>,
3028
c: Context
31-
) => HtmlEscapedString | Promise<HtmlEscapedString>
29+
) => ComponentResult
3230

3331
const createRenderer =
3432
(

0 commit comments

Comments
 (0)