fix(jsx): allow a function component to return an array (#5179)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
* 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 ---------
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Trailers
- Co-authored-by: Taku Amano <taku@taaas.jp>
Diff stats
8 files+239 added−26 removed
- tests:+193 added−1 removed
- other:+46 added−25 removed
Provenance
- Commit
3feb355- Tree
c98beb8- Author
natsuki ueda <63272932+natsuki-engr@users.noreply.github.com>- Committer
GitHub <noreply@github.com>- Parent
5d911d2
8 files changed+239 added−26 removed
modified:src/jsx/dom/index.test.tsx+24 added
372 unmodified lines373 expect(root.innerHTML).toBe('<div>2</div><div>1</div><button>+</button>')374 expect(Child).toBeCalledTimes(3)375 })376 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+401 it('multiple children', async () => {402 const Child = ({ name }: { name: string }) => {403 const [count, setCount] = useState(0)404 return (2544 unmodified linesmodified:src/jsx/dom/render.ts+1 added-1 removed
282 unmodified lines283 ...node.props,284 }285 : node.props286 try {287- return [func.call(null, props)]287+ return [func.call(null, props) as Child]288 } finally {289 buildDataStack.pop()290 }291 }534 unmodified linesmodified:src/jsx/intrinsic-element/components.test.tsx+18 added
1 /** @jsxImportSource ../ */2 import { useActionState } from '../'3+import { HtmlEscapedCallbackPhase, resolveCallback } from '../../utils/html'4 5 describe('intrinsic element', () => {6 describe('document metadata', () => {7 describe('title element', () => {10 unmodified lines18 expect(template.toString()).toBe(19 '<html><head><title>Hello</title></head><body><h1>World</h1></body></html>'20 )21 })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+ })39 })40 41 describe('link element', () => {42 it('should be hoisted link tag', async () => {562 unmodified linesmodified:src/jsx/base.ts+41 added-18 removed
23 unmodified lines24 } from './utils'25 26 // eslint-disable-next-line @typescript-eslint/no-explicit-any27 export type Props = Record<string, any>28+type FunctionComponentResult =29+ | HtmlEscapedString30+ | Child[]31+ | Promise<HtmlEscapedString | Child[]>32+ | null33 export type FC<P = Props> = {29- (props: P): HtmlEscapedString | Promise<HtmlEscapedString> | null34+ (props: P): FunctionComponentResult35 defaultProps?: Partial<P> | undefined36 displayName?: string | undefined37 }38 export type DOMAttributes = HonoJSX.HTMLAttributes39 40 // eslint-disable-next-line @typescript-eslint/no-namespace41 export namespace JSX {42 export type Element = HtmlEscapedString | Promise<HtmlEscapedString>43+ export type ElementType = string | ((props: never) => FunctionComponentResult)44 export interface ElementChildrenAttribute {45 children: Child46 }47 export interface IntrinsicElements extends IntrinsicElementsDefined {62 unmodified lines110 'reversed',111 'selected',112 ]113 114+type SuspendedContext = <T>(callback: () => T) => T115+116+const resolveFunctionComponentResult = (117+ result: Promise<string | JSXNode | Child[]>,118+ suspendedContext?: SuspendedContext119+): Promise<string> =>120+ result.then((resolved) => {121+ if (!Array.isArray(resolved) && !(resolved instanceof JSXNode)) {122+ return resolved123+ }124+ const children = Array.isArray(resolved) ? resolved : [resolved]125+ const render = () => {126+ const buffer: StringBufferWithCallbacks = [''] as StringBufferWithCallbacks127+ childrenToStringToBuffer(children, buffer)128+ return buffer.length === 1129+ ? raw(buffer[0], buffer.callbacks)130+ : stringBufferToString(buffer, buffer.callbacks)131+ }132+ return suspendedContext ? suspendedContext(render) : runWithRenderContext(render)133+ })134+135 const childrenToStringToBuffer = (children: Child[], buffer: StringBufferWithCallbacks): void => {136 for (let i = 0, len = children.length; i < len; i++) {137 const child = children[i]138 if (typeof child === 'string') {1 unmodified line140 } else if (typeof child === 'boolean' || child === null || child === undefined) {141 continue142 } else if (child instanceof JSXNode) {143 child.toStringToBuffer(buffer)117- } else if (118- typeof child === 'number' ||119- (child as unknown as { isEscaped: boolean }).isEscaped120- ) {144+ } else if (typeof child === 'number') {145 ;(buffer[0] as string) += child146+ } else if ((child as unknown as HtmlEscaped).isEscaped) {147+ ;(buffer[0] as string) += child148+ const callbacks = (child as unknown as HtmlEscapedString).callbacks149+ if (callbacks) {150+ buffer.callbacks ||= []151+ buffer.callbacks.push(...callbacks)152+ }153 } else if (child instanceof Promise) {154 buffer.unshift('', child)155 } else {156 // `child` type is `Child[]`, so stringify recursively16 unmodified lines173 props: Props174 key?: string175 children: Child[]176 isEscaped: true = true as const146- suspendedContext?: <T>(callback: () => T) => T177 constructor(tag: string | Function, props: Props, children: Child[]) {178 if (typeof tag !== 'function' && !isValidTagName(tag)) {179 throw new Error(`Invalid JSX tag name: ${tag}`)180 }21 unmodified lines202 ? resolveCallbackSync(raw(buffer[0], buffer.callbacks)).toString()203 : buffer[0]204 : stringBufferToString(buffer, buffer.callbacks)205 }176- return this.suspendedContext ? this.suspendedContext(render) : runWithRenderContext(render)206+ return runWithRenderContext(render)207 }208 209 toStringToBuffer(buffer: StringBufferWithCallbacks): void {210 const tag = this.tag as string85 unmodified lines296 // boolean or null or undefined297 return298 } else if (res instanceof Promise) {299 if (globalContexts.length === 0) {270- buffer.unshift('', res)300+ buffer.unshift('', resolveFunctionComponentResult(res))301 } else {302 // save the current context state for resuming the suspended subtree273- const suspendedContext = captureRenderContext()274- buffer.unshift(275- '',276- res.then((childRes) => {277- if (childRes instanceof JSXNode) {278- childRes.suspendedContext = suspendedContext279- }280- return childRes281- })282- )303+ buffer.unshift('', resolveFunctionComponentResult(res, captureRenderContext()))304 }305 } else if (res instanceof JSXNode) {306 res.toStringToBuffer(buffer)307+ } else if (Array.isArray(res)) {308+ childrenToStringToBuffer(res, buffer)309 } else if (typeof res === 'number' || (res as HtmlEscaped).isEscaped) {310 buffer[0] += res311 if (res.callbacks) {312 buffer.callbacks ||= []147 unmodified linesmodified:src/jsx/index.test.tsx+95 added-1 removed
1 /** @jsxImportSource ./ */2 /* eslint-disable @typescript-eslint/no-explicit-any */3-import { html } from '../helper/html'3+import { html, raw } from '../helper/html'4 import { Hono } from '../hono'5 import { DOM_MEMO } from './constants'6 import { captureRenderContext } from './context'7 import { Suspense, renderToReadableStream } from './streaming'163 unmodified lines171 )172 expect(template.toString()).toBe('<p><span>a</span><span>b</span></p>')173 })174 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 = '<script>alert(1)</script>'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+237 it('Empty elements are rended without closing tag', () => {238 const template = <input />239 expect(template.toString()).toBe('<input/>')240 })1072 unmodified lines1313 )1314 expect((await template.toString()).toString()).toBe('<span>dark</span>')1315 })1316 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 = () => sharedResult1333+ 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+1349 it('nested', async () => {1350 const template = (1351 <ThemeContext.Provider value='dark'>1352 <ParentAsyncConsumer />334 unmodified linesmodified:src/jsx/streaming.test.tsx+40 added
28 unmodified lines29 afterEach(() => {30 suspenseCounter++31 })32 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+73 it('Suspense / renderToReadableStream', async () => {74 let contentEvaluatedCount = 075 const Content = () => {76 contentEvaluatedCount++1081 unmodified linesmodified:src/middleware/jsx-renderer/index.test.tsx+16 added
53 unmodified lines54 '<!DOCTYPE html><div class="nested"><h1>http://localhost/nested</h1></div>'55 )56 })57 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+74 it('Should get the context object as a 2nd arg', async () => {75 const app = new Hono()76 app.use(77 jsxRenderer(453 unmodified linesmodified:src/middleware/jsx-renderer/index.ts+4 added-6 removed
8 unmodified lines9101112131314151617181920212324252622232425262728312930313233130 unmodified linesExpand all8 unmodified linesimport { Fragment, createContext, jsx, useContext } from '../../jsx'import type { FC, Context as JSXContext, JSXNode, PropsWithChildren } from '../../jsx'import { renderToReadableStream } from '../../jsx/streaming'import type { Env, Input, MiddlewareHandler } from '../../types'import type { HtmlEscapedString } from '../../utils/html'
export const RequestContext: JSXContext<Context<any, any, {}> | null> = createContext<Context | null>(null)
type RendererOptions = { docType?: boolean | string stream?: boolean | Record<string, string>}
type Component = ( props: PropsForRenderer & { Layout: FC }, c: Context) => HtmlEscapedString | Promise<HtmlEscapedString>type ComponentResult = Exclude<ReturnType<FC>, null>
type Component = (props: PropsForRenderer & { Layout: FC }, c: Context) => ComponentResult
type ComponentWithChildren = ( props: PropsWithChildren<PropsForRenderer & { Layout: FC }>, c: Context) => HtmlEscapedString | Promise<HtmlEscapedString>) => ComponentResult
const createRenderer = ( c: Context,130 unmodified linesExpand all