UNPKG

react-native-unit-components

Version:

Unit React Native components

72 lines (61 loc) 2.39 kB
import { Platform } from 'react-native'; import type { FontWeight, UNFonts, UNFontSource, UNFontData } from '../../types/shared/fonts.types'; const getMimeType = (fileName: string): string => { const ext = fileName.split('.').pop()?.toLowerCase(); switch (ext) { case 'woff': return 'font/woff'; case 'woff2': return 'font/woff2'; case 'otf': return 'font/otf'; default: return 'font/ttf'; } }; const getUrl = (source: UNFontSource, iosFontBase64Map?: Record<string, string>): string => { if (Platform.OS == 'ios') { const base64 = iosFontBase64Map?.[source.fileName]; if (base64) { const mime = getMimeType(source.fileName); return `url('data:${mime};base64,${base64}')`; } 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[], iosFontBase64Map?: Record<string, string>): string => { const numOfSources = sources.length; const sourcesString = sources .map((source, index) => { const suffix = index === numOfSources - 1 ? ';' : ','; const url = getUrl(source, iosFontBase64Map); 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, iosFontBase64Map?: Record<string, string>): 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, iosFontBase64Map)); }); }); // Combine all the font faces into a single string return fontFaces.join('\n'); };