UNPKG

react-native-unit-components

Version:

Unit React Native components

71 lines (60 loc) 2.08 kB
import { FontWeight, UNFontData } from '../types/shared'; import { UnitComponentsSDK } from '../unitComponentsSdkManager/UnitComponentsSdkManager'; const getFontWeightName = (familyFonts: UNFontData[], fontWeight?: number | string) => { /** * Given family variants and the required weight * Return the closet font that defined by the client. */ if (!fontWeight || fontWeight === 'normal') return 'Regular'; if (fontWeight === 'bold') return 'Bold'; const fontWeightNumber = Number(fontWeight); // Select the closet variant let selectedFontWeight = FontWeight.Regular.valueOf(); let minDistance = 1000; familyFonts.forEach((fontData: UNFontData) => { const currDistance = Math.abs(fontData.fontWeight - fontWeightNumber); if (currDistance < minDistance) { minDistance = currDistance; selectedFontWeight = fontData.fontWeight.valueOf(); } }); // FontWeight to String switch (selectedFontWeight) { case FontWeight.Thin: return 'Thin'; case FontWeight.ExtraLight: return 'ExtraLight'; case FontWeight.Light: return 'Light'; case FontWeight.Regular: return 'Regular'; case FontWeight.Medium: return 'Medium'; case FontWeight.SemiBold: return 'SemiBold'; case FontWeight.Bold: return 'Bold'; case FontWeight.ExtraBold: return 'ExtraBold'; case FontWeight.Black: return 'Black'; default: return 'Regular'; } }; export const getFontName = (fontFamily: string, fontWeight: number | string): string => { /* * Get the font family name and the font weight name from the THEME object. * Then, return a possible font. */ const fontsInApp = UnitComponentsSDK.getFonts(); if (!fontsInApp) { throw new Error('Fonts are not found in the app'); } const familyFonts = fontsInApp[fontFamily]; if (!familyFonts) { throw new Error(`Font family ${fontFamily} not found in the app's fonts`); } const fontWeightName = getFontWeightName(familyFonts, fontWeight); return `${fontFamily}-${fontWeightName}`; };