All files / atom/image/src index.js

95.83% Statements 23/24
86.66% Branches 26/30
87.5% Functions 7/8
95.83% Lines 23/24

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                                              1x                                           9x 9x 9x 9x   9x 7x 7x     9x 8x 8x 1x 1x       9x 8x     9x 1x 1x 1x     9x       9x                                                                                     1x 1x                                                                                                                                
import {useCallback, useEffect, useRef, useState, forwardRef} from 'react'
 
import cx from 'classnames'
import PropTypes from 'prop-types'
 
import Injector from '@s-ui/react-primitive-injector'
import PolymorphicElement from '@s-ui/react-primitive-polymorphic-element'
 
import ErrorImage from './ErrorImage.js'
import {
  BASE_CLASS,
  BASE_CLASS_FIGURE,
  CLASS_ERROR,
  CLASS_IMAGE,
  CLASS_PLACEHOLDER,
  CLASS_SKELETON,
  CLASS_SPINNER,
  DECODING,
  FETCHPRIORITY,
  LOADING
} from './settings.js'
import {htmlImgProps} from './types.js'
 
const AtomImage = forwardRef(
  (
    {
      as: As = 'div',
      alt,
      bgStyles,
      decoding = DECODING.AUTO,
      errorIcon,
      errorText,
      fetchpriority = FETCHPRIORITY.AUTO,
      loading = LOADING.EAGER,
      onError = () => {},
      onLoad = () => {},
      placeholder,
      skeleton,
      sources = [],
      spinner,
      className,
      ...imgProps
    },
    forwardedRef
  ) => {
    const imageRef = useRef()
    const [isLoading, setIsLoading] = useState(true)
    const [error, setError] = useState(false)
    const {src} = imgProps
 
    useEffect(() => {
      setIsLoading(true)
      setError(false)
    }, [src, setIsLoading, setError])
 
    const handleLoad = useCallback(() => {
      const loadCompleted = imageRef?.current?.complete
      if (loadCompleted === true) {
        setIsLoading(!loadCompleted)
        onLoad && onLoad()
      }
    }, [onLoad, setIsLoading])
 
    useEffect(() => {
      handleLoad()
    }, [handleLoad, imageRef])
 
    const handleError = () => {
      setIsLoading(false)
      setError(true)
      onError && onError()
    }
 
    const figureStyles = {
      backgroundImage: `url(${placeholder || skeleton})`
    }
 
    return (
      <PolymorphicElement
        as={As}
        className={cx(
          BASE_CLASS,
          {
            'is-error': error,
            'is-loading': isLoading,
            'is-loaded': !isLoading
          },
          className
        )}
        ref={forwardedRef}
      >
        <figure
          className={cx(BASE_CLASS_FIGURE, placeholder && CLASS_PLACEHOLDER, skeleton && CLASS_SKELETON)}
          style={!error && (placeholder || skeleton) ? figureStyles : {}}
        >
          <picture>
            {sources.map((source, idx) => (
              <source key={idx} {...source} />
            ))}
            <img
              alt={alt}
              className={CLASS_IMAGE}
              decoding={decoding}
              fetchpriority={fetchpriority}
              loading={loading}
              onError={handleError}
              onLoad={handleLoad}
              ref={imageRef}
              data-element="image"
              {...imgProps}
            />
          </picture>
        </figure>
        {!error && isLoading && spinner && <Injector classNames={CLASS_SPINNER}>{spinner}</Injector>}
        {error && <ErrorImage className={CLASS_ERROR} icon={errorIcon} text={errorText} />}
      </PolymorphicElement>
    )
  }
)
 
AtomImage.displayName = 'AtomImage'
AtomImage.propTypes = {
  /** Image url or base64 */
  src: PropTypes.string.isRequired,
 
  /** Description of the image */
  alt: PropTypes.string.isRequired,
 
  /**
   * Provides an image decoding hint to the browser
   * https://developer.mozilla.org/en-US/docs/Web/HTML/Element/img#attr-decoding
   */
  decoding: PropTypes.oneOf(Object.values(DECODING)),
 
  /**
   * Provides a hint of the relative priority to use when fetching the image
   * https://developer.mozilla.org/en-US/docs/Web/HTML/Element/img#attr-fetchpriority
   */
  fetchpriority: PropTypes.oneOf(Object.values(FETCHPRIORITY)),
 
  /**
   * Indicates how the browser should load the image
   * https://developer.mozilla.org/en-US/docs/Web/HTML/Element/img#attr-loading
   */
  loading: PropTypes.oneOf(Object.values(LOADING)),
 
  /** Image displayed (blurred) while the final image is being loaded */
  placeholder: PropTypes.string,
 
  /** Image (wireframe, skeleton) displayed (not blurred) while the final image is being loaded */
  skeleton: PropTypes.string,
 
  /** Spinner (component) displayed while the final image is being loaded */
  spinner: PropTypes.node,
 
  /** Icon (component) to be displayed in an Error Box when the image cannot be loaded */
  errorIcon: PropTypes.oneOfType([PropTypes.element, PropTypes.func]),
 
  /** Text to be displayed in an Error Box when the image cannot be loaded */
  errorText: PropTypes.string,
 
  /** Function to be called when the image cannot be loaded  */
  onError: PropTypes.func,
 
  /** Function to be called when the image completed its loading  */
  onLoad: PropTypes.func,
 
  /**
   * Source tags inside picture element,
   * array of props defined in https://developer.mozilla.org/en-US/docs/Web/HTML/Element/source expected
   */
  sources: PropTypes.arrayOf(
    PropTypes.shape({
      srcSet: PropTypes.string,
      media: PropTypes.string
    })
  ),
 
  /** <img> props */
  ...htmlImgProps
}
 
export default AtomImage
 
export {DECODING, FETCHPRIORITY, LOADING}