diff --git a/src/transformers/colorToRgbaFloat.ts b/src/transformers/colorToRgbaFloat.ts index 7d6a315cb..f7b55956c 100644 --- a/src/transformers/colorToRgbaFloat.ts +++ b/src/transformers/colorToRgbaFloat.ts @@ -4,6 +4,7 @@ import type StyleDictionary from 'style-dictionary' import {getTokenValue} from './utilities/getTokenValue' import {rgbaFloatToHex} from './utilities/rgbaFloatToHex' import mix from './utilities/mix' +import {hexToRgbaFloat} from './utilities/hexToRgbaFloat' const toRgbaFloat = (token: StyleDictionary.TransformedToken, alpha?: number) => { let tokenValue = getTokenValue(token) @@ -20,15 +21,8 @@ const toRgbaFloat = (token: StyleDictionary.TransformedToken, alpha?: number) => if (token.mix && token.mix.color && token.mix.weight) { hex = toHex(mix(tokenValue, tokenMixColor, token.mix.weight)) } - // retrieve spots from hex value (hex 3, hex 6 or hex 8) - const result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})?$/i.exec(hex) ?? ['00', '00', '00'] - // return parsed rgba float object using alpha value from token, from hex code or defaults to 1 - return { - r: parseInt(result[1], 16) / 255, - g: parseInt(result[2], 16) / 255, - b: parseInt(result[3], 16) / 255, - a: alpha !== undefined ? alpha : result[4] ? parseInt(result[4], 16) / 255 : 1, - } + // return color as RgbaFloat + return hexToRgbaFloat(hex, alpha) } // sum up the values of all values in an array diff --git a/src/transformers/utilities/hexToRgbaFloat.ts b/src/transformers/utilities/hexToRgbaFloat.ts new file mode 100644 index 000000000..aaa1205fd --- /dev/null +++ b/src/transformers/utilities/hexToRgbaFloat.ts @@ -0,0 +1,18 @@ +type RgbaFloat = { + r: number + g: number + b: number + a?: number +} + +export const hexToRgbaFloat = (hex: string, alpha?: number): RgbaFloat => { + // retrieve spots from hex value (hex 3, hex 6 or hex 8) + const result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})?$/i.exec(hex) ?? ['00', '00', '00'] + // return parsed rgba float object using alpha value from token, from hex code or defaults to 1 + return { + r: parseInt(result[1], 16) / 255, + g: parseInt(result[2], 16) / 255, + b: parseInt(result[3], 16) / 255, + a: alpha !== undefined ? alpha : result[4] ? parseInt(result[4], 16) / 255 : 1, + } +}