From 109dec16818c23d7b4f55e3c2fa976089ce962cf Mon Sep 17 00:00:00 2001 From: Haew Date: Fri, 1 May 2020 05:22:52 +0200 Subject: [PATCH] Allow colors to be defined as closures --- __tests__/withAlphaVariable.test.js | 12 ++++++++++++ src/util/withAlphaVariable.js | 7 +++++++ 2 files changed, 19 insertions(+) diff --git a/__tests__/withAlphaVariable.test.js b/__tests__/withAlphaVariable.test.js index ff5d3a529..12ec2df28 100644 --- a/__tests__/withAlphaVariable.test.js +++ b/__tests__/withAlphaVariable.test.js @@ -95,3 +95,15 @@ test('it ignores colors that already have an alpha channel', () => { 'background-color': 'hsla(240, 100%, 50%, 0.5)', }) }) + +test('it allows a closure to be passed', () => { + expect( + withAlphaVariable({ + color: variable => `rgba(0, 0, 0, var(${variable}))`, + property: 'background-color', + variable: '--bg-opacity', + }) + ).toEqual({ + 'background-color': 'rgba(0, 0, 0, var(--bg-opacity))', + }) +}) diff --git a/src/util/withAlphaVariable.js b/src/util/withAlphaVariable.js index 7083809b2..cd42606e0 100644 --- a/src/util/withAlphaVariable.js +++ b/src/util/withAlphaVariable.js @@ -1,4 +1,5 @@ import createColor from 'color' +import _ from 'lodash' function hasAlpha(color) { return ( @@ -18,6 +19,12 @@ function toRgba(color) { } export default function withAlphaVariable({ color, property, variable }) { + if (_.isFunction(color)) { + return { + [property]: color(variable), + } + } + try { const [r, g, b, a] = toRgba(color)