Skip to content

Commit

Permalink
Merge pull request #2080 from system-ui/lachlanjc-1728
Browse files Browse the repository at this point in the history
  • Loading branch information
hasparus committed Jan 29, 2022
2 parents ccb6009 + cf18e1c commit 705463b
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 2 deletions.
14 changes: 14 additions & 0 deletions packages/custom-properties/src/index.ts
@@ -1,6 +1,10 @@
import pluralize from 'pluralize'
import { Theme } from '@theme-ui/css'

// Simplified validator based on spec https://www.w3.org/TR/CSS22/syndata.html#value-def-identifier
// Does not check for "cannot start with a digit, two hyphens, or a hyphen followed by a digit"
const keyValidator = /^[A-z0-9][\w-]*$/

interface CustomProperties {
[key: string]: string | number
}
Expand All @@ -12,6 +16,16 @@ export default function makeCustomProperties(theme: Theme, prefix?: string) {
Object.entries(object).forEach(([key, value]) => {
let formattedKey = pluralize(key, 1)

if (
process.env.NODE_ENV !== 'production' &&
!keyValidator.test(formattedKey)
) {
console.warn(
`[theme-ui] Theme key "${value}" found will produce an invalid CSS custom property. ` +
'Keys must only contain the following: A-Z, a-z, 0-9, hyphen, underscore.'
)
}

if (prefix && !previousKey) {
formattedKey = `${prefix}-${formattedKey}`
}
Expand Down
16 changes: 14 additions & 2 deletions packages/custom-properties/test/test.js
@@ -1,4 +1,5 @@
import toCustomProperties from '../src'
import mockConsole from 'jest-mock-console'

const theme = {
colors: {
Expand All @@ -18,8 +19,7 @@ const theme = {
},
},
fonts: {
body:
'system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", sans-serif',
body: 'system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", sans-serif',
heading:
'system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", sans-serif',
monospace: 'Menlo, monospace',
Expand All @@ -35,13 +35,25 @@ const theme = {
}

it('transforms a theme config to CSS custom properties', () => {
mockConsole()
const result = toCustomProperties(theme)

expect(result).toMatchSnapshot()
expect(console.warn).toHaveBeenCalledTimes(0)
})

it('transforms a theme config to CSS custom properties with prefix', () => {
const result = toCustomProperties(theme, '🍭')

expect(result).toMatchSnapshot()
})

it('warns on invalid CSS custom property key', () => {
mockConsole()
toCustomProperties({ sizes: { '1/4': 1 / 4, '1/2': 1 / 2 } })

expect(console.warn).toHaveBeenCalledTimes(2)
expect(console.warn).toHaveBeenLastCalledWith(
'[theme-ui] Theme key "0.5" found will produce an invalid CSS custom property. Keys must only contain the following: A-Z, a-z, 0-9, hyphen, underscore.'
)
})

0 comments on commit 705463b

Please sign in to comment.