Skip to content
Myr

Merge pull request #306 from honojs/feat/jsx

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by Yusuke Wada · committed by GitHub · parents d2a4b2d, e6c916a · Browse files · 11 files+397 added−4 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Trailers

  • feat: jsx middleware

Diff stats

11 files+397 added−4 removed

  • tests:+170 added−0 removed
  • other:+227 added−4 removed

11 files+397 added−4 removed

added:src/middleware/jsx/index.test.tsx+162 added
1import { Hono } from '../../hono'2import { h, jsx, memo } from '.'34describe('JSX middleware', () => {5 const app = new Hono()6 app.use('*', jsx())78 it('Should render HTML strings', async () => {9 app.get('/', (c) => {10 return c.render(<h1>Hello</h1>)11 })12 const res = await app.request('http://localhost/')13 expect(res.status).toBe(200)14 expect(res.headers.get('Content-Type')).toBe('text/html; charset=UTF-8')15 expect(await res.text()).toBe('<!doctype html><h1>Hello</h1>')16 })17})1819describe('render to string', () => {20 it('Nested array', () => {21 const template = (22 <p>23 {[[['a']], [['b']]].map((item1) =>24 item1.map((item2) => item2.map((item3) => <span>{item3}</span>))25 )}26 </p>27 )28 expect(template.toString()).toBe('<p><span>a</span><span>b</span></p>')29 })3031 it('Props value is null', () => {32 const template = <span data-hello={null}>Hello</span>33 expect(template.toString()).toBe('<span>Hello</span>')34 })3536 it('Props value is undefined', () => {37 const template = <span data-hello={undefined}>Hello</span>38 expect(template.toString()).toBe('<span>Hello</span>')39 })4041 describe('dangerouslySetInnerHTML', () => {42 it('Should render dangerouslySetInnerHTML', () => {43 const template = <span dangerouslySetInnerHTML={{ __html: '" is allowed here' }}></span>44 expect(template.toString()).toBe('<span>" is allowed here</span>')45 })4647 it('Should get an error if both dangerouslySetInnerHTML and children are specified', () => {48 expect(() => (49 <span dangerouslySetInnerHTML={{ __html: '" is allowed here' }}>Hello</span>50 )).toThrow()51 })52 })5354 // https://en.reactjs.org/docs/jsx-in-depth.html#booleans-null-and-undefined-are-ignored55 describe('Booleans, Null, and Undefined Are Ignored', () => {56 it.each([true, false, undefined, null])('%s', (item) => {57 expect((<span>{item}</span>).toString()).toBe('<span></span>')58 })5960 it('falsy value', () => {61 const template = <span>{0}</span>62 expect(template.toString()).toBe('<span>0</span>')63 })64 })6566 // https://en.reactjs.org/docs/jsx-in-depth.html#props-default-to-true67 describe('Props Default to “True”', () => {68 it('default prop value', () => {69 const template = <span data-hello>Hello</span>70 expect(template.toString()).toBe('<span data-hello="true">Hello</span>')71 })72 })7374 // https://en.reactjs.org/docs/jsx-in-depth.html#functions-as-children75 describe('Functions as Children', () => {76 it('Function', () => {77 function Repeat(props: any) {78 const items = []79 for (let i = 0; i < props.numTimes; i++) {80 items.push((props.children as Function)(i))81 }82 return <div>{items}</div>83 }8485 function ListOfTenThings() {86 return (87 <Repeat numTimes={10}>88 {(index: string) => <div key={index}>This is item {index} in the list</div>}89 </Repeat>90 )91 }9293 const template = <ListOfTenThings />94 expect(template.toString()).toBe(95 '<div><div key="0">This is item 0 in the list</div><div key="1">This is item 1 in the list</div><div key="2">This is item 2 in the list</div><div key="3">This is item 3 in the list</div><div key="4">This is item 4 in the list</div><div key="5">This is item 5 in the list</div><div key="6">This is item 6 in the list</div><div key="7">This is item 7 in the list</div><div key="8">This is item 8 in the list</div><div key="9">This is item 9 in the list</div></div>'96 )97 })98 })99})100101describe('memo', () => {102 it('memoized', () => {103 let counter = 0104 const Header = memo(() => <title>Test Site {counter}</title>)105 const Body = () => <span>{counter}</span>106107 let template = (108 <html>109 <head>110 <Header />111 </head>112 <body>113 <Body />114 </body>115 </html>116 )117 expect(template.toString()).toBe(118 '<html><head><title>Test Site 0</title></head><body><span>0</span></body></html>'119 )120121 counter++122 template = (123 <html>124 <head>125 <Header />126 </head>127 <body>128 <Body />129 </body>130 </html>131 )132 expect(template.toString()).toBe(133 '<html><head><title>Test Site 0</title></head><body><span>1</span></body></html>'134 )135 })136137 it('props are updated', () => {138 const Body = memo(({ counter }: { counter: number }) => <span>{counter}</span>)139140 let template = <Body counter={0} />141 expect(template.toString()).toBe('<span>0</span>')142143 template = <Body counter={1} />144 expect(template.toString()).toBe('<span>1</span>')145 })146147 it('custom propsAreEqual', () => {148 const Body = memo(149 ({ counter }: { counter: number, refresh?: boolean }) => <span>{counter}</span>,150 (_, nextProps) => typeof nextProps.refresh == 'undefined' ? true : !nextProps.refresh151 )152153 let template = <Body counter={0} />154 expect(template.toString()).toBe('<span>0</span>')155156 template = <Body counter={1} />157 expect(template.toString()).toBe('<span>0</span>')158159 template = <Body counter={2} refresh={true} />160 expect(template.toString()).toBe('<span>2</span>')161 })162})
added:src/middleware/jsx/index.ts+113 added
1import type { Context } from '../../context'2import type { Next } from '../../hono'3import { escape } from '../../utils/html'45declare global {6 // eslint-disable-next-line @typescript-eslint/no-namespace7 namespace h.JSX {8 interface IntrinsicElements {9 [tagName: string]: Record<string, any>10 }11 }12}1314export const jsx = () => {15 return async (c: Context, next: Next) => {16 c.render = (content: string) => {17 const output = `<!doctype html>${content.toString()}`18 return c.html(output)19 }20 await next()21 }22}2324type EscapedString = string & { isEscaped: true }2526export const h = (27 tag: string | Function,28 props: Record<string, any>,29 ...children: (string | EscapedString)[]30): EscapedString => {31 if (typeof tag === 'function') {32 return tag.call(null, { ...props, children: children.length <= 1 ? children[0] : children })33 }3435 let result = `<${tag}`3637 const propsKeys = Object.keys(props || {})38 for (let i = 0, len = propsKeys.length; i < len; i++) {39 const v = props[propsKeys[i]]40 if (propsKeys[i] === 'dangerouslySetInnerHTML') {41 if (children.length > 0) {42 throw 'Can only set one of `children` or `props.dangerouslySetInnerHTML`.'43 }4445 const escapedString = new String(v.__html) as EscapedString46 escapedString.isEscaped = true47 children = [escapedString]48 continue49 } else if (v === null || v === undefined) {50 continue51 }5253 result += ` ${propsKeys[i]}="${escape(v.toString())}"`54 }5556 result += '>'5758 const flattenChildren = children.flat(Infinity)59 for (let i = 0, len = flattenChildren.length; i < len; i++) {60 const child = flattenChildren[i]61 if (typeof child === 'boolean' || child === null || child === undefined) {62 continue63 } else if (typeof child === 'object' && (child as any).isEscaped) {64 result += child65 } else {66 result += escape(child.toString())67 }68 }6970 result += `</${tag}>`7172 const escapedString = new String(result) as EscapedString73 escapedString.isEscaped = true7475 return escapedString76}7778type FC<T = Record<string, any>> = (props: T) => EscapedString7980const shallowEqual = (a: Record<string, any>, b: Record<string, any>): boolean => {81 if (a === b) {82 return true83 }8485 const aKeys = Object.keys(a)86 const bKeys = Object.keys(b)87 if (aKeys.length !== bKeys.length) {88 return false89 }9091 for (let i = 0, len = aKeys.length; i < len; i++) {92 if (a[aKeys[i]] !== b[aKeys[i]]) {93 return false94 }95 }9697 return true98}99100export const memo = <T>(101 component: FC<T>,102 propsAreEqual: (prevProps: Readonly<T>, nextProps: Readonly<T>) => boolean = shallowEqual103): FC<T> => {104 let computed = undefined105 let prevProps: T | undefined = undefined106 return ((props: T): EscapedString => {107 if (prevProps && !propsAreEqual(prevProps, props)) {108 computed = undefined109 }110 prevProps = props111 return (computed ||= component(props))112 }) as FC<T>113}
added:src/middleware/jsx/README.md+89 added
1# JSX Middleware23JSX Middleware enable rendering HTML with JSX syntax.4It's just for Sever-Side-Rendering. No virtual DOM.5This middleware supports only for TypeScript.67## Settings89tsconfig.json:1011```json12{13 "compilerOptions": {14 "jsx": "react",15 "jsxFactory": "h"16 }17}18```1920## Usage2122index.tsx:2324```tsx25import { Hono } from 'hono'26import { h, jsx } from 'hono/jsx'2728const app = new Hono()2930app.use('*', jsx())3132const Layout = (props: { children?: string }) => {33 return (34 <html>35 <body>{props.children}</body>36 </html>37 )38}3940const Top = (props: { messages: string[] }) => {41 return (42 <Layout>43 <h1>Hello Hono!</h1>44 <ul>45 {props.messages.map((message) => {46 return <li>{message}!!</li>47 })}48 </ul>49 </Layout>50 )51}5253app.get('/', (c) => {54 const messages = ['Good Morning', 'Good Evening', 'Good Night']55 return c.render(<Top messages={messages} />)56})5758app.fire()59```6061## dangerouslySetInnerHTML6263```tsx64app.get('/foo', (c) => {65 const html = { __html: 'JSX &middot; SSR' }66 return c.render(<div dangerouslySetInnerHTML={html} />)67})68```6970## Tips for Cloudflare Workers7172It's useful to use Miniflare's`live-reload` option for developing.7374package.json:7576```json77{78 "scripts": {79 "build": "esbuild --bundle --outdir=dist ./src/index.tsx",80 "dev": "miniflare --live-reload --debug"81 }82}83```8485wrangler.toml:8687```toml88command = "yarn run build"89```
added:src/middleware/mustache/Context.ts+3 added
modified:src/middleware/mustache/mustache.ts+3 added-3 removed
added:src/utils/html.test.ts+8 added
added:src/utils/html.ts+11 added
modified:src/context.ts+1 added-1 removed
19 unmodified lines
20 private _headers: Record<string, string> | undefined21 private _res: Response | undefined22 private notFoundHandler: NotFoundHandler2324 render: (template: string, params?: object, options?: object) => Promise<Response>24 render: (content: string, params?: object, options?: object) => Response | Promise<Response>2526 constructor(27 req: Request<RequestParamKeyType>,28 env: E | undefined = undefined,
101 unmodified lines
modified:package.json+4 added
22 unmodified lines
23 "./cookie": "./dist/middleware/cookie/index.js",24 "./cors": "./dist/middleware/cors/index.js",25 "./etag": "./dist/middleware/etag/index.js",26 "./graphql-server": "./dist/middleware/graphql-server/index.js",27 "./jsx": "./dist/middleware/jsx/index.js",28 "./jwt": "./dist/middleware/jwt/index.js",29 "./logger": "./dist/middleware/logger/index.js",30 "./mustache": "./dist/middleware/mustache/index.js",31 "./mustache.module": "./dist/middleware/mustache/module.mjs",
28 unmodified lines
60 ],61 "graphql-server": [62 "./dist/middleware/graphql-server"63 ],64 "jsx": [65 "./dist/middleware/jsx"66 ],67 "jwt": [68 "./dist/middleware/jwt"69 ],70 "logger": [
85 unmodified lines
modified:README.md+1 added
71 unmodified lines
72- [Cookie parsing / serializing](https://github.com/honojs/hono/tree/master/src/middleware/cookie/)73- [CORS](https://github.com/honojs/hono/tree/master/src/middleware/cors/)74- [ETag](https://github.com/honojs/hono/tree/master/src/middleware/etag/)75- [GraphQL Server](https://github.com/honojs/hono/tree/master/src/middleware/graphql-server/)76- [JSX](https://github.com/honojs/hono/tree/master/src/middleware/jsx/)77- [JWT Authentication](https://github.com/honojs/hono/tree/master/src/middleware/jwt/)78- [Logger](https://github.com/honojs/hono/tree/master/src/middleware/logger/)79- [Mustache template engine](https://github.com/honojs/hono/tree/master/src/middleware/mustache/) (Only for Cloudflare Workers)80- [JSON pretty printing](https://github.com/honojs/hono/tree/master/src/middleware/pretty-json/)
666 unmodified lines
modified:tsconfig.json+2 added