UNPKG

@livelike/react-native

Version:

LiveLike React Native package

53 lines (46 loc) 1.45 kB
import { StyleProp, StyleSheet, TextStyle } from 'react-native'; import { useFonts } from './useFonts'; import { useMemo } from 'react'; import { FontFamilyType, FontWeightType } from '../types'; export type UseFontFamilyArgs = { style: StyleProp<TextStyle>; }; /** * @description useFontFamily hook returns an evaluated fontFamily based on fontWeight and fontStyle * This is useful in case of custom fonts. * @returns fontFamily and fontFamilyType */ export function useFontFamily({ style }: UseFontFamilyArgs): { fontFamily: FontWeightType; fontFamilyType: FontFamilyType; } { const { fonts } = useFonts(); return useMemo(() => { const fontFamilyType = getFontFamilyType(style); return { fontFamilyType, fontFamily: fonts[fontFamilyType], }; }, [style, fonts]); } function getFontFamilyType(style: StyleProp<TextStyle>): FontFamilyType { const { fontWeight, fontStyle } = StyleSheet.flatten(style); const isItalicFontStyle = fontStyle === 'italic'; const weightMap = { '100': 'thin', '200': 'extraLight', '300': 'light', '500': 'bold', '600': 'semiBold', bold: 'bold', '700': 'bold', '800': 'extraBold', '900': 'black', }; const weightKey = fontWeight?.toString(); const weightType = weightMap[weightKey]; if (weightType) { return isItalicFontStyle ? `${weightType}Italic` : weightType; } return isItalicFontStyle ? 'italic' : 'regular'; }