Skip to content

Commit

Permalink
fix: support CSS variables
Browse files Browse the repository at this point in the history
Fixes #582
  • Loading branch information
gregberge committed Nov 13, 2021
1 parent 985444d commit cbdb47f
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 2 deletions.
12 changes: 12 additions & 0 deletions packages/hast-util-to-babel-ast/src/index.test.ts
Expand Up @@ -83,4 +83,16 @@ describe('hast-util-to-babel-ast', () => {
`"<svg><text><tspan>{\\"<\\"}</tspan></text></svg>;"`,
)
})

it('properly converts style with variables', () => {
const code = `<svg><path style="--index: 1; font-size: 24px;"></path><path style="--index: 2"></path></svg>`
expect(transform(code)).toMatchInlineSnapshot(`
"<svg><path style={{
\\"--index\\": 1,
fontSize: 24
}} /><path style={{
\\"--index\\": 2
}} /></svg>;"
`)
})
})
11 changes: 9 additions & 2 deletions packages/hast-util-to-babel-ast/src/stringToObjectStyle.ts
Expand Up @@ -2,21 +2,28 @@
import * as t from '@babel/types'
import { hyphenToCamelCase, isNumeric, trimEnd } from './util'

const PX_REGEX = /^\d+px$/
const MS_REGEX = /^-ms-/
const VAR_REGEX = /^--/

/**
* Determines if the CSS value can be converted from a
* 'px' suffixed string to a numeric value.
*/
const isConvertiblePixelValue = (value: string) => {
return /^\d+px$/.test(value)
return PX_REGEX.test(value)
}

/**
* Format style key into JSX style object key.
*/
const formatKey = (key: string) => {
if (VAR_REGEX.test(key)) {
return t.stringLiteral(key)
}
key = key.toLowerCase()
// Don't capitalize -ms- prefix
if (/^-ms-/.test(key)) key = key.substr(1)
if (MS_REGEX.test(key)) key = key.substr(1)
return t.identifier(hyphenToCamelCase(key))
}

Expand Down

0 comments on commit cbdb47f

Please sign in to comment.