From b9db0c4a1db856c308442aa003fdc5ba68dc0be9 Mon Sep 17 00:00:00 2001 From: Federico Ciardi Date: Fri, 26 Mar 2021 11:18:25 +0100 Subject: [PATCH] feat: transform `hsl` to `hsla` --- __tests__/withAlphaVariable.test.js | 23 +++++++++++++++++++++++ src/util/withAlphaVariable.js | 12 ++++++++++-- 2 files changed, 33 insertions(+), 2 deletions(-) diff --git a/__tests__/withAlphaVariable.test.js b/__tests__/withAlphaVariable.test.js index 6fdc939f181d..19f9ffc97049 100644 --- a/__tests__/withAlphaVariable.test.js +++ b/__tests__/withAlphaVariable.test.js @@ -118,3 +118,26 @@ test('it allows a closure to be passed', () => { 'background-color': 'rgba(0, 0, 0, var(--tw-bg-opacity))', }) }) + +test('it transforms rgb and hsl to rgba and hsla', () => { + expect( + withAlphaVariable({ + color: 'rgb(50, 50, 50)', + property: 'background-color', + variable: '--tw-bg-opacity', + }) + ).toEqual({ + '--tw-bg-opacity': '1', + 'background-color': 'rgba(50, 50, 50, var(--tw-bg-opacity))', + }) + expect( + withAlphaVariable({ + color: 'hsl(50, 50%, 50%)', + property: 'background-color', + variable: '--tw-bg-opacity', + }) + ).toEqual({ + '--tw-bg-opacity': '1', + 'background-color': 'hsla(50, 50, 50, var(--tw-bg-opacity))', + }) +}) diff --git a/src/util/withAlphaVariable.js b/src/util/withAlphaVariable.js index d47dd275b0c0..7599eb5960b7 100644 --- a/src/util/withAlphaVariable.js +++ b/src/util/withAlphaVariable.js @@ -16,6 +16,12 @@ export function toRgba(color) { return [r, g, b, a === undefined && hasAlpha(color) ? 1 : a] } +export function toHsla(color) { + const [h, s, l, a] = createColor(color).hsl().array() + + return [h, s, l, a === undefined && hasAlpha(color) ? 1 : a] +} + export default function withAlphaVariable({ color, property, variable }) { if (_.isFunction(color)) { return { @@ -25,7 +31,9 @@ export default function withAlphaVariable({ color, property, variable }) { } try { - const [r, g, b, a] = toRgba(color) + const isHSL = color.startsWith('hsl') + + const [i, j, k, a] = isHSL ? toHsla(color) : toRgba(color) if (a !== undefined) { return { @@ -35,7 +43,7 @@ export default function withAlphaVariable({ color, property, variable }) { return { [variable]: '1', - [property]: `rgba(${r}, ${g}, ${b}, var(${variable}))`, + [property]: `${isHSL ? 'hsla' : 'rgba'}(${i}, ${j}, ${k}, var(${variable}))`, } } catch (error) { return {