Skip to content

Commit

Permalink
feat(jsx): support htmlfor attribute alias (honojs#2916)
Browse files Browse the repository at this point in the history
* add an attribute alias for 'for' to 'htmlFor'

* Updated the utils.test to include attribute aliases.

* bun run format:fix and lint:fix
  • Loading branch information
akira-tsuno authored Jun 6, 2024
1 parent 448a002 commit 817626f
Show file tree
Hide file tree
Showing 2 changed files with 79 additions and 1 deletion.
70 changes: 69 additions & 1 deletion src/jsx/utils.test.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,72 @@
import { styleObjectForEach } from './utils'
import { normalizeIntrinsicElementProps, styleObjectForEach } from './utils'

describe('normalizeIntrinsicElementProps', () => {
it('should convert className to class', () => {
const props: Record<string, unknown> = {
className: 'test-class',
id: 'test-id',
}

normalizeIntrinsicElementProps(props)

expect(props).toEqual({
class: 'test-class',
id: 'test-id',
})
})

it('should convert htmlFor to for', () => {
const props: Record<string, unknown> = {
htmlFor: 'test-for',
name: 'test-name',
}

normalizeIntrinsicElementProps(props)

expect(props).toEqual({
for: 'test-for',
name: 'test-name',
})
})

it('should convert multiple attribute aliases', () => {
const props: Record<string, unknown> = {
className: 'test-class',
htmlFor: 'test-for',
type: 'text',
}

normalizeIntrinsicElementProps(props)

expect(props).toEqual({
class: 'test-class',
for: 'test-for',
type: 'text',
})
})

it('should not modify props without className or htmlFor', () => {
const props: Record<string, unknown> = {
id: 'test-id',
name: 'test-name',
}

normalizeIntrinsicElementProps(props)

expect(props).toEqual({
id: 'test-id',
name: 'test-name',
})
})

it('should handle empty props', () => {
const props: Record<string, unknown> = {}

normalizeIntrinsicElementProps(props)

expect(props).toEqual({})
})
})

describe('styleObjectForEach', () => {
describe('Should output the number as it is, when a number type is passed', () => {
Expand Down
10 changes: 10 additions & 0 deletions src/jsx/utils.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,18 @@
/**
* Normalizes intrinsic element properties by converting JSX element properties
* to their corresponding HTML attributes.
*
* @param props - JSX element properties.
*/
export const normalizeIntrinsicElementProps = (props: Record<string, unknown>): void => {
if (props && 'className' in props) {
props['class'] = props['className']
delete props['className']
}
if (props && 'htmlFor' in props) {
props['for'] = props['htmlFor']
delete props['htmlFor']
}
}

export const styleObjectForEach = (
Expand Down

0 comments on commit 817626f

Please sign in to comment.