Budget Overview
A native budget summary with category allocations, actual spending, progress, and clear remaining or overspent balances.
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 budget-overviewSource files
Expand a file to read the source the installer copies into your app.
components/blocks/budget-overview/BudgetOverview.tsx
import * as React from 'react'
import { FlatList, I18nManager, View, type ViewProps } from 'react-native'
import { ChevronLeft, ChevronRight } from 'lucide-react-native'
import { Icon } from '@/components/ui/icon'
import { ListItem, ListItemContent, ListItemDescription, ListItemTitle, ListSeparator } from '@/components/ui/list'
import { Progress } from '@/components/ui/progress'
import { Text } from '@/components/ui/text'
import { cn } from '@/lib/utils'
export interface BudgetOverviewCategory {
id: string
name: string
/** Non-negative safe integer in minor currency units (such as cents). */
allocated: number
/** Non-negative safe integer in the same units as allocated. */
spent: number
}
const defaultLabels = {
categories: 'Categories',
noCategories: 'No budget categories yet',
noAllocation: 'No allocation',
fullySpent: 'Fully spent',
unavailable: 'Budget summary unavailable',
spentOf: (spent: string, allocated: string) => `${spent} of ${allocated} spent`,
remaining: (amount: string) => `${amount} remaining`,
exceeded: (amount: string) => `${amount} over budget`,
}
export interface BudgetOverviewProps extends ViewProps {
className?: string
/** Omit to show the sample. An empty array renders the empty state. */
categories?: readonly BudgetOverviewCategory[]
/** ISO 4217 code shared by every category in this period. */
currency?: string
locale?: string
header?: React.ReactNode
labels?: Partial<typeof defaultLabels>
onCategoryPress?: (category: BudgetOverviewCategory) => void
}
const sample: readonly BudgetOverviewCategory[] = [
{ id: 'workspace', name: 'Studio supplies', allocated: 15_000, spent: 10_234 },
{ id: 'transport', name: 'Transport', allocated: 8_000, spent: 9_200 },
]
function validAmount(value: number) {
return Number.isSafeInteger(value) && value >= 0
}
function amountFormatter(locale: string | undefined, currency: string) {
const code = currency.trim().toUpperCase()
if (!/^[A-Z]{3}$/.test(code)) return undefined
const format = new Intl.NumberFormat(locale, { style: 'currency', currency: code })
const { maximumFractionDigits: precision = 2, numberingSystem } = format.resolvedOptions()
if (precision === 0) return (minor: number) => format.format(minor)
const divisor = 10 ** precision
const digits = new Intl.NumberFormat(locale, {
minimumIntegerDigits: precision,
maximumFractionDigits: 0,
numberingSystem,
useGrouping: false,
})
const zeroFraction = digits.format(0)
const halfFraction = digits.format(divisor / 2)
const sample = format.format(0.5)
const sampleStart = sample.lastIndexOf(halfFraction)
if (sampleStart < 0) return undefined
const suffixLength = sample.length - sampleStart - halfFraction.length
return (minor: number) => {
const remainder = minor % divisor
const whole = format.format((minor - remainder) / divisor)
if (!remainder) return whole
// Replace only the fractional digits to preserve the locale's monetary
// separators and affixes without relying on Hermes formatToParts.
const fractionEnd = whole.length - suffixLength
return whole.slice(0, fractionEnd - zeroFraction.length) + digits.format(remainder) + whole.slice(fractionEnd)
}
}
export function BudgetOverview({
className,
categories = sample,
currency = 'USD',
locale,
header,
labels,
onCategoryPress,
...props
}: BudgetOverviewProps) {
const copy = { ...defaultLabels, ...labels }
const formatter = React.useMemo(() => amountFormatter(locale, currency), [locale, currency])
const validCategories = React.useMemo(
() => categories.filter((category) => validAmount(category.allocated) && validAmount(category.spent)),
[categories],
)
const totals = React.useMemo(
() =>
validCategories.reduce(
(sum, category) => ({
allocated: sum.allocated + category.allocated,
spent: sum.spent + category.spent,
}),
{ allocated: 0, spent: 0 },
),
[validCategories],
)
const showTotal =
!!formatter &&
validCategories.length > 0 &&
validCategories.length === categories.length &&
validAmount(totals.allocated) &&
validAmount(totals.spent)
const Chevron = I18nManager.isRTL ? ChevronLeft : ChevronRight
function amount(minor: number) {
return formatter?.(minor) ?? ''
}
function balance(allocated: number, spent: number) {
if (!allocated && !spent) return copy.noAllocation
if (spent > allocated) return copy.exceeded(amount(spent - allocated))
if (spent === allocated) return copy.fullySpent
return copy.remaining(amount(allocated - spent))
}
return (
<View {...props} className={cn('min-h-0 flex-1 bg-background', className)}>
<FlatList
data={formatter ? validCategories : []}
keyExtractor={(category) => category.id}
contentContainerStyle={{ paddingBottom: 16 }}
ListHeaderComponent={
<View className="gap-4 pb-3">
{header}
{showTotal ? (
<View className="gap-3 rounded-2xl border border-border bg-card p-5">
<View className="gap-1">
<Text
size="title"
className={totals.spent > totals.allocated ? 'text-destructive' : undefined}
style={{ fontVariant: ['tabular-nums'] }}
>
{balance(totals.allocated, totals.spent)}
</Text>
<Text size="sm" variant="muted" style={{ fontVariant: ['tabular-nums'] }}>
{copy.spentOf(amount(totals.spent), amount(totals.allocated))}
</Text>
</View>
{totals.allocated > 0 ? (
<Progress
aria-hidden
value={totals.spent}
max={totals.allocated}
indicatorClassName={totals.spent > totals.allocated ? 'bg-destructive' : undefined}
/>
) : null}
</View>
) : formatter && validCategories.length > 0 ? (
<Text size="sm" variant="muted">
{copy.unavailable}
</Text>
) : null}
{validCategories.length > 0 && formatter ? (
<Text accessibilityRole="header" className="font-semibold">
{copy.categories}
</Text>
) : null}
</View>
}
ListEmptyComponent={
<View className="items-center rounded-xl border border-border px-4 py-8">
<Text className="text-center font-medium">
{categories.length > 0 ? copy.unavailable : copy.noCategories}
</Text>
</View>
}
ItemSeparatorComponent={ListSeparator}
renderItem={({ item }) => {
const over = item.spent > item.allocated
const categoryBalance = balance(item.allocated, item.spent)
const categorySpending = copy.spentOf(amount(item.spent), amount(item.allocated))
return (
<ListItem
accessible
accessibilityLabel={[item.name, categorySpending, categoryBalance].join(', ')}
onPress={onCategoryPress ? () => onCategoryPress(item) : undefined}
className="px-0"
>
<ListItemContent className="gap-2">
<View className="flex-row flex-wrap items-baseline justify-between gap-x-3 gap-y-1">
<ListItemTitle className="min-w-0 shrink">{item.name}</ListItemTitle>
<Text
size="sm"
className={cn('font-medium', over && 'text-destructive')}
style={{ fontVariant: ['tabular-nums'] }}
>
{categoryBalance}
</Text>
</View>
<ListItemDescription style={{ fontVariant: ['tabular-nums'] }}>{categorySpending}</ListItemDescription>
{item.allocated > 0 ? (
<Progress
aria-hidden
value={item.spent}
max={item.allocated}
indicatorClassName={over ? 'bg-destructive' : undefined}
/>
) : null}
</ListItemContent>
{onCategoryPress ? <Icon icon={Chevron} size={18} className="text-muted-foreground" /> : null}
</ListItem>
)
}}
/>
</View>
)
}
components/blocks/budget-overview/index.ts
export { BudgetOverview, type BudgetOverviewCategory, type BudgetOverviewProps } from './BudgetOverview'