Skip to content

Commit

Permalink
feat: transform hsl to hsla
Browse files Browse the repository at this point in the history
  • Loading branch information
fedeci committed Mar 26, 2021
1 parent e227320 commit b9db0c4
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 2 deletions.
23 changes: 23 additions & 0 deletions __tests__/withAlphaVariable.test.js
Expand Up @@ -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))',
})
})
12 changes: 10 additions & 2 deletions src/util/withAlphaVariable.js
Expand Up @@ -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 {
Expand All @@ -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 {
Expand All @@ -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 {
Expand Down

0 comments on commit b9db0c4

Please sign in to comment.