UIPackage React Native
Search
Menu

Media Chapter List

A native chapter list with playback position, exact seek requests, and accessible current-chapter 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 media-chapter-list

Source files

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

components/blocks/media-chapter-list/MediaChapterList.tsx
import * as React from 'react'
import { FlatList, View, useWindowDimensions, type ViewProps } from 'react-native'
import { ListItem, ListItemContent, ListItemDescription, ListItemTitle, ListSeparator } from '@/components/ui/list'
import { Text } from '@/components/ui/text'
import { cn } from '@/lib/utils'

export interface MediaChapter {
  id: string
  title: string
  startSeconds: number
  detail?: string
}

const defaultLabels = {
  title: 'Chapters',
  empty: 'No chapters available.',
  current: 'Current chapter',
  duration: (value: string) => `Duration, ${value}`,
  startsAt: (value: string) => `Starts at ${value}`,
}

export interface MediaChapterListProps extends Omit<ViewProps, 'children'> {
  className?: string
  /** Media duration. Every valid chapter begins before this timestamp. */
  duration: number
  /** The caller's current playback position in seconds. */
  position?: number
  /** A controlled current chapter, overriding position when supplied. Null means none. */
  currentId?: string | null
  /** IDs and start times must be distinct. Invalid entries are omitted. */
  chapters?: readonly MediaChapter[]
  onSeek?: (id: string, startSeconds: number) => void
  disabled?: boolean
  header?: React.ReactNode
  labels?: Partial<typeof defaultLabels>
  formatTime?: (seconds: number) => string
  formatAccessibleTime?: (seconds: number) => string
}

function hoursMinutesSeconds(seconds: number) {
  const whole = Math.floor(seconds)
  return [Math.floor(whole / 3600), Math.floor(whole / 60) % 60, whole % 60]
}

function clock(seconds: number) {
  const [hour, minute, second] = hoursMinutesSeconds(seconds)
  const rest = String(second).padStart(2, '0')
  return hour ? `${hour}:${String(minute).padStart(2, '0')}:${rest}` : `${minute}:${rest}`
}

function speak(seconds: number) {
  const [hour, minute, second] = hoursMinutesSeconds(seconds)
  const parts = [
    hour ? `${hour} ${hour === 1 ? 'hour' : 'hours'}` : '',
    minute ? `${minute} ${minute === 1 ? 'minute' : 'minutes'}` : '',
    second ? `${second} ${second === 1 ? 'second' : 'seconds'}` : '',
  ]
  return parts.filter(Boolean).join(', ') || '0 seconds'
}

function validChapters(chapters: readonly MediaChapter[], duration: number) {
  const ids = new Set<string>()
  const starts = new Set<number>()
  const ordered = chapters
    .filter(
      (chapter) =>
        chapter.id.trim() && chapter.title.trim() && chapter.startSeconds >= 0 && chapter.startSeconds < duration,
    )
    .sort((left, right) => left.startSeconds - right.startSeconds)
  return ordered.filter((chapter) => {
    if (ids.has(chapter.id) || starts.has(chapter.startSeconds)) return false
    ids.add(chapter.id)
    starts.add(chapter.startSeconds)
    return true
  })
}

export function MediaChapterList({
  className,
  duration,
  position,
  currentId,
  chapters = [],
  onSeek,
  disabled = false,
  header,
  labels,
  formatTime = clock,
  formatAccessibleTime = speak,
  ...props
}: MediaChapterListProps) {
  const copy = { ...defaultLabels, ...labels }
  const safeDuration = Number.isFinite(duration) && duration > 0 && duration <= Number.MAX_SAFE_INTEGER ? duration : 0
  const ordered = React.useMemo(() => validChapters(chapters, safeDuration), [chapters, safeDuration])
  const { width, fontScale } = useWindowDimensions()
  const stack = width < 360 || fontScale >= 1.4
  let selected = currentId
  if (currentId === undefined && position !== undefined && Number.isFinite(position) && position >= 0) {
    for (const chapter of ordered) {
      if (chapter.startSeconds > position) break
      selected = chapter.id
    }
  }

  return (
    <View {...props} className={cn('min-h-0 flex-1', className)}>
      <FlatList
        data={ordered}
        keyExtractor={(chapter) => chapter.id}
        ItemSeparatorComponent={ListSeparator}
        contentContainerStyle={{ paddingBottom: 16 }}
        ListHeaderComponent={
          <View className="gap-3 pb-3">
            {header}
            <View className="flex-row flex-wrap items-baseline justify-between gap-2">
              <Text size="xl" accessibilityRole="header">
                {copy.title}
              </Text>
              {safeDuration ? (
                <Text
                  size="sm"
                  variant="muted"
                  accessibilityLabel={copy.duration(formatAccessibleTime(safeDuration))}
                  style={{ fontVariant: ['tabular-nums'] }}
                >
                  {formatTime(safeDuration)}
                </Text>
              ) : null}
            </View>
          </View>
        }
        ListEmptyComponent={<Text className="rounded-xl border border-border px-4 py-6 text-center">{copy.empty}</Text>}
        renderItem={({ item }) => {
          const current = item.id === selected
          return (
            <ListItem
              accessible
              accessibilityLabel={[
                item.title,
                copy.startsAt(formatAccessibleTime(item.startSeconds)),
                item.detail,
                current && !onSeek ? copy.current : undefined,
              ]
                .filter(Boolean)
                .join(', ')}
              accessibilityState={{ selected: current && !!onSeek }}
              disabled={disabled && !!onSeek}
              onPress={
                onSeek
                  ? () => {
                      if (!disabled) onSeek(item.id, item.startSeconds)
                    }
                  : undefined
              }
              className={cn(current && 'rounded-lg bg-muted', stack && 'flex-col items-start')}
            >
              <ListItemContent>
                <ListItemTitle className={current ? 'font-semibold' : undefined}>{item.title}</ListItemTitle>
                {item.detail ? <ListItemDescription>{item.detail}</ListItemDescription> : null}
                {current ? (
                  <Text size="sm" className="font-medium">
                    {copy.current}
                  </Text>
                ) : null}
              </ListItemContent>
              <Text size="sm" variant="muted" style={{ fontVariant: ['tabular-nums'] }}>
                {formatTime(item.startSeconds)}
              </Text>
            </ListItem>
          )
        }}
      />
    </View>
  )
}
components/blocks/media-chapter-list/index.ts
export { MediaChapterList, type MediaChapter, type MediaChapterListProps } from './MediaChapterList'

Dependencies

Registry items

Browse media and playback