Skip to content

Commit

Permalink
fix for rgbaFloat (#700)
Browse files Browse the repository at this point in the history
  • Loading branch information
lukasoppermann authored Jul 21, 2023
1 parent 194102c commit a911592
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 4 deletions.
17 changes: 13 additions & 4 deletions src/transformers/colorToRgbaFloat.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,20 @@ import {mix, toHex} from 'color2k'
import {isColor} from '~/src/filters'
import type StyleDictionary from 'style-dictionary'
import {getTokenValue} from './utilities/getTokenValue'
import {rgbaFloatToHex} from './utilities/rgbaFloatToHex'

const toRgbaFloat = (token: StyleDictionary.TransformedToken, alpha?: number) => {
let tokenValue = getTokenValue(token)
let tokenMixColor = token.mix?.color
// get hex value from color string
// const hex = toHex(color)
const hex = toHex(mix(getTokenValue(token), token.mix?.color || getTokenValue(token), token.mix?.weight || 0))
if (isRgbaFloat(tokenValue)) {
tokenValue = rgbaFloatToHex(tokenValue, false)
}
if (tokenMixColor && isRgbaFloat(tokenMixColor)) {
tokenMixColor = rgbaFloatToHex(tokenMixColor, false)
}
// mix color with mix color and weight
const hex = toHex(mix(tokenValue, tokenMixColor || tokenValue, token.mix?.weight || 0))
// 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
Expand All @@ -27,7 +36,7 @@ const isRgbaFloat = (value: unknown) => {
'r' in value &&
'g' in value &&
'b' in value &&
sum(Object.values(value)) < 5
sum([value.r, value.g, value.b]) < 5
) {
return true
}
Expand All @@ -46,7 +55,7 @@ export const colorToRgbaFloat: StyleDictionary.Transform = {
matcher: isColor,
transformer: (token: StyleDictionary.TransformedToken) => {
// skip if value is already rgb float
if (isRgbaFloat(token.value)) return token.value
if (isRgbaFloat(token.value) && !('mix' in token) && !('alpha' in token)) return token.value
// convert hex or rgb values to rgba float
return toRgbaFloat(token, token.alpha)
},
Expand Down
5 changes: 5 additions & 0 deletions src/transformers/utilities/rgbaFloatToHex.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
export const rgbaFloatToHex = ({r, g, b, a}: {r: number; g: number; b: number; a?: number}, alpha = true): string => {
const values = [r, g, b, alpha === true && a ? a : undefined].filter(Boolean) as number[]

return `#${values.map(v => `${(v * 255).toString(16)}`.padEnd(2, '0')).join('')}`
}

0 comments on commit a911592

Please sign in to comment.