Skip to content
Myr

perf(jsx): JSX performance improvement (#444)

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

* perf(jsx): Update benchmark for JSX. * perf(utils/html): Improve `escape` performance. Improved `escape` performance with reference to the react-dom implementation. * refactor(utils/html): Subdivide HtmlEscapedString * perf(jsx): Rewrite JSX with new `escapeToBuffer` and `JSXNode`. * refactor(jsx): A function `jsx` returns `JSXNode` now. * perf(html): Rewrite html middleware with new `escapeToBuffer`. * Update tests for JSX. * Update tests for utils/html.

authored by Taku Amano · committed by GitHub · parent dab3c26 · Browse files · 7 files+258 added−91 removed
This commit

State

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

Diff stats

7 files+258 added−91 removed

  • tests:+74 added−9 removed
  • other:+184 added−82 removed

7 files+258 added−91 removed

modified:benchmarks/jsx/index.tsx+5 added-5 removed
modified:src/middleware/html/index.ts+15 added-11 removed
modified:src/middleware/jsx/index.test.tsx+54 added-4 removed
1import { Hono } from '../../hono'2import { html } from '../html/index'3import { jsx, memo, Fragment } from './index'45interface SiteData {6 title: string7 children?: any8}910describe('JSX middleware', () => {5 const app = new Hono()11 let app: Hono1213 beforeEach(() => {14 app = new Hono()15 })1617 it('Should render HTML strings', async () => {18 app.get('/', (c) => {19 return c.html(<h1>Hello</h1>)20 })
1 unmodified line
22 expect(res.status).toBe(200)23 expect(res.headers.get('Content-Type')).toBe('text/html; charset=UTF-8')24 expect(await res.text()).toBe('<h1>Hello</h1>')25 })2627 it('Should be able to be used with html middleware', async () => {28 const Layout = (props: SiteData) => html`<!DOCTYPE html>29 <html>30 <head>31 <title>${props.title}</title>32 </head>33 <body>34 ${props.children}35 </body>36 </html>`3738 const Content = (props: { siteData: SiteData; name: string }) => (39 <Layout {...props.siteData}>40 <h1>{props.name}</h1>41 </Layout>42 )4344 app.get('/', (c) => {45 const props = {46 name: 'JSX',47 siteData: {48 title: 'with html middleware',49 },50 }51 return c.html(<Content {...props} />)52 })53 const res = await app.request('http://localhost/')54 expect(res.status).toBe(200)55 expect(res.headers.get('Content-Type')).toBe('text/html; charset=UTF-8')56 expect(await res.text()).toBe(`<!DOCTYPE html>57 <html>58 <head>59 <title>with html middleware</title>60 </head>61 <body>62 <h1>JSX</h1>63 </body>64 </html>`)65 })66})6768describe('render to string', () => {69 it('Nested array', () => {
28 unmodified lines
98 expect(template.toString()).toBe('<span>" is allowed here</span>')99 })100101 it('Should get an error if both dangerouslySetInnerHTML and children are specified', () => {52 expect(() => (53 <span dangerouslySetInnerHTML={{ __html: '" is allowed here' }}>Hello</span>54 )).toThrow()102 expect(() =>103 (<span dangerouslySetInnerHTML={{ __html: '" is allowed here' }}>Hello</span>).toString()104 ).toThrow()105 })106 })107108 // https://en.reactjs.org/docs/jsx-in-depth.html#booleans-null-and-undefined-are-ignored
236 unmodified lines
modified:src/middleware/jsx/index.ts+108 added-54 removed
1import { escape } from '../../utils/html'2import type { HtmlEscapedString } from '../../utils/html'1import { escapeToBuffer } from '../../utils/html'2import type { Buffer, HtmlEscaped, HtmlEscapedString } from '../../utils/html'34declare global {5 // eslint-disable-next-line @typescript-eslint/no-namespace6 namespace jsx.JSX {
21 unmodified lines
28 'wbr',29]30const booleanAttributes = ['checked', 'selected', 'disabled', 'readonly', 'multiple']3132const newHtmlEscapedString = (str: string): HtmlEscapedString => {33 const escapedString = new String(str) as HtmlEscapedString34 escapedString.isEscaped = true35 return escapedString32const childrenToStringToBuffer = (children: Child[], buffer: Buffer): void => {33 for (let i = 0, len = children.length; i < len; i++) {34 const child = children[i]35 if (typeof child === 'string') {36 escapeToBuffer(child, buffer)37 } else if (typeof child === 'boolean' || child === null || child === undefined) {38 continue39 } else if (child instanceof JSXNode) {40 child.toStringToBuffer(buffer)41 } else if (typeof child === 'number' || (child as any).isEscaped) {42 buffer[0] += child43 } else {44 // `child` type is `Child[]`, so stringify recursively45 childrenToStringToBuffer(child, buffer)46 }47 }48}4938export { jsxFn as jsx }39const jsxFn = (40 tag: string | Function,41 props: Record<string, any>,42 ...children: (string | HtmlEscapedString)[]43): HtmlEscapedString => {44 if (typeof tag === 'function') {45 return tag.call(null, { ...props, children: children.length <= 1 ? children[0] : children })50type Child = string | number | JSXNode | Child[]51export class JSXNode implements HtmlEscaped {52 tag: string | Function53 props: Record<string, any>54 children: Child[]55 isEscaped: true = true56 constructor(tag: string | Function, props: Record<string, any>, children: Child[]) {57 this.tag = tag58 this.props = props59 this.children = children60 }6148 let result = tag !== '' ? `<${tag}` : ''62 toString(): string {63 const buffer: Buffer = ['']64 this.toStringToBuffer(buffer)65 return buffer[0]66 }6750 const propsKeys = Object.keys(props || {})68 toStringToBuffer(buffer: Buffer): void {69 const tag = this.tag as string70 const props = this.props71 let { children } = this7273 buffer[0] += `<${tag}`7475 const propsKeys = Object.keys(props || {})7677 for (let i = 0, len = propsKeys.length; i < len; i++) {78 const v = props[propsKeys[i]]52 for (let i = 0, len = propsKeys.length; i < len; i++) {53 const v = props[propsKeys[i]]54 if (typeof v === 'string') {55 result += ` ${propsKeys[i]}="${escape(v)}"`56 } else if (typeof v === 'number') {57 result += ` ${propsKeys[i]}="${v}"`58 } else if (v === null || v === undefined) {59 // Do nothing60 } else if (typeof v === 'boolean' && booleanAttributes.includes(propsKeys[i])) {61 if (v) {62 result += ` ${propsKeys[i]}=""`79 if (typeof v === 'string') {80 buffer[0] += ` ${propsKeys[i]}="`81 escapeToBuffer(v, buffer)82 buffer[0] += '"'83 } else if (typeof v === 'number') {84 buffer[0] += ` ${propsKeys[i]}="${v}"`85 } else if (v === null || v === undefined) {86 // Do nothing87 } else if (typeof v === 'boolean' && booleanAttributes.includes(propsKeys[i])) {88 if (v) {89 buffer[0] += ` ${propsKeys[i]}=""`90 }91 } else if (propsKeys[i] === 'dangerouslySetInnerHTML') {92 if (children.length > 0) {93 throw 'Can only set one of `children` or `props.dangerouslySetInnerHTML`.'94 }9596 const escapedString = new String(v.__html) as HtmlEscapedString97 escapedString.isEscaped = true98 children = [escapedString]99 } else {100 buffer[0] += ` ${propsKeys[i]}="`101 escapeToBuffer(v.toString(), buffer)102 buffer[0] += '"'103 }64 } else if (propsKeys[i] === 'dangerouslySetInnerHTML') {65 if (children.length > 0) {66 throw 'Can only set one of `children` or `props.dangerouslySetInnerHTML`.'67 }104 }10569 children = [newHtmlEscapedString(v.__html)]70 } else {71 result += ` ${propsKeys[i]}="${escape(v.toString())}"`106 if (emptyTags.includes(tag as string)) {107 buffer[0] += '/>'108 return109 }73 }11075 if (emptyTags.includes(tag)) {76 result += '/>'77 return newHtmlEscapedString(result)78 }111 buffer[0] += '>'11280 if (tag !== '') {81 result += '>'113 childrenToStringToBuffer(children, buffer)114115 buffer[0] += `</${tag}>`116 }117}11884 const flattenChildren = children.flat(Infinity)85 for (let i = 0, len = flattenChildren.length; i < len; i++) {86 const child = flattenChildren[i]87 if (typeof child === 'boolean' || child === null || child === undefined) {88 continue89 } else if (typeof child === 'object' && (child as any).isEscaped) {90 result += child119class JSXFunctionNode extends JSXNode {120 toStringToBuffer(buffer: Buffer): void {121 const { children } = this122123 const res = (this.tag as Function).call(null, {124 ...this.props,125 children: children.length <= 1 ? children[0] : children,126 })127128 if (res instanceof JSXNode) {129 res.toStringToBuffer(buffer)130 } else if (typeof res === 'number' || (res as HtmlEscaped).isEscaped) {131 buffer[0] += res132 } else {92 result += escape(child.toString())133 escapeToBuffer(res, buffer)134 }135 }136}13796 if (tag !== '') {97 result += `</${tag}>`138class JSXFragmentNode extends JSXNode {139 toStringToBuffer(buffer: Buffer): void {140 childrenToStringToBuffer(this.children, buffer)141 }142}143100 return newHtmlEscapedString(result)144export { jsxFn as jsx }145const jsxFn = (146 tag: string | Function,147 props: Record<string, any>,148 ...children: (string | HtmlEscapedString)[]149): JSXNode => {150 if (typeof tag === 'function') {151 return new JSXFunctionNode(tag, props, children)152 } else {153 return new JSXNode(tag, props, children)154 }155}156157type FC<T = Record<string, any>> = (props: T) => HtmlEscapedString158
31 unmodified lines
190 return (computed ||= component(props))191 }) as FC<T>192}193140export const Fragment = (props: { key?: string; children?: any }): HtmlEscapedString => {141 return jsxFn('', {}, ...(props.children || []))194export const Fragment = (props: { key?: string; children?: any }): JSXNode => {195 return new JSXFragmentNode('', {}, props.children || [])196}
modified:src/middleware/jsx/jsx-dev-runtime.ts+2 added-2 removed
modified:src/utils/html.test.ts+20 added-5 removed
modified:src/utils/html.ts+54 added-10 removed