UNPKG

react-native-unit-components

Version:

Unit React Native components

57 lines (47 loc) 1.77 kB
import { Platform } from 'react-native'; import type { FontWeight, UNFonts, UNFontSource, UNFontData } from '../../types/shared/fonts.types'; const getUrl = (source: UNFontSource): string => { if (Platform.OS == 'ios') { return `url('${source.fileName}')`; } // Handle '/' of dir Relative path let relativeDirPath = source.assetDirRelativePath; if (source.assetDirRelativePath[-1] !== '/') { relativeDirPath = `${source.assetDirRelativePath}/`; } if (source.assetDirRelativePath[0] !== '/') { relativeDirPath = `/${source.assetDirRelativePath}`; } return `url('file:///android_asset${relativeDirPath}${source.fileName}')`; }; const getFontFace = (fontFamily: string, fontWeight: FontWeight, sources: UNFontSource[]): string => { const numOfSources = sources.length; const sourcesString = sources .map((source, index) => { const suffix = index === numOfSources - 1 ? ';' : ','; const url = getUrl(source); const format = source?.format ? `format('${source.format}')` : ''; return `${url} ${format}${suffix}`; }) .join('\n'); return ` @font-face { font-family: '${fontFamily}'; src: ${sourcesString} font-weight: ${fontWeight.valueOf()}; } `; }; export const getFontFacesString = (fonts?: UNFonts): string => { if (!fonts) return ''; const fontFaces: string[] = []; // Iterate over all the fonts and their variants // create font-face for each variant Object.entries(fonts).forEach(([familyName, familyFonts]) => { familyFonts.forEach((fontData: UNFontData) => { fontFaces.push(getFontFace(familyName, fontData.fontWeight, fontData.sources)); }); }); // Combine all the font faces into a single string return fontFaces.join('\n'); };