From 817626ff7d2b7961ace72af22e84d50741344f95 Mon Sep 17 00:00:00 2001 From: Akira Tsuno <52409365+akira-tsuno@users.noreply.github.com> Date: Thu, 6 Jun 2024 17:32:01 +0900 Subject: [PATCH] feat(jsx): support htmlfor attribute alias (#2916) * add an attribute alias for 'for' to 'htmlFor' * Updated the utils.test to include attribute aliases. * bun run format:fix and lint:fix --- src/jsx/utils.test.ts | 70 ++++++++++++++++++++++++++++++++++++++++++- src/jsx/utils.ts | 10 +++++++ 2 files changed, 79 insertions(+), 1 deletion(-) diff --git a/src/jsx/utils.test.ts b/src/jsx/utils.test.ts index 0f6fd7b66..5bf488e61 100644 --- a/src/jsx/utils.test.ts +++ b/src/jsx/utils.test.ts @@ -1,4 +1,72 @@ -import { styleObjectForEach } from './utils' +import { normalizeIntrinsicElementProps, styleObjectForEach } from './utils' + +describe('normalizeIntrinsicElementProps', () => { + it('should convert className to class', () => { + const props: Record = { + 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 = { + 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 = { + 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 = { + 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 = {} + + normalizeIntrinsicElementProps(props) + + expect(props).toEqual({}) + }) +}) describe('styleObjectForEach', () => { describe('Should output the number as it is, when a number type is passed', () => { diff --git a/src/jsx/utils.ts b/src/jsx/utils.ts index 169593473..716ffcb3a 100644 --- a/src/jsx/utils.ts +++ b/src/jsx/utils.ts @@ -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): 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 = (