0
0
mirror of https://github.com/honojs/hono.git synced 2024-11-21 18:18:57 +01:00

feat(middleware/jsx): We need Fragment. (#310)

This commit is contained in:
Taku Amano 2022-06-12 08:20:31 +09:00 committed by GitHub
parent cfc8c6ee9d
commit 5993b61067
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 37 additions and 6 deletions

View File

@ -1,5 +1,5 @@
import { Hono } from '../../hono'
import { h, jsx, memo } from '.'
import { h, jsx, memo, Fragment } from '.'
describe('JSX middleware', () => {
const app = new Hono()
@ -146,8 +146,8 @@ describe('memo', () => {
it('custom propsAreEqual', () => {
const Body = memo(
({ counter }: { counter: number, refresh?: boolean }) => <span>{counter}</span>,
(_, nextProps) => typeof nextProps.refresh == 'undefined' ? true : !nextProps.refresh
({ counter }: { counter: number; refresh?: boolean }) => <span>{counter}</span>,
(_, nextProps) => (typeof nextProps.refresh == 'undefined' ? true : !nextProps.refresh)
)
let template = <Body counter={0} />
@ -160,3 +160,25 @@ describe('memo', () => {
expect(template.toString()).toBe('<span>2</span>')
})
})
describe('Fragment', () => {
it('Should render children', () => {
const template = (
<>
<p>1</p>
<p>2</p>
</>
)
expect(template.toString()).toBe('<p>1</p><p>2</p>')
})
it('Should render nothing for empty Fragment', () => {
const template = <></>
expect(template.toString()).toBe('')
})
it('Should render nothing for undefined', () => {
const template = <>{undefined}</>
expect(template.toString()).toBe('')
})
})

View File

@ -32,7 +32,7 @@ export const h = (
return tag.call(null, { ...props, children: children.length <= 1 ? children[0] : children })
}
let result = `<${tag}`
let result = tag !== '' ? `<${tag}` : ''
const propsKeys = Object.keys(props || {})
for (let i = 0, len = propsKeys.length; i < len; i++) {
@ -53,7 +53,9 @@ export const h = (
result += ` ${propsKeys[i]}="${escape(v.toString())}"`
}
result += '>'
if (tag !== '') {
result += '>'
}
const flattenChildren = children.flat(Infinity)
for (let i = 0, len = flattenChildren.length; i < len; i++) {
@ -67,7 +69,9 @@ export const h = (
}
}
result += `</${tag}>`
if (tag !== '') {
result += `</${tag}>`
}
const escapedString = new String(result) as EscapedString
escapedString.isEscaped = true
@ -111,3 +115,7 @@ export const memo = <T>(
return (computed ||= component(props))
}) as FC<T>
}
export const Fragment = (props: { key?: string; children?: any }): EscapedString => {
return h('', {}, ...(props.children || []))
}

View File

@ -20,6 +20,7 @@
],
"jsx": "react",
"jsxFactory": "h",
"jsxFragmentFactory": "Fragment",
},
"include": [
"src/**/*.ts",