1import resolveAssetSource from './resolveAssetSource'; 2import { resolveBlurhashString, resolveThumbhashString } from './resolveHashString'; 3import { ImageNativeProps, ImageProps, ImageSource } from '../Image.types'; 4 5export function isBlurhashString(str: string): boolean { 6 return /^(blurhash:\/)?[\w#$%*+,\-.:;=?@[\]^_{}|~]+(\/[\d.]+)*$/.test(str); 7} 8 9// Base64 strings will be recognized as blurhash by default (to keep compatibility), 10// interpret as thumbhash only if correct uri scheme is provided 11export function isThumbhashString(str: string): boolean { 12 return str.startsWith('thumbhash:/'); 13} 14 15function resolveSource(source?: ImageSource | string | number | null): ImageSource | null { 16 if (typeof source === 'string') { 17 if (isBlurhashString(source)) { 18 return resolveBlurhashString(source); 19 } else if (isThumbhashString(source)) { 20 return resolveThumbhashString(source); 21 } 22 return { uri: source }; 23 } 24 if (typeof source === 'number') { 25 return resolveAssetSource(source); 26 } 27 if (typeof source === 'object' && (source?.blurhash || source?.thumbhash)) { 28 const { blurhash, thumbhash, ...restSource } = source; 29 const resolved = thumbhash 30 ? resolveThumbhashString(thumbhash) 31 : resolveBlurhashString(blurhash as string); 32 return { 33 ...resolved, 34 ...restSource, 35 }; 36 } 37 return source ?? null; 38} 39 40/** 41 * Resolves provided `source` prop to an array of objects expected by the native implementation. 42 */ 43export function resolveSources(sources?: ImageProps['source']): ImageNativeProps['source'] { 44 if (Array.isArray(sources)) { 45 return sources.map(resolveSource).filter(Boolean) as ImageSource[]; 46 } 47 return [resolveSource(sources)].filter(Boolean) as ImageSource[]; 48} 49