UIPackage React Native
Search

Image

Image loading, error fallback and retry with source-safe request state.

Install

First install? Set up the registry in your app.

npx --yes --package=https://native.uipkge.dev/cli/uipkge-native-0.1.1.tgz uipkge-native add image

Source files

Expand a file to read the source the installer copies into your app.

components/ui/image/Image.tsx
import * as React from 'react'
import {
  Image as NativeImage,
  Pressable,
  StyleSheet,
  View,
  type ImageProps as NativeImageProps,
  type ImageURISource,
  type ViewProps,
} from 'react-native'
import { cssInterop } from 'react-native-css-interop'
import { Button, type ButtonProps } from '@/components/ui/button'
import { Spinner } from '@/components/ui/spinner'
import { Text } from '@/components/ui/text'
import { renderTextChildren } from '@/lib/label-children'
import { cn } from '@/lib/utils'

type Status = 'loading' | 'loaded' | 'error'
interface ImageState {
  source: NativeImageProps['source'] | undefined
  hasSource: boolean
  status: Status
  attempt: number
  current: (attempt: number) => boolean
  settle: (attempt: number, status: 'loaded' | 'error') => boolean
  retry: () => void
}
const Context = React.createContext<ImageState | null>(null)
function useImage() {
  const value = React.useContext(Context)
  if (!value) throw new Error('Image parts must be inside Image')
  return value
}
function hasImageSource(source: NativeImageProps['source'] | undefined): boolean {
  if (typeof source === 'number') return Number.isFinite(source) && source > 0
  return !!source && 'uri' in source && !!source.uri?.trim()
}
function ImageStateProvider({ source, children }: { source?: NativeImageProps['source']; children: React.ReactNode }) {
  const hasSource = hasImageSource(source)
  const [status, setStatus] = React.useState<Status>(hasSource ? 'loading' : 'error')
  const [attempt, setAttempt] = React.useState(0)
  const active = React.useRef(true)
  const generation = React.useRef(0)
  const phase = React.useRef(status)
  React.useLayoutEffect(() => {
    active.current = true
    return () => {
      active.current = false
    }
  }, [])
  return (
    <Context.Provider
      value={{
        source,
        hasSource,
        status,
        attempt,
        current: (request) => active.current && generation.current === request,
        settle: (request, next) => {
          if (!active.current || generation.current !== request || phase.current !== 'loading') return false
          phase.current = next
          setStatus(next)
          return true
        },
        retry: () => {
          if (!hasSource || phase.current === 'loading') return
          generation.current += 1
          phase.current = 'loading'
          setAttempt(generation.current)
          setStatus('loading')
        },
      }}
    >
      {children}
    </Context.Provider>
  )
}

/** Responsive variants belong in the caller so each request has a distinct source identity. */
export type ImageSourceValue = number | ImageURISource
export interface ImageProps extends ViewProps {
  source?: ImageSourceValue
  className?: string
}
export const Image = React.forwardRef<React.ComponentRef<typeof View>, ImageProps>(
  ({ source, className, style, children, ...props }, ref) => {
    const identity = JSON.stringify(source) ?? 'missing'
    return (
      <View
        {...props}
        ref={ref}
        className={cn('relative w-full overflow-hidden rounded-lg bg-muted', className)}
        style={[{ aspectRatio: 16 / 9 }, style]}
      >
        <ImageStateProvider key={identity} source={source}>
          {children ?? (
            <>
              <ImageSource accessibilityLabel={props.accessibilityLabel} />
              <ImageLoading />
              <ImageFallback />
            </>
          )}
        </ImageStateProvider>
      </View>
    )
  },
)
Image.displayName = 'Image'

export type ImageSourceProps = Omit<NativeImageProps, 'source' | 'src' | 'srcSet'> & { className?: string }
export const ImageSource = React.forwardRef<React.ComponentRef<typeof NativeImage>, ImageSourceProps>(
  ({ className, style, resizeMode = 'cover', onLoad, onError, onLoadStart, onLoadEnd, ...props }, ref) => {
    const image = useImage()
    const { src: _src, srcSet: _srcSet, ...nativeProps } = props as NativeImageProps
    if (!image.hasSource || image.status === 'error') return null
    const request = image.attempt
    return (
      <NativeImage
        {...nativeProps}
        key={request}
        ref={ref}
        source={image.source}
        accessible={
          nativeProps.accessible ?? (nativeProps.accessibilityLabel || nativeProps['aria-label'] ? true : undefined)
        }
        resizeMode={resizeMode}
        // Bundled assets have intrinsic dimensions. The preview's bounds must win by default.
        className={className}
        style={[StyleSheet.absoluteFill, { width: '100%', height: '100%' }, style]}
        onLoadStart={() => {
          if (image.current(request)) onLoadStart?.()
        }}
        onLoad={(event) => {
          if (image.settle(request, 'loaded')) onLoad?.(event)
        }}
        onError={(event) => {
          if (image.settle(request, 'error')) onError?.(event)
        }}
        onLoadEnd={() => {
          if (image.current(request)) onLoadEnd?.()
        }}
      />
    )
  },
)
ImageSource.displayName = 'ImageSource'
cssInterop(ImageSource, { className: 'style' })

export const ImageFallback = React.forwardRef<React.ComponentRef<typeof View>, ViewProps & { className?: string }>(
  ({ children = <Text variant="muted">Image unavailable.</Text>, className, ...props }, ref) => {
    const image = useImage()
    if (image.status !== 'error') return null
    return (
      <View
        {...props}
        ref={ref}
        className={cn('absolute inset-0 items-center justify-center gap-[12px] bg-muted p-[16px]', className)}
      >
        {renderTextChildren(children)}
      </View>
    )
  },
)
ImageFallback.displayName = 'ImageFallback'
export const ImageLoading = React.forwardRef<React.ComponentRef<typeof View>, ViewProps & { className?: string }>(
  ({ children = <Spinner />, className, ...props }, ref) => {
    const image = useImage()
    if (image.status !== 'loading') return null
    return (
      <View
        pointerEvents="none"
        {...props}
        ref={ref}
        className={cn('absolute inset-0 items-center justify-center bg-muted', className)}
      >
        {renderTextChildren(children)}
      </View>
    )
  },
)
ImageLoading.displayName = 'ImageLoading'
export const ImageRetry = React.forwardRef<React.ComponentRef<typeof Pressable>, ButtonProps>(
  ({ children = 'Retry image', disabled, onPress, ...props }, ref) => {
    const image = useImage()
    const isDisabled = !!disabled || !image.hasSource || image.status === 'loading'
    return (
      <Button
        variant="outline"
        {...props}
        ref={ref}
        disabled={isDisabled}
        onPress={(event) => {
          if (isDisabled) return
          onPress?.(event)
          if (!event.isDefaultPrevented()) image.retry()
        }}
      >
        {children}
      </Button>
    )
  },
)
ImageRetry.displayName = 'ImageRetry'
components/ui/image/index.ts
export * from './Image'

Dependencies

Registry items

npm packages

  • react-native-css-interop
Browse more components