UIPackage React Native
Search
Menu

Media Download Library

A native offline library with caller-owned download progress, retry, cancel, playback, and removal.

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 media-download-library

Source files

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

components/blocks/media-download-library/MediaDownloadLibrary.tsx
import { Children, Fragment, isValidElement, type ReactNode } from 'react'
import { View, type ViewProps } from 'react-native'
import { CircleAlert, CircleCheck, Clock, Download } from 'lucide-react-native'
import { Button } from '@/components/ui/button'
import { Icon } from '@/components/ui/icon'
import { List, ListItem, ListItemContent, ListItemDescription, ListItemTitle } from '@/components/ui/list'
import { Progress } from '@/components/ui/progress'
import { Text } from '@/components/ui/text'
import { cn } from '@/lib/utils'

export interface MediaDownloadLibraryProps extends ViewProps {
  className?: string
  /** A bounded set of on-device rows. This inline block does not virtualize its content. */
  children?: ReactNode
  /** Caller-composed queued, active, and failed transfers. */
  transfers?: ReactNode
  actions?: ReactNode
  transfersLabel?: string
  downloadedLabel?: string
  emptyMessage?: string
}

function hasRows(children: ReactNode): boolean {
  return Children.toArray(children).some((child) =>
    isValidElement<{ children?: ReactNode }>(child) && child.type === Fragment ? hasRows(child.props.children) : true,
  )
}

export function MediaDownloadLibrary({
  children,
  transfers,
  actions,
  transfersLabel = 'Transfers',
  downloadedLabel = 'On this device',
  emptyMessage = 'No downloads yet.',
  className,
  ...props
}: MediaDownloadLibraryProps) {
  return (
    <View {...props} className={cn('gap-[20px]', className)}>
      {hasRows(transfers) ? (
        <View className="gap-[8px]">
          <Text className="font-semibold">{transfersLabel}</Text>
          <List className="gap-[4px]">{transfers}</List>
        </View>
      ) : null}
      <View className="gap-[8px]">
        <Text className="font-semibold">{downloadedLabel}</Text>
        {hasRows(children) ? (
          <List className="gap-[4px]">{children}</List>
        ) : (
          <Text variant="muted">{emptyMessage}</Text>
        )}
        {actions}
      </View>
    </View>
  )
}

export type MediaDownloadState =
  | { kind: 'queued' }
  | { kind: 'downloading'; progress?: number }
  | { kind: 'failed'; reason?: string }
  | { kind: 'downloaded'; size?: string }

const statusIcons = { queued: Clock, downloading: Download, failed: CircleAlert, downloaded: CircleCheck }
const percentFormat = new Intl.NumberFormat(undefined, { style: 'percent', maximumFractionDigits: 0 })

const defaultLabels = {
  queued: 'Waiting to download',
  downloading: 'Downloading',
  failed: 'Download failed',
  downloaded: 'Available offline',
  cancel: 'Cancel download',
  retry: 'Retry download',
  play: 'Play',
  remove: 'Remove download',
  downloadingProgress: (progress: number) => `Downloading · ${percentFormat.format(progress)}`,
  actionForItem: (action: string, title: string) => `${action}, ${title}`,
}

export interface MediaDownloadItemProps extends ViewProps {
  className?: string
  title: string
  detail?: string
  /** Download progress is a fraction from 0 to 1. Omit it for an indeterminate transfer. */
  state: MediaDownloadState
  onCancel?: () => void
  onRetry?: () => void
  onOpen?: () => void
  /** The consumer owns confirmation or undo and removal of the underlying file. */
  onRemove?: () => void
  labels?: Partial<typeof defaultLabels>
}

export function MediaDownloadItem({
  title,
  detail,
  state,
  onCancel,
  onRetry,
  onOpen,
  onRemove,
  labels,
  className,
  ...props
}: MediaDownloadItemProps) {
  const copy = { ...defaultLabels, ...labels }
  const icon = statusIcons[state.kind]
  const progress =
    state.kind === 'downloading' && state.progress !== undefined && Number.isFinite(state.progress)
      ? Math.max(0, Math.min(1, state.progress))
      : undefined
  const canCancel = onCancel && (state.kind === 'queued' || state.kind === 'downloading')
  const canRetry = onRetry && state.kind === 'failed'
  const canOpen = onOpen && state.kind === 'downloaded'
  const canRemove = onRemove && state.kind === 'downloaded'

  return (
    <View {...props} className={cn('px-[4px] pb-[4px]', className)}>
      <ListItem className="items-start px-[12px]">
        <View className="size-[40px] items-center justify-center rounded-md bg-muted">
          <Icon
            icon={icon}
            size={19}
            className={state.kind === 'failed' ? 'text-destructive' : 'text-muted-foreground'}
          />
        </View>
        <ListItemContent>
          <ListItemTitle>{title}</ListItemTitle>
          {detail ? <ListItemDescription>{detail}</ListItemDescription> : null}
          <Text
            size="sm"
            variant="muted"
            className={state.kind === 'failed' ? 'text-destructive' : undefined}
            style={{ fontVariant: ['tabular-nums'] }}
          >
            {progress === undefined ? copy[state.kind] : copy.downloadingProgress(progress)}
          </Text>
          {state.kind === 'downloaded' && state.size ? <ListItemDescription>{state.size}</ListItemDescription> : null}
          {state.kind === 'failed' && state.reason ? <ListItemDescription>{state.reason}</ListItemDescription> : null}
          {state.kind === 'downloading' ? (
            <Progress
              accessibilityLabel={copy.actionForItem(copy.downloading, title)}
              accessibilityState={{ busy: true }}
              value={progress === undefined ? undefined : Math.round(progress * 100)}
              className="mt-[4px]"
            />
          ) : null}
        </ListItemContent>
      </ListItem>
      {canCancel || canRetry || canOpen || canRemove ? (
        <View className="flex-row flex-wrap items-center gap-[4px] px-[12px]">
          {canCancel ? (
            <Button
              size="sm"
              variant="ghost"
              accessibilityLabel={copy.actionForItem(copy.cancel, title)}
              onPress={onCancel}
            >
              {copy.cancel}
            </Button>
          ) : null}
          {canRetry ? (
            <Button
              size="sm"
              variant="outline"
              accessibilityLabel={copy.actionForItem(copy.retry, title)}
              onPress={onRetry}
            >
              {copy.retry}
            </Button>
          ) : null}
          {canOpen ? (
            <Button
              size="sm"
              variant="outline"
              accessibilityLabel={copy.actionForItem(copy.play, title)}
              onPress={onOpen}
            >
              {copy.play}
            </Button>
          ) : null}
          {canRemove ? (
            <Button
              size="sm"
              variant="ghost"
              accessibilityLabel={copy.actionForItem(copy.remove, title)}
              onPress={onRemove}
            >
              {copy.remove}
            </Button>
          ) : null}
        </View>
      ) : null}
    </View>
  )
}
components/blocks/media-download-library/index.ts
export {
  MediaDownloadItem,
  MediaDownloadLibrary,
  type MediaDownloadItemProps,
  type MediaDownloadLibraryProps,
  type MediaDownloadState,
} from './MediaDownloadLibrary'

Dependencies

Registry items

npm packages

  • lucide-react-native
Browse media and playback