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
Provenance
- Commit
583d3d4- Tree
4036929- Author
Yusuke Wada <yusuke@kamawada.com>- Committer
GitHub <noreply@github.com>- Parent 1
d2a4b2d- Parent 2
e6c916a
11 files changed+397 added−4 removed
added:src/middleware/jsx/index.test.tsx+162 added
1+import { Hono } from '../../hono'2+import { h, jsx, memo } from '.'3+4+describe('JSX middleware', () => {5+ const app = new Hono()6+ app.use('*', jsx())7+8+ 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+})18+19+describe('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+ })30+31+ it('Props value is null', () => {32+ const template = <span data-hello={null}>Hello</span>33+ expect(template.toString()).toBe('<span>Hello</span>')34+ })35+36+ it('Props value is undefined', () => {37+ const template = <span data-hello={undefined}>Hello</span>38+ expect(template.toString()).toBe('<span>Hello</span>')39+ })40+41+ 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+ })46+47+ 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+ })53+54+ // 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+ })59+60+ it('falsy value', () => {61+ const template = <span>{0}</span>62+ expect(template.toString()).toBe('<span>0</span>')63+ })64+ })65+66+ // 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+ })73+74+ // 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+ }84+85+ 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+ }92+93+ 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+})100+101+describe('memo', () => {102+ it('memoized', () => {103+ let counter = 0104+ const Header = memo(() => <title>Test Site {counter}</title>)105+ const Body = () => <span>{counter}</span>106+107+ 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+ )120+121+ 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+ })136+137+ it('props are updated', () => {138+ const Body = memo(({ counter }: { counter: number }) => <span>{counter}</span>)139+140+ let template = <Body counter={0} />141+ expect(template.toString()).toBe('<span>0</span>')142+143+ template = <Body counter={1} />144+ expect(template.toString()).toBe('<span>1</span>')145+ })146+147+ 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+ )152+153+ let template = <Body counter={0} />154+ expect(template.toString()).toBe('<span>0</span>')155+156+ template = <Body counter={1} />157+ expect(template.toString()).toBe('<span>0</span>')158+159+ template = <Body counter={2} refresh={true} />160+ expect(template.toString()).toBe('<span>2</span>')161+ })162+})added:src/middleware/jsx/index.ts+113 added
1+import type { Context } from '../../context'2+import type { Next } from '../../hono'3+import { escape } from '../../utils/html'4+5+declare 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+}13+14+export 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+}23+24+type EscapedString = string & { isEscaped: true }25+26+export 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+ }34+35+ let result = `<${tag}`36+37+ 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+ }44+45+ const escapedString = new String(v.__html) as EscapedString46+ escapedString.isEscaped = true47+ children = [escapedString]48+ continue49+ } else if (v === null || v === undefined) {50+ continue51+ }52+53+ result += ` ${propsKeys[i]}="${escape(v.toString())}"`54+ }55+56+ result += '>'57+58+ 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+ }69+70+ result += `</${tag}>`71+72+ const escapedString = new String(result) as EscapedString73+ escapedString.isEscaped = true74+75+ return escapedString76+}77+78+type FC<T = Record<string, any>> = (props: T) => EscapedString79+80+const shallowEqual = (a: Record<string, any>, b: Record<string, any>): boolean => {81+ if (a === b) {82+ return true83+ }84+85+ const aKeys = Object.keys(a)86+ const bKeys = Object.keys(b)87+ if (aKeys.length !== bKeys.length) {88+ return false89+ }90+91+ for (let i = 0, len = aKeys.length; i < len; i++) {92+ if (a[aKeys[i]] !== b[aKeys[i]]) {93+ return false94+ }95+ }96+97+ return true98+}99+100+export 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 Middleware2+3+JSX Middleware enable rendering HTML with JSX syntax.4+It's just for Sever-Side-Rendering. No virtual DOM.5+This middleware supports only for TypeScript.6+7+## Settings8+9+tsconfig.json:10+11+```json12+{13+ "compilerOptions": {14+ "jsx": "react",15+ "jsxFactory": "h"16+ }17+}18+```19+20+## Usage21+22+index.tsx:23+24+```tsx25+import { Hono } from 'hono'26+import { h, jsx } from 'hono/jsx'27+28+const app = new Hono()29+30+app.use('*', jsx())31+32+const Layout = (props: { children?: string }) => {33+ return (34+ <html>35+ <body>{props.children}</body>36+ </html>37+ )38+}39+40+const 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+}52+53+app.get('/', (c) => {54+ const messages = ['Good Morning', 'Good Evening', 'Good Night']55+ return c.render(<Top messages={messages} />)56+})57+58+app.fire()59+```60+61+## dangerouslySetInnerHTML62+63+```tsx64+app.get('/foo', (c) => {65+ const html = { __html: 'JSX · SSR' }66+ return c.render(<div dangerouslySetInnerHTML={html} />)67+})68+```69+70+## Tips for Cloudflare Workers71+72+It's useful to use Miniflare's`live-reload` option for developing.73+74+package.json:75+76+```json77+{78+ "scripts": {79+ "build": "esbuild --bundle --outdir=dist ./src/index.tsx",80+ "dev": "miniflare --live-reload --debug"81+ }82+}83+```84+85+wrangler.toml:86+87+```toml88+command = "yarn run build"89+```added:src/middleware/mustache/Context.ts+3 added
123export interface Context { render(template: string, params?: object, options?: object): Promise<Response>}modified:src/middleware/mustache/mustache.ts+3 added-3 removed
1233456711 unmodified lines19202122232324252627272829303138 unmodified linesimport Mustache from 'mustache'import type { Context } from '../../context'import type { Handler, Next } from '../../hono'import type { Next } from '../../hono'import { bufferToString } from '../../utils/buffer'import type { KVAssetOptions } from '../../utils/cloudflare'import { getContentFromKVAsset, getKVFilePath } from '../../utils/cloudflare'
11 unmodified lines manifest?: object | string namespace?: KVNamespace}
export const mustache = (init: MustacheOptions = { root: '' }): Handler => {export const mustache = (init: MustacheOptions = { root: '' }) => { const { root } = init
return async (c: Context, next: Next) => { c.render = async (filename, params = {}, options?) => { c.render = async (filename, params = {}, options?): Promise<Response> => { const path = getKVFilePath({ filename: `${filename}${EXTENSION}`, root: root, defaultDocument: DEFAULT_DOCUMENT,38 unmodified linesadded:src/utils/html.test.ts+8 added
12345678import { escape } from './html'
describe('HTML escape', () => { it('Should escape special characters', () => { expect(escape('I <b>think</b> this is good.')).toBe('I <b>think</b> this is good.') expect(escape('John "Johnny" Smith')).toBe('John "Johnny" Smith') })})added:src/utils/html.ts+11 added
1234567891011const entityMap: Record<string, string> = { '&': '&', '<': '<', '>': '>', '"': '"',}const escapeRe = new RegExp(`[${Object.keys(entityMap).join('')}]`, 'g')const replaceFn = (m: string) => entityMap[m]export const escape = (str: string): string => { return str.replace(escapeRe, replaceFn)}modified:src/context.ts+1 added-1 removed
19 unmodified lines20 private _headers: Record<string, string> | undefined21 private _res: Response | undefined22 private notFoundHandler: NotFoundHandler23 24- render: (template: string, params?: object, options?: object) => Promise<Response>24+ render: (content: string, params?: object, options?: object) => Response | Promise<Response>25 26 constructor(27 req: Request<RequestParamKeyType>,28 env: E | undefined = undefined,101 unmodified linesmodified:package.json+4 added
22 unmodified lines23 "./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 lines60 ],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 linesmodified:README.md+1 added
71 unmodified lines72 - [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 linesmodified:tsconfig.json+2 added
16 unmodified lines171819202122232425263 unmodified lines16 unmodified lines "jest", "node", "@cloudflare/workers-types" ], "jsx": "react", "jsxFactory": "h", }, "include": [ "src/**/*.ts", "src/**/*.mts",3 unmodified lines