Skip to content

Commit

Permalink
convertFloatToPixel (#908)
Browse files Browse the repository at this point in the history
* convertFloatToPixel

* rm unitless
  • Loading branch information
lukasoppermann authored Apr 19, 2024
1 parent 108d613 commit ffbb8ef
Show file tree
Hide file tree
Showing 3 changed files with 40 additions and 0 deletions.
6 changes: 6 additions & 0 deletions src/PrimerStyleDictionary.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ import {
shadowToCss,
typographyToCss,
dimensionToRemPxArray,
floatToPixel,
} from './transformers'
import {
javascriptCommonJs,
Expand Down Expand Up @@ -132,6 +133,11 @@ StyleDictionary.registerTransform({
...colorToHex,
})

StyleDictionary.registerTransform({
name: 'float/pixel',
...floatToPixel,
})

StyleDictionary.registerTransform({
name: 'dimension/rem',
...dimensionToRem,
Expand Down
33 changes: 33 additions & 0 deletions src/transformers/floatToPixel.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
import type StyleDictionary from 'style-dictionary'
import {isNumber} from '../filters'
/**
* takes a value and returns it if its a px string if it is a float and the token has a fontSize value in extensions['org.primer.data']
* @param value
* @returns string
*/
export const convertFloatToPixel = (token: StyleDictionary.TransformedToken) => {
// short circut if value is not a number
if (
typeof token.value !== 'number' ||
!token.$extensions?.['org.primer.data']?.fontSize ||
typeof token.$extensions?.['org.primer.data']?.fontSize !== 'number'
) {
return token.value
}
// convert value
const convertedValue = token.$extensions?.['org.primer.data']?.fontSize * token.value
// return converted value
return `${convertedValue}px`
}
/**
* @description converts a float value to a pixel value based on the provided fontSize on the tokersn extension
* @type value transformer — [StyleDictionary.ValueTransform](https://github.com/amzn/style-dictionary/blob/main/types/Transform.d.ts)
* @matcher matches all tokens of $type `isNumber`
* @transformer returns a pixel string
*/
export const floatToPixel: StyleDictionary.Transform = {
type: `value`,
transitive: true,
matcher: isNumber,
transformer: (token: StyleDictionary.TransformedToken): string => convertFloatToPixel(token),
}
1 change: 1 addition & 0 deletions src/transformers/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ export {colorToHexAlpha} from './colorToHexAlpha'
export {colorToHexMix} from './colorToHexMix'
export {colorToRgbAlpha} from './colorToRgbAlpha'
export {colorToRgbaFloat} from './colorToRgbaFloat'
export {floatToPixel} from './floatToPixel'
export {dimensionToRem} from './dimensionToRem'
export {dimensionToRemPxArray} from './dimensionToRemPxArray'
export {dimensionToPixelUnitless} from './dimensionToPixelUnitless'
Expand Down

0 comments on commit ffbb8ef

Please sign in to comment.