Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: support CSS variables #627

Merged
merged 1 commit into from
Nov 13, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions packages/hast-util-to-babel-ast/src/index.test.ts
Original file line number Diff line number Diff line change
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
Original file line number Diff line number Diff line change
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