-
-
Save sibelius/2667e05b330ed518386e13ccaca4670c to your computer and use it in GitHub Desktop.
Makes React Native components look more consistent on different device sizes. The base size is an iPhone 6.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import _ from 'lodash' | |
import { Dimensions, PixelRatio } from 'react-native' | |
import { platformIsIos } from 'expresso-common/common/platform' | |
const { height } = Dimensions.get('window') | |
const iphone6Height = 667 | |
const pixelRatio = PixelRatio.get() | |
const fieldsToNormalize = [ | |
'fontSize', | |
'lineHeight', | |
'letterSpacing', | |
'width', | |
'height', | |
'margin', | |
'marginTop', | |
'marginBottom', | |
'marginLeft', | |
'marginRight', | |
'padding', | |
'paddingTop', | |
'paddingBottom', | |
'paddingLeft', | |
'paddingRight', | |
] | |
const normalizeFontIos = (size) => { | |
return size | |
} | |
export const normalizeFont = (size) => { | |
if (platformIsIos()) { | |
return normalizeFontIos(size) | |
} | |
if (pixelRatio === 2) { | |
return Math.round(size * 1) | |
} | |
return size * 1 | |
} | |
export const normalizeValue = (value) => { | |
return Math.round((height / iphone6Height) * value) | |
} | |
export const normalizeKeyValue = (styleKey, value) => { | |
if (['fontSize', 'lineHeight', 'letterSpacing'].includes(styleKey)) { | |
return normalizeFont(value) | |
} | |
return Math.round((height / iphone6Height) * value) | |
} | |
export const denormalizeValue = (value) => { | |
return Math.round((iphone6Height / height) * value) | |
} | |
export function normalizeStyle(style) { | |
const normalizedStyle = _.mapValues(_.pick(style, fieldsToNormalize), (value, key) => normalizeKeyValue(key, value)) | |
return { | |
..._.omit(style, fieldsToNormalize), | |
...normalizedStyle | |
} | |
} | |
export default function normalizeStyles(styles) { | |
return _.mapValues(styles, (style) => normalizeStyle(style)) | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment