Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: transform hsl to hsla #3850

Merged
merged 5 commits into from Apr 30, 2021
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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))',
fedeci marked this conversation as resolved.
Show resolved Hide resolved
})
})
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)
Copy link
Contributor Author

@fedeci fedeci Mar 26, 2021

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We use generic component names because we don't know if it will be rgb or hsl


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