1- import createColor from 'color '
1+ import culori from 'culori '
22import _ from 'lodash'
33
4- function hasAlpha ( color ) {
5- return (
6- color . startsWith ( 'rgba(' ) ||
7- color . startsWith ( 'hsla(' ) ||
8- ( color . startsWith ( '#' ) && color . length === 9 ) ||
9- ( color . startsWith ( '#' ) && color . length === 5 )
10- )
11- }
12-
13- export function toRgba ( color ) {
14- const [ r , g , b , a ] = createColor ( color ) . rgb ( ) . array ( )
15-
16- return [ r , g , b , a === undefined && hasAlpha ( color ) ? 1 : a ]
17- }
18-
19- export function toHsla ( color ) {
20- const [ h , s , l , a ] = createColor ( color ) . hsl ( ) . array ( )
21-
22- return [ h , `${ s } %` , `${ l } %` , a === undefined && hasAlpha ( color ) ? 1 : a ]
4+ function isValidColor ( color ) {
5+ return culori . parse ( color ) !== undefined
236}
247
258export function withAlphaValue ( color , alphaValue , defaultValue ) {
269 if ( _ . isFunction ( color ) ) {
2710 return color ( { opacityValue : alphaValue } )
2811 }
2912
30- try {
31- const isHSL = color . startsWith ( 'hsl' )
32- const [ i , j , k ] = isHSL ? toHsla ( color ) : toRgba ( color )
33- return `${ isHSL ? 'hsla' : 'rgba' } (${ i } , ${ j } , ${ k } , ${ alphaValue } )`
34- } catch {
35- return defaultValue
13+ if ( isValidColor ( color ) ) {
14+ // Parse color
15+ const parsed = culori . parse ( color )
16+
17+ // Apply alpha value
18+ parsed . alpha = alphaValue
19+
20+ // Return formatted string
21+ if ( parsed . mode === 'hsl' ) {
22+ return culori . formatHsl ( parsed )
23+ } else {
24+ return culori . formatRgb ( parsed )
25+ }
3626 }
27+
28+ return defaultValue
3729}
3830
3931export default function withAlphaVariable ( { color, property, variable } ) {
@@ -44,24 +36,32 @@ export default function withAlphaVariable({ color, property, variable }) {
4436 }
4537 }
4638
47- try {
48- const isHSL = color . startsWith ( 'hsl' )
49-
50- const [ i , j , k , a ] = isHSL ? toHsla ( color ) : toRgba ( color )
39+ if ( isValidColor ( color ) ) {
40+ const { alpha = 1 , mode } = culori . parse ( color )
5141
52- if ( a !== undefined ) {
42+ if ( alpha !== 1 ) {
43+ // Has an alpha value, return color as-is
5344 return {
5445 [ property ] : color ,
5546 }
5647 }
5748
58- return {
59- [ variable ] : '1' ,
60- [ property ] : `${ isHSL ? 'hsla' : 'rgba' } (${ i } , ${ j } , ${ k } , var(${ variable } ))` ,
49+ let value
50+ if ( mode === 'hsl' ) {
51+ const { h, s, l } = culori . hsl ( color )
52+ value = `hsla(${ h } , ${ s } , ${ l } , var(${ variable } ))`
53+ } else {
54+ const { r, g, b } = culori . rgb ( color )
55+ value = `rgba(${ r } , ${ g } , ${ b } , var(${ variable } ))`
6156 }
62- } catch ( error ) {
57+
6358 return {
64- [ property ] : color ,
59+ [ variable ] : '1' ,
60+ [ property ] : value ,
6561 }
6662 }
63+
64+ return {
65+ [ property ] : color ,
66+ }
6767}
0 commit comments