Skip to content

Commit e55c87f

Browse files
extract fn (#811)
1 parent 0bc0855 commit e55c87f

File tree

2 files changed

+21
-9
lines changed

2 files changed

+21
-9
lines changed

src/transformers/colorToRgbaFloat.ts

Lines changed: 3 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ import type StyleDictionary from 'style-dictionary'
44
import {getTokenValue} from './utilities/getTokenValue'
55
import {rgbaFloatToHex} from './utilities/rgbaFloatToHex'
66
import mix from './utilities/mix'
7+
import {hexToRgbaFloat} from './utilities/hexToRgbaFloat'
78

89
const toRgbaFloat = (token: StyleDictionary.TransformedToken, alpha?: number) => {
910
let tokenValue = getTokenValue(token)
@@ -20,15 +21,8 @@ const toRgbaFloat = (token: StyleDictionary.TransformedToken, alpha?: number) =>
2021
if (token.mix && token.mix.color && token.mix.weight) {
2122
hex = toHex(mix(tokenValue, tokenMixColor, token.mix.weight))
2223
}
23-
// retrieve spots from hex value (hex 3, hex 6 or hex 8)
24-
const result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})?$/i.exec(hex) ?? ['00', '00', '00']
25-
// return parsed rgba float object using alpha value from token, from hex code or defaults to 1
26-
return {
27-
r: parseInt(result[1], 16) / 255,
28-
g: parseInt(result[2], 16) / 255,
29-
b: parseInt(result[3], 16) / 255,
30-
a: alpha !== undefined ? alpha : result[4] ? parseInt(result[4], 16) / 255 : 1,
31-
}
24+
// return color as RgbaFloat
25+
return hexToRgbaFloat(hex, alpha)
3226
}
3327

3428
// sum up the values of all values in an array
Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
type RgbaFloat = {
2+
r: number
3+
g: number
4+
b: number
5+
a?: number
6+
}
7+
8+
export const hexToRgbaFloat = (hex: string, alpha?: number): RgbaFloat => {
9+
// retrieve spots from hex value (hex 3, hex 6 or hex 8)
10+
const result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})?$/i.exec(hex) ?? ['00', '00', '00']
11+
// return parsed rgba float object using alpha value from token, from hex code or defaults to 1
12+
return {
13+
r: parseInt(result[1], 16) / 255,
14+
g: parseInt(result[2], 16) / 255,
15+
b: parseInt(result[3], 16) / 255,
16+
a: alpha !== undefined ? alpha : result[4] ? parseInt(result[4], 16) / 255 : 1,
17+
}
18+
}

0 commit comments

Comments
 (0)