Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 3 additions & 9 deletions src/transformers/colorToRgbaFloat.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand All @@ -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
Expand Down
18 changes: 18 additions & 0 deletions src/transformers/utilities/hexToRgbaFloat.ts
Original file line number Diff line number Diff line change
@@ -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,
}
}