All files / react-native-web/src/exports/Image index.js

81.68% Statements 107/131
73.33% Branches 77/105
81.25% Functions 13/16
81.68% Lines 107/131

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382                                                  3x 3x 3x 3x   3x 3x     62x                         62x 62x       62x 62x   62x     62x 1x   62x 1x 1x 1x     62x 2x     62x 4x         62x 62x 62x 62x 62x 62x   62x 62x   62x       62x 2x 2x 60x 21x 21x         164x 164x   8x 8x 8x 8x   8x 16x     8x 8x 156x 28x 128x 47x     164x 75x   75x             164x                         3x                               62x   62x 62x             62x 40x 40x 14x 14x 3x     37x     62x 62x 62x 62x 62x 62x 62x         62x 62x 62x 62x 62x 62x     62x                     62x                                         62x 62x 43x   43x 17x 17x 6x     17x     11x 11x 6x   11x 6x                                       86x           43x     62x                                                 3x     3x           3x       3x 1x     3x 1x     3x                   3x                                         3x                                                  
/**
 * Copyright (c) Nicolas Gallagher.
 * Copyright (c) Facebook, Inc. and its affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 *
 * @flow
 */
 
import type { ImageProps } from './types';
 
import * as React from 'react';
import createElement from '../createElement';
import css from '../StyleSheet/css';
import { getAssetByID } from '../../modules/AssetRegistry';
import resolveShadowValue from '../StyleSheet/resolveShadowValue';
import ImageLoader from '../../modules/ImageLoader';
import PixelRatio from '../PixelRatio';
import StyleSheet from '../StyleSheet';
import TextAncestorContext from '../Text/TextAncestorContext';
import View from '../View';
 
export type { ImageProps };
 
const ERRORED = 'ERRORED';
const LOADED = 'LOADED';
const LOADING = 'LOADING';
const IDLE = 'IDLE';
 
let _filterId = 0;
const svgDataUriPattern = /^(data:image\/svg\+xml;utf8,)(.*)/;
 
function createTintColorSVG(tintColor, id) {
  return tintColor && id != null ? (
    <svg style={{ position: 'absolute', height: 0, visibility: 'hidden', width: 0 }}>
      <defs>
        <filter id={`tint-${id}`} suppressHydrationWarning={true}>
          <feFlood floodColor={`${tintColor}`} key={tintColor} />
          <feComposite in2="SourceAlpha" operator="atop" />
        </filter>
      </defs>
    </svg>
  ) : null;
}
 
function getFlatStyle(style, blurRadius, filterId) {
  const flatStyle = { ...StyleSheet.flatten(style) };
  const { filter, resizeMode, shadowOffset, tintColor } = flatStyle;
 
  // Add CSS filters
  // React Native exposes these features as props and proprietary styles
  const filters = [];
  let _filter = null;
 
  Iif (filter) {
    filters.push(filter);
  }
  if (blurRadius) {
    filters.push(`blur(${blurRadius}px)`);
  }
  if (shadowOffset) {
    const shadowString = resolveShadowValue(flatStyle);
    Eif (shadowString) {
      filters.push(`drop-shadow(${shadowString})`);
    }
  }
  if (tintColor && filterId != null) {
    filters.push(`url(#tint-${filterId})`);
  }
 
  if (filters.length > 0) {
    _filter = filters.join(' ');
  }
 
  // These styles are converted to CSS filters applied to the
  // element displaying the background image.
  delete flatStyle.blurRadius;
  delete flatStyle.shadowColor;
  delete flatStyle.shadowOpacity;
  delete flatStyle.shadowOffset;
  delete flatStyle.shadowRadius;
  delete flatStyle.tintColor;
  // These styles are not supported on View
  delete flatStyle.overlayColor;
  delete flatStyle.resizeMode;
 
  return [flatStyle, resizeMode, _filter, tintColor];
}
 
function resolveAssetDimensions(source) {
  if (typeof source === 'number') {
    const { height, width } = getAssetByID(source);
    return { height, width };
  } else if (source != null && !Array.isArray(source) && typeof source === 'object') {
    const { height, width } = source;
    return { height, width };
  }
}
 
