UIPackage React Native
Search

Shared Expense

Equal expense splitting with selectable participants and exact rounding in minor currency units.

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 shared-expense

Source files

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

components/blocks/shared-expense/SharedExpense.tsx
import { useWindowDimensions, View, type ViewProps } from 'react-native'
import { Check } from 'lucide-react-native'
import { Button } from '@/components/ui/button'
import { Icon } from '@/components/ui/icon'
import { List, ListItem, ListItemContent, ListItemTitle, ListSeparator } from '@/components/ui/list'
import { Text } from '@/components/ui/text'
import { cn } from '@/lib/utils'

const defaultLabels = {
  total: 'Total to split',
  participants: 'Who is sharing?',
  empty: 'No participants are available for this expense.',
  select: 'Select someone to split this expense.',
  staleSelection: 'Some selected people are unavailable. Review the list before continuing.',
  invalidTotal: 'Enter a valid expense total to continue.',
  review: 'Review split',
}

export interface SharedExpenseParticipant {
  id: string
  name: string
}

export interface SharedExpenseShare {
  id: string
  amountMinor: number
}

export interface SharedExpenseProps extends Omit<ViewProps, 'children'> {
  className?: string
  title: string
  /** Nonnegative, safe integer in the currency's smallest unit. */
  amountMinor: number | null
  /** Unique stable IDs and order. Any rounding remainder goes to the first selected rows in this order. */
  participants: readonly SharedExpenseParticipant[]
  selectedIds: readonly string[]
  onSelectionChange: (ids: string[]) => void
  onReview: (shares: SharedExpenseShare[]) => void
  formatMinor: (amountMinor: number) => string
  labels?: Partial<typeof defaultLabels>
}

export function SharedExpense({
  className,
  title,
  amountMinor,
  participants,
  selectedIds,
  onSelectionChange,
  onReview,
  formatMinor,
  labels,
  ...props
}: SharedExpenseProps) {
  const copy = { ...defaultLabels, ...labels }
  const { fontScale } = useWindowDimensions()
  const stacked = fontScale >= 1.35
  const selected = new Set(selectedIds)
  const included = participants.filter(({ id }) => selected.has(id))
  const validTotal = amountMinor !== null && Number.isSafeInteger(amountMinor) && amountMinor >= 0
  const staleSelection = included.length !== selected.size
  const shares = new Map<string, number>()

  if (validTotal && included.length && !staleSelection) {
    const remainder = amountMinor % included.length
    const share = (amountMinor - remainder) / included.length
    included.forEach(({ id }, index) => shares.set(id, share + Number(index < remainder)))
  }
  const message = !validTotal
    ? copy.invalidTotal
    : !participants.length
      ? copy.empty
      : staleSelection
        ? copy.staleSelection
        : copy.select

  function toggle(id: string) {
    // A deliberate change reconciles selections from a previous participant list.
    const next = new Set(included.map((participant) => participant.id))
    if (!next.delete(id)) next.add(id)
    onSelectionChange(
      participants.filter((participant) => next.has(participant.id)).map((participant) => participant.id),
    )
  }

  return (
    <View {...props} className={cn('gap-4', className)}>
      <View className="gap-1 border-b border-border pb-4">
        <Text size="lg" accessibilityRole="header" className="font-semibold">
          {title}
        </Text>
        <Text size="sm" variant="muted">
          {copy.total}
        </Text>
        {validTotal ? (
          <Text size="title" style={{ fontVariant: ['tabular-nums'] }}>
            {formatMinor(amountMinor)}
          </Text>
        ) : null}
      </View>
      <Text accessibilityRole="header" className="font-semibold">
        {copy.participants}
      </Text>
      {participants.length ? (
        <List>
          {participants.map(({ id, name }, index) => {
            const share = shares.get(id)
            const formatted = share === undefined ? undefined : formatMinor(share)
            const shareText = formatted ? <Text style={{ fontVariant: ['tabular-nums'] }}>{formatted}</Text> : null
            const checked = selected.has(id)

            return (
              <View key={id}>
                {index ? <ListSeparator /> : null}
                <ListItem
                  accessibilityRole="checkbox"
                  accessibilityLabel={formatted ? `${name}, ${formatted}` : name}
                  accessibilityState={{ checked }}
                  onPress={() => toggle(id)}
                  className="px-3"
                >
                  <View
                    aria-hidden
                    className={cn(
                      'size-6 shrink-0 items-center justify-center rounded border border-muted-foreground',
                      checked && 'border-primary bg-primary',
                    )}
                  >
                    {checked ? <Icon icon={Check} size={16} className="text-primary-foreground" /> : null}
                  </View>
                  <ListItemContent>
                    <ListItemTitle>{name}</ListItemTitle>
                    {stacked ? shareText : null}
                  </ListItemContent>
                  {stacked ? null : shareText}
                </ListItem>
              </View>
            )
          })}
        </List>
      ) : null}
      {!shares.size ? (
        <Text size="sm" variant="muted">
          {message}
        </Text>
      ) : null}
      <Button
        disabled={!shares.size}
        accessibilityLabel={copy.review}
        onPress={() => {
          if (shares.size) onReview(Array.from(shares, ([id, amountMinor]) => ({ id, amountMinor })))
        }}
      >
        {copy.review}
      </Button>
    </View>
  )
}
components/blocks/shared-expense/index.ts
export { SharedExpense } from './SharedExpense'
export type { SharedExpenseParticipant, SharedExpenseProps, SharedExpenseShare } from './SharedExpense'

Dependencies

Registry items

npm packages

  • lucide-react-native
Browse finance