UIPackage React Native
Search
Menu

Subscription Overview

A native list of current and expired subscriptions with a next-charge preview, localized prices, and renewal and access dates.

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 subscription-overview

Source files

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

components/blocks/subscription-overview/SubscriptionOverview.tsx
import * as React from 'react'
import { FlatList, View, type ViewProps } from 'react-native'
import { Badge } from '@/components/ui/badge'
import { ListItem, ListItemContent, ListItemDescription, ListItemTitle, ListSeparator } from '@/components/ui/list'
import { SegmentedControl, SegmentedControlItem } from '@/components/ui/segmented-control'
import { Text } from '@/components/ui/text'
import { cn } from '@/lib/utils'

type BillingInterval = 'week' | 'month' | 'year'
type SubscriptionStatus = 'active' | 'trial' | 'ending' | 'expired'

export interface SubscriptionOverviewEntry {
  id: string
  name: string
  plan?: string
  /** Non-negative recurring amount in major currency units. */
  amount: number
  currency: string
  interval: BillingInterval
  status: SubscriptionStatus
  /** Renewal, trial end, or access end, depending on status. Unix milliseconds. */
  periodEndsAt?: number
}

const defaultLabels = {
  current: 'Current',
  expired: 'Expired',
  active: 'Active',
  trial: 'Free trial',
  ending: 'Ending',
  nextCharge: 'Next charge',
  emptyCurrent: 'No current subscriptions',
  emptyExpired: 'No expired subscriptions',
  price: (amount: string, interval: BillingInterval) => `${amount} / ${interval}`,
  renewsOn: (date: string) => `Renews ${date}`,
  trialEndsOn: (date: string) => `Trial ends ${date}`,
  endsOn: (date: string) => `Access ends ${date}`,
  expiredOn: (date: string) => `Expired ${date}`,
}

export interface SubscriptionOverviewProps extends ViewProps {
  className?: string
  /** Pass an empty array for an account without subscriptions. */
  entries?: readonly SubscriptionOverviewEntry[]
  locale?: string
  /** Reference timestamp for the next charge. Defaults to the current time at render. */
  now?: number
  labels?: Partial<typeof defaultLabels>
  header?: React.ReactNode
  onEntryPress?: (entry: SubscriptionOverviewEntry) => void
}

function sampleEntries(now: number): SubscriptionOverviewEntry[] {
  const renewal = new Date(now)
  renewal.setDate(renewal.getDate() + 3)
  return [
    {
      id: 'sample-1',
      name: 'Harbor Storage',
      plan: '100 GB',
      amount: 3.99,
      currency: 'USD',
      interval: 'month',
      status: 'active',
      periodEndsAt: renewal.getTime(),
    },
    {
      id: 'sample-2',
      name: 'Field Notes',
      plan: 'Personal',
      amount: 24,
      currency: 'USD',
      interval: 'year',
      status: 'expired',
    },
  ]
}

function periodEnd(entry: SubscriptionOverviewEntry) {
  return entry.periodEndsAt !== undefined && Number.isFinite(new Date(entry.periodEndsAt).getTime())
    ? entry.periodEndsAt
    : undefined
}

function currencyCode(entry: SubscriptionOverviewEntry) {
  const currency = entry.currency.trim().toUpperCase()
  return /^[A-Z]{3}$/.test(currency) ? currency : undefined
}

