Skip to content

Commit

Permalink
Allow grabbing theme values with a decimal (#815)
Browse files Browse the repository at this point in the history
This PR contains a fix for spacing theme values containing a decimal,
like this:

```js
tw`pl-[calc(20px + theme(spacing.2.5))]`

// ↓ ↓ ↓ ↓ ↓ ↓

({
  "paddingLeft": "calc(20px + 0.625rem)"
});
```

Previously values like this would return an incorrect value.
This made square brackets required to select these type of values: 

```js
tw`pl-[calc(20px + theme(spacing[2.5]))]`
```

Related #814
  • Loading branch information
ben-rogerson committed Jul 23, 2023
1 parent e438582 commit 8668bf2
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 1 deletion.
11 changes: 10 additions & 1 deletion src/core/lib/createTheme.ts
Expand Up @@ -18,7 +18,16 @@ function createTheme(
defaultValue?: string,
options = {}
): number | boolean | Record<string, unknown> {
const [pathRoot, ...subPaths] = toPath(path)
let [pathRoot, ...subPaths] = toPath(path)

// Retain dots in spacing values, eg: `ml-[theme(spacing.0.5)]`
if (
pathRoot === 'spacing' &&
subPaths.length === 2 &&
subPaths.every(x => !Number.isNaN(Number(x)))
) {
subPaths = [subPaths.join('.')]
}

const value = getConfigValue(
path ? ['theme', pathRoot, ...subPaths] : ['theme'],
Expand Down
12 changes: 12 additions & 0 deletions tests/arbitraryValues.test.ts
Expand Up @@ -229,6 +229,18 @@ it('should allow using the DEFAULT key when using theme', async () => {
})
})

it('should allow dots instead of square brackets for decimal point values', async () => {
const input = 'tw`ml-[theme(spacing.0.5)]`'

return run(input).then(result => {
expect(result).toMatchFormattedJavaScript(`
({
"marginLeft": "0.125rem"
});
`)
})
})

it('should not output unparsable arbitrary CSS values', async () => {
// eslint-disable-next-line no-template-curly-in-string
const input = 'tw`w-[${sizes.width}]`'
Expand Down

0 comments on commit 8668bf2

Please sign in to comment.