From 8668bf2df96a3e6a352525199a6be7dde65b93dd Mon Sep 17 00:00:00 2001 From: Ben Rogerson Date: Mon, 24 Jul 2023 08:14:02 +0930 Subject: [PATCH] Allow grabbing theme values with a decimal (#815) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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 https://github.com/ben-rogerson/twin.macro/discussions/814 --- src/core/lib/createTheme.ts | 11 ++++++++++- tests/arbitraryValues.test.ts | 12 ++++++++++++ 2 files changed, 22 insertions(+), 1 deletion(-) diff --git a/src/core/lib/createTheme.ts b/src/core/lib/createTheme.ts index 1dc261a..ce722af 100644 --- a/src/core/lib/createTheme.ts +++ b/src/core/lib/createTheme.ts @@ -18,7 +18,16 @@ function createTheme( defaultValue?: string, options = {} ): number | boolean | Record { - 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'], diff --git a/tests/arbitraryValues.test.ts b/tests/arbitraryValues.test.ts index 056cdd4..14762e4 100644 --- a/tests/arbitraryValues.test.ts +++ b/tests/arbitraryValues.test.ts @@ -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}]`'