export function SubscriptionOverview({
  className,
  entries,
  header,
  locale,
  now = Date.now(),
  labels,
  onEntryPress,
  ...props
}: SubscriptionOverviewProps) {
  const copy = { ...defaultLabels, ...labels }
  const [sample] = React.useState(() => sampleEntries(now))
  const [view, setView] = React.useState<'current' | 'expired'>('current')
  const dateFormat = React.useMemo(() => new Intl.DateTimeFormat(locale, { dateStyle: 'medium' }), [locale])
  const eligible = (entries ?? sample)
    .filter((entry) => (entry.status === 'expired') === (view === 'expired'))
    .sort((a, b) =>
      view === 'expired'
        ? (periodEnd(b) ?? -Infinity) - (periodEnd(a) ?? -Infinity)
        : (periodEnd(a) ?? Infinity) - (periodEnd(b) ?? Infinity),
    )
  const upcoming =
    view === 'current'
      ? eligible.find((entry) => {
          const date = periodEnd(entry)
          return (
            (entry.status === 'active' || entry.status === 'trial') &&
            Number.isFinite(entry.amount) &&
            entry.amount > 0 &&
            !!currencyCode(entry) &&
            date !== undefined &&
            date >= now
          )
        })
      : undefined

  function displayPrice(entry: SubscriptionOverviewEntry) {
    const amount = entry.amount
    const currency = currencyCode(entry)
    if (!currency || !Number.isFinite(amount) || amount < 0) return undefined
    return copy.price(new Intl.NumberFormat(locale, { style: 'currency', currency }).format(amount), entry.interval)
  }

  return (
    <View {...props} className={cn('min-h-0 flex-1 bg-background', className)}>
      <FlatList
        data={upcoming ? eligible.filter((entry) => entry.id !== upcoming.id) : eligible}
        keyExtractor={(entry) => entry.id}
        contentContainerStyle={{ paddingBottom: 16 }}
        ListHeaderComponent={
          <View className="gap-4 pb-4">
            {header}
            <SegmentedControl
              value={view}
              onValueChange={(value) => {
                if (value === 'current' || value === 'expired') setView(value)
              }}
            >
              <SegmentedControlItem value="current">{copy.current}</SegmentedControlItem>
              <SegmentedControlItem value="expired">{copy.expired}</SegmentedControlItem>
            </SegmentedControl>
            {upcoming ? (
              <ListItem
                accessible
                accessibilityLabel={[
                  copy.nextCharge,
                  upcoming.name,
                  displayPrice(upcoming),
                  dateFormat.format(periodEnd(upcoming)!),
                  upcoming.status === 'trial' && copy.trial,
                ]
                  .filter(Boolean)
                  .join(', ')}
                onPress={onEntryPress ? () => onEntryPress(upcoming) : undefined}
                className="flex-col items-start gap-1 rounded-2xl border border-border bg-card px-5 py-4"
              >
                <Text size="sm" variant="muted">
                  {copy.nextCharge}
                </Text>
                <Text size="xl" style={{ fontVariant: ['tabular-nums'] }}>
                  {displayPrice(upcoming)}
                </Text>
                <Text>{upcoming.name}</Text>
                <Text size="sm" variant="muted">
                  {upcoming.status === 'trial'
                    ? copy.trialEndsOn(dateFormat.format(periodEnd(upcoming)!))
                    : dateFormat.format(periodEnd(upcoming)!)}
                </Text>
              </ListItem>
            ) : null}
          </View>
        }
        ListEmptyComponent={
          upcoming ? undefined : (
            <View className="items-center rounded-xl border border-border px-4 py-8">
              <Text className="text-center font-medium">
                {view === 'current' ? copy.emptyCurrent : copy.emptyExpired}
              </Text>
            </View>
          )
        }
        ItemSeparatorComponent={ListSeparator}
        renderItem={({ item }) => {
          const timestamp = periodEnd(item)
          const date = timestamp === undefined ? undefined : dateFormat.format(timestamp)
          const describeDate = {
            active: copy.renewsOn,
            trial: copy.trialEndsOn,
            ending: copy.endsOn,
            expired: copy.expiredOn,
          }[item.status]
          const dateDescription = date ? describeDate(date) : undefined
          const price = displayPrice(item)
          return (
            <ListItem
              accessible
              accessibilityLabel={[item.name, item.plan, copy[item.status], price, dateDescription]
                .filter(Boolean)
                .join(', ')}
              onPress={onEntryPress ? () => onEntryPress(item) : undefined}
              className="items-start px-0"
            >
              <ListItemContent className="gap-2">
                <View className="flex-row flex-wrap items-center justify-between gap-x-2 gap-y-1">
                  <ListItemTitle className="min-w-0 shrink">{item.name}</ListItemTitle>
                  <Badge variant={item.status === 'trial' ? 'info' : 'outline'} text={copy[item.status]} />
                </View>
                {item.plan ? <ListItemDescription>{item.plan}</ListItemDescription> : null}
                <View className="flex-row flex-wrap gap-x-3 gap-y-1">
                  {price ? (
                    <Text size="sm" style={{ fontVariant: ['tabular-nums'] }}>
                      {price}
                    </Text>
                  ) : null}
                  {dateDescription ? (
                    <Text size="sm" variant="muted">
                      {dateDescription}
                    </Text>
                  ) : null}
                </View>
              </ListItemContent>
            </ListItem>
          )
        }}
      />
    </View>
  )
}
components/blocks/subscription-overview/index.ts
export {
  SubscriptionOverview,
  type SubscriptionOverviewEntry,
  type SubscriptionOverviewProps,
} from './SubscriptionOverview'

Dependencies

Browse finance