import React from 'react' ; import PropTypes from 'prop-types' ; import { Image as NativeImage , ImageSourcePropType } from 'react-native' ; import SvgUri from 'react-native-svg-uri' ; import { mediaApi } from '@sitecore-jss/sitecore-jss/media' ; export interface ImageFieldValue { /** HTML attributes that will be appended to the rendered <img /> tag. */ [ attributeName ] : unknown ; src ? : string | number ; width ? : number ; height ? : number ; style ? : { [ key ] : unknown ; } ; } export interface ImageField { value ? : ImageFieldValue ; editable ? : string ; } export interface ImageProps { /** HTML attributes that will be appended to the rendered <img /> tag. */ [ attributeName ] : unknown ; /** The image field data. */ media : ImageField | ImageFieldValue | null ; field ? : ImageField | ImageFieldValue | null ; /**
     * Parameters that will be attached to Sitecore media URLs
     */ imageUrlParams ? : { [ paramName ] : string ; } | null ; } const getImageAttrs = ( { src , width , height , style , ... otherAttrs } , imageUrlParams ? ) => { if ( ! src ) { return null ; } const newAttrs = { ... otherAttrs } ; const imgStyles = { } ; if ( width ) { imgStyles . width = typeof width !== 'number' ? Number ( width ) : width ; } if ( height ) { imgStyles . height = typeof height !== 'number' ? Number ( height ) : height ; } if ( typeof src === 'number' ) { newAttrs . source = src ; } else { const uri = mediaApi . updateImageUrl ( src , imageUrlParams ) ; newAttrs . source = { uri } ; } if ( isSvgImage ( newAttrs . source as ImageSourcePropType ) ) { newAttrs . style = { ... ( style || { } ) , ... imgStyles } ; } else { newAttrs . style = style ? [ imgStyles , style ] : imgStyles ; } return newAttrs ; } ; export const isSvgImage = ( source ) => { const isSvg = /\.svg($|\?|\&)/g ; const src = NativeImage . resolveAssetSource ( source ) ; return src && isSvg . test ( src . uri ) ; } ; export const Image = ( { media , imageUrlParams , field , ... otherProps } ) => { let dynamicMedia = media ; if ( field && ! media ) { dynamicMedia = field ; } if ( ! dynamicMedia || ( ! dynamicMedia . value && ! ( dynamicMedia as ImageFieldValue ) . src ) ) { return null ; } const img = ( dynamicMedia as ImageFieldValue ) . src ? dynamicMedia : ( dynamicMedia as ImageField ) . value ; if ( ! img ) { return null ; } const attrs = getImageAttrs ( { ... ( img as ImageFieldValue ) , ... otherProps } , imageUrlParams ) ; if ( attrs && isSvgImage ( attrs . source as ImageSourcePropType ) ) return < SvgUri { ... attrs } / > ; if ( attrs ) return < NativeImage { ... attrs } source = { attrs . source as ImageSourcePropType } / > ; return null ; } ; Image . propTypes = { media : PropTypes . oneOfType ( [ PropTypes . shape ( { src : PropTypes . oneOfType ( [ PropTypes . string , PropTypes . number ] ) } ) , PropTypes . shape ( { value : PropTypes . object } ) , ] ) , imageUrlParams : PropTypes . any } ; Image . displayName = 'Image' ;