Skip to content

Commit 23d12aa

Browse files
committed
fix(hast-util-to-babel-ast): correctly handle aria attributes
Closes #279
1 parent 39c24c5 commit 23d12aa

2 files changed

Lines changed: 28 additions & 5 deletions

File tree

packages/hast-util-to-babel-ast/src/getAttributes.js

Lines changed: 21 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -3,17 +3,33 @@ import { isNumeric, kebabCase, replaceSpaces } from './util'
33
import stringToObjectStyle from './stringToObjectStyle'
44
import { ATTRIBUTE_MAPPING, ELEMENT_ATTRIBUTE_MAPPING } from './mappings'
55

6+
function convertAriaAttribute(kebabKey) {
7+
const [aria, ...parts] = kebabKey.split('-')
8+
return `${aria}-${parts.join('').toLowerCase()}`
9+
}
10+
611
function getKey(key, value, node) {
7-
const kebabKey = kebabCase(key)
8-
if (kebabKey.startsWith('aria-') || kebabKey.startsWith('data-')) {
9-
return t.jsxIdentifier(kebabKey)
10-
}
1112
const lowerCaseKey = key.toLowerCase()
1213
const mappedElementAttribute =
1314
ELEMENT_ATTRIBUTE_MAPPING[node.name] &&
1415
ELEMENT_ATTRIBUTE_MAPPING[node.name][lowerCaseKey]
1516
const mappedAttribute = ATTRIBUTE_MAPPING[lowerCaseKey]
16-
return t.jsxIdentifier(mappedElementAttribute || mappedAttribute || key)
17+
18+
if (mappedElementAttribute || mappedAttribute) {
19+
return t.jsxIdentifier(mappedElementAttribute || mappedAttribute)
20+
}
21+
22+
const kebabKey = kebabCase(key)
23+
24+
if (kebabKey.startsWith('aria-')) {
25+
return t.jsxIdentifier(convertAriaAttribute(kebabKey))
26+
}
27+
28+
if (kebabKey.startsWith('data-')) {
29+
return t.jsxIdentifier(kebabKey)
30+
}
31+
32+
return t.jsxIdentifier(key)
1733
}
1834

1935
function getValue(key, value) {

packages/hast-util-to-babel-ast/src/index.test.js

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -48,6 +48,13 @@ describe('hast-util-to-babel-ast', () => {
4848
)
4949
})
5050

51+
it('should correctly transform aria-xxxXxx', () => {
52+
const code = `<svg aria-labelledby="foo" aria-describedat="foo" aria-describedby="foo"></svg>`
53+
expect(transform(code)).toMatchInlineSnapshot(
54+
`"<svg aria-labelledby=\\"foo\\" aria-describedat=\\"foo\\" aria-describedby=\\"foo\\" />;"`,
55+
)
56+
})
57+
5158
it('should correctly transform data-x', () => {
5259
const code = `<svg data-hidden="true"></svg>`
5360
expect(transform(code)).toMatchInlineSnapshot(

0 commit comments

Comments
 (0)