Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(jsx/precompile): Normalization and stringification of attribute values as renderToString #3432

Merged
merged 5 commits into from
Sep 24, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
54 changes: 54 additions & 0 deletions runtime-tests/deno-jsx/jsx.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -110,3 +110,57 @@ Deno.test('JSX: css', async () => {
'<html><head><style id="hono-css">.css-3142110215{color:red}</style></head><body><div class="css-3142110215"></div></body></html>'
)
})

Deno.test('JSX: normalize key', async () => {
const className = <div className='foo'></div>
const htmlFor = <div htmlFor='foo'></div>
const crossOrigin = <div crossOrigin='foo'></div>
const httpEquiv = <div httpEquiv='foo'></div>
const itemProp = <div itemProp='foo'></div>
const fetchPriority = <div fetchPriority='foo'></div>
const noModule = <div noModule='foo'></div>
const formAction = <div formAction='foo'></div>

assertEquals(className.toString(), '<div class="foo"></div>')
assertEquals(htmlFor.toString(), '<div for="foo"></div>')
assertEquals(crossOrigin.toString(), '<div crossorigin="foo"></div>')
assertEquals(httpEquiv.toString(), '<div http-equiv="foo"></div>')
assertEquals(itemProp.toString(), '<div itemprop="foo"></div>')
assertEquals(fetchPriority.toString(), '<div fetchpriority="foo"></div>')
assertEquals(noModule.toString(), '<div nomodule="foo"></div>')
assertEquals(formAction.toString(), '<div formaction="foo"></div>')
})

Deno.test('JSX: null or undefined', async () => {
const nullHtml = <div className={null}></div>
const undefinedHtml = <div className={undefined}></div>

// react-jsx : <div>
// precompile : <div > // Extra whitespace is allowed because it is a specification.

assertEquals(nullHtml.toString().replace(/\s+/g, ''), '<div></div>')
assertEquals(undefinedHtml.toString().replace(/\s+/g, ''), '<div></div>')
})

Deno.test('JSX: boolean attributes', async () => {
const trueHtml = <div disabled={true}></div>
const falseHtml = <div disabled={false}></div>

// output is different, but semantics as HTML is the same, so both are OK
// react-jsx : <div disabled="">
// precompile : <div disabled>

assertEquals(trueHtml.toString().replace('=""', ''), '<div disabled></div>')
assertEquals(falseHtml.toString(), '<div></div>')
})

Deno.test('JSX: number', async () => {
const html = <div tabindex={1}></div>

assertEquals(html.toString(), '<div tabindex="1"></div>')
})

Deno.test('JSX: style', async () => {
const html = <div style={{ fontSize: '12px', color: null }}></div>
assertEquals(html.toString(), '<div style="font-size:12px"></div>')
})
2 changes: 1 addition & 1 deletion src/jsx/base.ts
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ const emptyTags = [
'track',
'wbr',
]
const booleanAttributes = [
export const booleanAttributes = [
'allowfullscreen',
'async',
'autofocus',
Expand Down
42 changes: 36 additions & 6 deletions src/jsx/jsx-runtime.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,13 +6,43 @@
export { jsxDEV as jsx, Fragment } from './jsx-dev-runtime'
export { jsxDEV as jsxs } from './jsx-dev-runtime'
export type { JSX } from './jsx-dev-runtime'

import { html, raw } from '../helper/html'
import type { HtmlEscapedString } from '../utils/html'
import type { HtmlEscapedString, StringBuffer, HtmlEscaped } from '../utils/html'
import { escapeToBuffer, stringBufferToString } from '../utils/html'
import { styleObjectForEach } from './utils'

Check warning on line 12 in src/jsx/jsx-runtime.ts

View check run for this annotation

Codecov / codecov/patch

src/jsx/jsx-runtime.ts#L11-L12

Added lines #L11 - L12 were not covered by tests

export { html as jsxTemplate }

export const jsxAttr = (
name: string,
value: string | Promise<string>
): HtmlEscapedString | Promise<HtmlEscapedString> =>
typeof value === 'string' ? raw(name + '="' + html`${value}` + '"') : html`${name}="${value}"`
key: string,
v: string | Promise<string> | Record<string, string | number | null | undefined | boolean>
): HtmlEscapedString | Promise<HtmlEscapedString> => {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can we create one common function for these lines and https://github.com/usualoma/hono/blob/fd80df6a0f03876cf6ac2b12b4b7b812c19ca616/src/jsx/base.ts#L180-L227 and use it from the both?

Like this, though, I think objectToAttribute is not the best name.

export const objectToAttribute = (key: string, v: any, buffer: any) => {
  if (v === null || v === undefined) {
    return
  }
  if (key === 'style' && typeof v === 'object') {
    // object to style strings
    let styleStr = ''
    styleObjectForEach(v as Record<string, string | number>, (property, value) => {
      if (value != null) {
        styleStr += `${styleStr ? ';' : ''}${property}:${value}`
      }
    })
    escapeToBuffer(styleStr, buffer)
    buffer[0] += '"'
  } else if (typeof v === 'boolean' && booleanAttributes.includes(key)) {
    return buffer
  } else if (typeof v === 'string') {
  // ...
  return buffer
}

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@yusukebe
I also considered making it common, but if it is made common, there will inevitably be overhead for both sides in the following areas.

https://github.com/usualoma/hono/blob/4405e69ae8ab419b2dab36dfd25c605a9c50fca3/src/jsx/base.ts#L202
https://github.com/usualoma/hono/blob/4405e69ae8ab419b2dab36dfd25c605a9c50fca3/src/jsx/base.ts#L205

I don't think it's a big overhead, but I want to be particularly conscious of performance when stringifying JSX, so I want to keep it separate for each implementation for optimization. What do you think?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@usualoma

Understood well. Let's go with this. Thank you for spending for considering it!

const buffer: StringBuffer = [`${key}="`] as StringBuffer
if (key === 'style' && typeof v === 'object') {

Check warning on line 21 in src/jsx/jsx-runtime.ts

View check run for this annotation

Codecov / codecov/patch

src/jsx/jsx-runtime.ts#L17-L21

Added lines #L17 - L21 were not covered by tests
// object to style strings
let styleStr = ''
styleObjectForEach(v as Record<string, string | number>, (property, value) => {
if (value != null) {
styleStr += `${styleStr ? ';' : ''}${property}:${value}`
}
})
escapeToBuffer(styleStr, buffer)
buffer[0] += '"'
} else if (typeof v === 'string') {
escapeToBuffer(v, buffer)
buffer[0] += '"'
} else if (v === null || v === undefined) {
return raw('')
} else if (typeof v === 'number' || (v as unknown as HtmlEscaped).isEscaped) {
buffer[0] += `${v}"`
} else if (v instanceof Promise) {
buffer.unshift('"', v)
} else {
escapeToBuffer(v.toString(), buffer)
buffer[0] += '"'
}

Check warning on line 43 in src/jsx/jsx-runtime.ts

View check run for this annotation

Codecov / codecov/patch

src/jsx/jsx-runtime.ts#L23-L43

Added lines #L23 - L43 were not covered by tests

return buffer.length === 1 ? raw(buffer[0]) : stringBufferToString(buffer, undefined)
}

Check warning on line 46 in src/jsx/jsx-runtime.ts

View check run for this annotation

Codecov / codecov/patch

src/jsx/jsx-runtime.ts#L45-L46

Added lines #L45 - L46 were not covered by tests

export const jsxEscape = (value: string) => value
Loading