Skip to content

Commit

Permalink
fix(hast-util-to-babel-ast): correctly handle aria attributes
Browse files Browse the repository at this point in the history
Closes #279
  • Loading branch information
gregberge committed Apr 11, 2019
1 parent 6366e73 commit a74c585
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 5 deletions.
26 changes: 21 additions & 5 deletions packages/hast-util-to-babel-ast/src/getAttributes.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,17 +3,33 @@ import { isNumeric, kebabCase, replaceSpaces } from './util'
import stringToObjectStyle from './stringToObjectStyle'
import { ATTRIBUTE_MAPPING, ELEMENT_ATTRIBUTE_MAPPING } from './mappings'

function convertAriaAttribute(kebabKey) {
const [aria, ...parts] = kebabKey.split('-')
return `${aria}-${parts.join('').toLowerCase()}`
}

function getKey(key, value, node) {
const kebabKey = kebabCase(key)
if (kebabKey.startsWith('aria-') || kebabKey.startsWith('data-')) {
return t.jsxIdentifier(kebabKey)
}
const lowerCaseKey = key.toLowerCase()
const mappedElementAttribute =
ELEMENT_ATTRIBUTE_MAPPING[node.name] &&
ELEMENT_ATTRIBUTE_MAPPING[node.name][lowerCaseKey]
const mappedAttribute = ATTRIBUTE_MAPPING[lowerCaseKey]
return t.jsxIdentifier(mappedElementAttribute || mappedAttribute || key)

if (mappedElementAttribute || mappedAttribute) {
return t.jsxIdentifier(mappedElementAttribute || mappedAttribute)
}

const kebabKey = kebabCase(key)

if (kebabKey.startsWith('aria-')) {
return t.jsxIdentifier(convertAriaAttribute(kebabKey))
}

if (kebabKey.startsWith('data-')) {
return t.jsxIdentifier(kebabKey)
}

return t.jsxIdentifier(key)
}

function getValue(key, value) {
Expand Down
7 changes: 7 additions & 0 deletions packages/hast-util-to-babel-ast/src/index.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,13 @@ describe('hast-util-to-babel-ast', () => {
)
})

it('should correctly transform aria-xxxXxx', () => {
const code = `<svg aria-labelledby="foo" aria-describedat="foo" aria-describedby="foo"></svg>`
expect(transform(code)).toMatchInlineSnapshot(
`"<svg aria-labelledby=\\"foo\\" aria-describedat=\\"foo\\" aria-describedby=\\"foo\\" />;"`,
)
})

it('should correctly transform data-x', () => {
const code = `<svg data-hidden="true"></svg>`
expect(transform(code)).toMatchInlineSnapshot(
Expand Down

0 comments on commit a74c585

Please sign in to comment.