Skip to content

Commit

Permalink
fix: missing space in jsx prop (#118)
Browse files Browse the repository at this point in the history
  • Loading branch information
huozhi authored Jan 18, 2025
1 parent 19dded5 commit 06fd073
Show file tree
Hide file tree
Showing 3 changed files with 46 additions and 4 deletions.
10 changes: 10 additions & 0 deletions lib/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -475,9 +475,19 @@ function tokenize(code, options) {
if (isIdentifier(prop)) {
current = prop
append(T_PROPERTY)
} else if (prop === ' ') {
current = prop
append(T_SPACE)
}
continue
}

// if (curr === ' ' || isSign(curr)) {
// append()
// current = curr
// append()
// continue
// }
}
}

Expand Down
27 changes: 27 additions & 0 deletions test/ast.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -370,6 +370,33 @@ describe('jsx', () => {
`)
})

it('preserve spaces in arrow function jsx prop correctly', () => {
const code = '<Foo prop={(v) => 1)} />'

const tokens = tokenize(code)
expect(getTokensAsString(tokens, { filterSpaces: false })).toMatchInlineSnapshot(`
[
"< => sign",
"Foo => entity",
" => space",
"prop => property",
"= => sign",
"{ => sign",
"( => sign",
"v => identifier",
") => sign",
"= => sign",
"> => sign",
" => space",
"1 => identifier",
") => sign",
"} => sign",
" => space",
"/> => sign",
]
`)
})

it('should render string for any jsx attribute values', () => {
const code = '<h1 data-title="true" />'
const tokens = tokenize(code)
Expand Down
13 changes: 9 additions & 4 deletions test/testing-utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,15 +26,20 @@ function getTokenArray(tokens) {
return tokens.map((tk) => [tk[1], getTypeName(tk)]);
}

function extractTokenArray(tokens) {
function extractTokenArray(tokens, options: { filterSpaces?: boolean } = {}) {
const { filterSpaces = true } = options
return tokens
.map((tk) => [mergeSpaces(tk[1]), getTypeName(tk)])
.filter(([_, type]) => type !== 'space' && type !== 'break')
.filter(([_, type]) =>
filterSpaces
? type !== 'space' && type !== 'break'
: true
)
}

// Generate the string representation of the tokens
function getTokensAsString(tokens) {
const extracted = extractTokenArray(tokens)
function getTokensAsString(tokens: any[], options: { filterSpaces?: boolean } = {}) {
const extracted = extractTokenArray(tokens, options)
return extracted.map(([value, type]) => `${value} => ${type}`)
}

Expand Down

0 comments on commit 06fd073

Please sign in to comment.