Support for rgba format?

#4 · open · 2 comments

View on GitHub ↗

ilibaz

It would be nice to support rgba format in CSS linear gradients which is more commonly used than HEXa. Currently I had to implement this parsing before using this lib: ``` import rgb2hex from "rgb2hex" const addAlpha = (color: string, opacity: number) => { const _opacity = Math.floor(opacity * 255) .toString(16) .padStart(2, "0") return color + _opacity } const gradientString = "linear-gradient(88.56deg, rgba(159, 130, 255, 1.0) 0%, rgba(246, 136, 208, 1.0) 100%)" const rgbaRegex = /rgba?\((\d+),\s*(\d+),\s*(\d+)(?:,\s*(\d+(?:\.\d+)?))?\)/g const rgbaMatches = [...gradientString.matchAll(rgbaRegex)] rgbaMatches.forEach(match => { const hexObj = rgb2hex(match[0]) gradientString = gradientString.replace(match[0], addAlpha(hexObj.hex, hexObj.alpha)) }) ```

Comments

nandorojo

I think I fixed this by replacing the source function with this: ```ts export function gradientPropsFromCSS(str: string) { const values = str?.match(/([a-zA-Z0-9_-]+)\((.*)\).*/) if (!values) throw new Error('Invalid CSS Gradient function: ' + str) const [, method, argString] = values const args = [] let buffer = '' let openParens = 0; for (let i = 0; i < argString.length; i++) { const char = argString[i]; if (char === ',' && openParens === 0) { args.push(buffer.trim()); buffer = ''; } else { buffer += char; if (char === '(') { openParens++; } else if (char === ')') { openParens--; } } } args.push(buffer.trim()); return parseGradient( { args, method }, { width: 1, height: 1 } ) } ``` Will add some unit tests to be sure.

nandorojo

this can be closed now.