function resolveAssetUri(source): ?string {
  let uri = null;
  if (typeof source === 'number') {
    // get the URI from the packager
    const asset = getAssetByID(source);
    let scale = asset.scales[0];
    Eif (asset.scales.length > 1) {
      const preferredScale = PixelRatio.get();
      // Get the scale which is closest to the preferred scale
      scale = asset.scales.reduce((prev, curr) =>
        Math.abs(curr - preferredScale) < Math.abs(prev - preferredScale) ? curr : prev
      );
    }
    const scaleSuffix = scale !== 1 ? `@${scale}x` : '';
    uri = asset ? `${asset.httpServerLocation}/${asset.name}${scaleSuffix}.${asset.type}` : '';
  } else if (typeof source === 'string') {
    uri = source;
  } else if (source && typeof source.uri === 'string') {
    uri = source.uri;
  }
 
  if (uri) {
    const match = uri.match(svgDataUriPattern);
    // inline SVG markup may contain characters (e.g., #, ") that need to be escaped
    Iif (match) {
      const [, prefix, svg] = match;
      const encodedSvg = encodeURIComponent(svg);
      return `${prefix}${encodedSvg}`;
    }
  }
 
  return uri;
}
 
interface ImageStatics {
  getSize: (
    uri: string,
    success: (width: number, height: number) => void,
    failure: () => void
  ) => void;
  prefetch: (uri: string) => Promise<void>;
  queryCache: (uris: Array<string>) => Promise<{| [uri: string]: 'disk/memory' |}>;
}
 
const Image: React.AbstractComponent<ImageProps, React.ElementRef<typeof View>> = React.forwardRef(
  (props, ref) => {
    const {
      accessibilityLabel,
      blurRadius,
      defaultSource,
      draggable,
      onError,
      onLayout,
      onLoad,
      onLoadEnd,
      onLoadStart,
      pointerEvents,
      source,
      style,
      ...rest
    } = props;
 
    Eif (process.env.NODE_ENV !== 'production') {
      Iif (props.children) {
        throw new Error(
          'The <Image> component cannot contain children. If you want to render content on top of the image, consider using the <ImageBackground> component or absolute positioning.'
        );
      }
    }
 
    const [state, updateState] = React.useState(() => {
      const uri = resolveAssetUri(source);
      if (uri != null) {
        const isLoaded = ImageLoader.has(uri);
        if (isLoaded) {
          return LOADED;
        }
      }
      return IDLE;
    });
 
    const [layout, updateLayout] = React.useState({});
    const hasTextAncestor = React.useContext(TextAncestorContext);
    const hiddenImageRef = React.useRef(null);
    const filterRef = React.useRef(_filterId++);
    const requestRef = React.useRef(null);
    const shouldDisplaySource = state === LOADED || (state === LOADING && defaultSource == null);
    const [flatStyle, _resizeMode, filter, tintColor] = getFlatStyle(
      style,
      blurRadius,
      filterRef.current
    );
    const resizeMode = props.resizeMode || _resizeMode || 'cover';
    const selectedSource = shouldDisplaySource ? source : defaultSource;
    const displayImageUri = resolveAssetUri(selectedSource);
    const imageSizeStyle = resolveAssetDimensions(selectedSource);
    const backgroundImage = displayImageUri ? `url("${displayImageUri}")` : null;
    const backgroundSize = getBackgroundSize();
 
    // Accessibility image allows users to trigger the browser's image context menu
    const hiddenImage = displayImageUri
      ? createElement('img', {
          alt: accessibilityLabel || '',
          classList: [classes.accessibilityImage],
          draggable: draggable || false,
          ref: hiddenImageRef,
          src: displayImageUri
        })
      : null;
 
    function getBackgroundSize(): ?string {
      Iif (hiddenImageRef.current != null && (resizeMode === 'center' || resizeMode === 'repeat')) {
        const { naturalHeight, naturalWidth } = hiddenImageRef.current;
        const { height, width } = layout;
        if (naturalHeight && naturalWidth && height && width) {
          const scaleFactor = Math.min(1, width / naturalWidth, height / naturalHeight);
          const x = Math.ceil(scaleFactor * naturalWidth);
          const y = Math.ceil(scaleFactor * naturalHeight);
          return `${x}px ${y}px`;
        }
      }
    }
 
    function handleLayout(e) {
      if (resizeMode === 'center' || resizeMode === 'repeat' || onLayout) {
        const { layout } = e.nativeEvent;
        onLayout && onLayout(e);
        updateLayout(layout);
      }
    }
 
    // Image loading
    const uri = resolveAssetUri(source);
    React.useEffect(() => {
      abortPendingRequest();
 
      if (uri != null) {
        updateState(LOADING);
        if (onLoadStart) {
          onLoadStart();
        }
 
        requestRef.current = ImageLoader.load(
          uri,
          function load(e) {
            updateState(LOADED);
            if (onLoad) {
              onLoad(e);
            }
            if (onLoadEnd) {
              onLoadEnd();
            }
          },
          function error() {
            updateState(ERRORED);
            if (onError) {
              onError({
                nativeEvent: {
                  error: `Failed to load resource ${uri} (404)`
                }
              });
            }
            if (onLoadEnd) {
              onLoadEnd();
            }
          }
        );
      }
 
      function abortPendingRequest() {
        Iif (requestRef.current != null) {
          ImageLoader.abort(requestRef.current);
          requestRef.current = null;
        }
      }
 
      return abortPendingRequest;
    }, [uri, requestRef, updateState, onError, onLoad, onLoadEnd, onLoadStart]);
 
    return (
      <View
        {...rest}
        accessibilityLabel={accessibilityLabel}
        onLayout={handleLayout}
        pointerEvents={pointerEvents}
        ref={ref}
        style={[styles.root, hasTextAncestor && styles.inline, imageSizeStyle, flatStyle]}
      >
        <View
          style={[
            styles.image,
            resizeModeStyles[resizeMode],
            { backgroundImage, filter },
            backgroundSize != null && { backgroundSize }
          ]}
          suppressHydrationWarning={true}
        />
        {hiddenImage}
        {createTintColorSVG(tintColor, filterRef.current)}
      </View>
    );
  }
);
 
Image.displayName = 'Image';
 
// $FlowIgnore: This is the correct type, but casting makes it unhappy since the variables aren't defined yet
const ImageWithStatics = (Image: React.AbstractComponent<
  ImageProps,
  React.ElementRef<typeof View>
> &
  ImageStatics);
 
ImageWithStatics.getSize = function (uri, success, failure) {
  ImageLoader.getSize(uri, success, failure);
};
 
ImageWithStatics.prefetch = function (uri) {
  return ImageLoader.prefetch(uri);
};
 
ImageWithStatics.queryCache = function (uris) {
  return ImageLoader.queryCache(uris);
};
 
const classes = css.create({
  accessibilityImage: {
    ...StyleSheet.absoluteFillObject,
    height: '100%',
    opacity: 0,
    width: '100%',
    zIndex: -1
  }
});
 
const styles = StyleSheet.create({
  root: {
    flexBasis: 'auto',
    overflow: 'hidden',
    zIndex: 0
  },
  inline: {
    display: 'inline-flex'
  },
  image: {
    ...StyleSheet.absoluteFillObject,
    backgroundColor: 'transparent',
    backgroundPosition: 'center',
    backgroundRepeat: 'no-repeat',
    backgroundSize: 'cover',
    height: '100%',
    width: '100%',
    zIndex: -1
  }
});
 
const resizeModeStyles = StyleSheet.create({
  center: {
    backgroundSize: 'auto'
  },
  contain: {
    backgroundSize: 'contain'
  },
  cover: {
    backgroundSize: 'cover'
  },
  none: {
    backgroundPosition: '0 0',
    backgroundSize: 'auto'
  },
  repeat: {
    backgroundPosition: '0 0',
    backgroundRepeat: 'repeat',
    backgroundSize: 'auto'
  },
  stretch: {
    backgroundSize: '100% 100%'
  }
});
 
export default ImageWithStatics;