UIPackage React Native
Search
Menu

Notification Inbox

An in-app inbox with all and unread filters, caller-owned read status, and a bulk read action.

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 notification-inbox

Source files

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

components/blocks/notification-inbox/NotificationInbox.tsx
import * as React from 'react'
import { ActivityIndicator, FlatList, View, useWindowDimensions, type ViewProps } from 'react-native'
import { Alert, AlertDescription } from '@/components/ui/alert'
import { Button } from '@/components/ui/button'
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 { useAnnouncement } from '@/lib/accessibility'
import { useThemeColors } from '@/lib/theme'
import { cn } from '@/lib/utils'

export interface NotificationInboxEntry {
  id: string
  title: string
  message?: string
  source?: string
  /** A caller-localized timestamp or relative time. */
  time?: string
  read: boolean
}

export type NotificationInboxFilter = 'all' | 'unread'

const defaultLabels = {
  filters: 'Notification filter',
  all: 'All',
  unread: 'Unread',
  read: 'Read',
  unreadCount: (count: number) => `${count} unread`,
  empty: 'No notifications yet.',
  caughtUp: 'You’re caught up.',
  loading: 'Loading notifications…',
  reload: 'Try loading again',
  markAll: 'Mark all as read',
  markingAll: 'Marking as read…',
  markAllFailed: 'Could not mark notifications as read. Try again.',
}

export interface NotificationInboxProps extends Omit<ViewProps, 'children'> {
  className?: string
  /** Display order and read status come from the caller. IDs must be unique. */
  entries?: readonly NotificationInboxEntry[]
  filter?: NotificationInboxFilter
  onFilterChange?: (filter: NotificationInboxFilter) => void
  onOpen?: (id: string) => void
  /** Receives the unread IDs shown in the inbox when the action starts. */
  onMarkAllRead?: (ids: string[]) => void | boolean | Promise<void | boolean>
  loading?: boolean
  loadError?: string
  onRetryLoad?: () => void
  labels?: Partial<typeof defaultLabels>
  header?: React.ReactNode
}

export function NotificationInbox({
  className,
  entries = [],
  filter,
  onFilterChange,
  onOpen,
  onMarkAllRead,
  loading = false,
  loadError,
  onRetryLoad,
  labels,
  header,
  ...props
}: NotificationInboxProps) {
  const copy = { ...defaultLabels, ...labels }
  const colors = useThemeColors()
  const { width, fontScale } = useWindowDimensions()
  const stackMeta = width < 360 || fontScale >= 1.4
  const [internalFilter, setInternalFilter] = React.useState<NotificationInboxFilter>('all')
  const shownFilter = filter ?? internalFilter
  const unread = entries.filter((item) => !item.read)
  const visible = shownFilter === 'unread' ? unread : entries
  const [marking, setMarking] = React.useState(false)
  const [markFailed, setMarkFailed] = React.useState(false)
  const markRequest = React.useRef(false)
  const markUnavailable = loading || !!loadError || unread.length === 0
  const markError = markFailed && !markUnavailable
  const caughtUp = shownFilter === 'unread' && entries.length > 0 && unread.length === 0
  useAnnouncement(
    loading ? copy.loading : loadError || (markError ? copy.markAllFailed : caughtUp ? copy.caughtUp : undefined),
  )

  async function markAll() {
    if (!onMarkAllRead || markUnavailable || markRequest.current) return
    markRequest.current = true
    setMarking(true)
    setMarkFailed(false)
    try {
      if ((await onMarkAllRead(unread.map(({ id }) => id))) === false) setMarkFailed(true)
    } catch {
      setMarkFailed(true)
    } finally {
      markRequest.current = false
      setMarking(false)
    }
  }

  return (
    <View {...props} className={cn('min-h-0 flex-1', className)}>
      <FlatList
        data={visible}
        keyExtractor={(item) => item.id}
        ItemSeparatorComponent={ListSeparator}
        contentContainerStyle={{ paddingBottom: 16 }}
        ListHeaderComponent={
          <View className="gap-3 pb-3">
            {header}
            <SegmentedControl
              accessibilityLabel={copy.filters}
              value={shownFilter}
              onValueChange={(next) => {
                if (next !== 'all' && next !== 'unread') return
                if (filter === undefined) setInternalFilter(next)
                onFilterChange?.(next)
              }}
            >
              <SegmentedControlItem value="all">{copy.all}</SegmentedControlItem>
              <SegmentedControlItem value="unread">{copy.unread}</SegmentedControlItem>
            </SegmentedControl>
            {entries.length ? (
              <View className="flex-row flex-wrap items-center justify-between gap-x-2">
                <Text size="sm" variant="muted">
                  {copy.unreadCount(unread.length)}
                </Text>
                {onMarkAllRead ? (
                  <Button
                    variant="ghost"
                    accessibilityLabel={marking ? copy.markingAll : copy.markAll}
                    loading={marking}
                    disabled={markUnavailable}
                    onPress={() => {
                      void markAll()
                    }}
                  >
                    {marking ? copy.markingAll : copy.markAll}
                  </Button>
                ) : null}
              </View>
            ) : null}
            {loadError && !loading ? (
              <Alert accessibilityRole="none">
                <AlertDescription>{loadError}</AlertDescription>
                {onRetryLoad ? (
                  <Button
                    variant="outline"
                    className="self-start"
                    accessibilityLabel={copy.reload}
                    onPress={onRetryLoad}
                  >
                    {copy.reload}
                  </Button>
                ) : null}
              </Alert>
            ) : null}
            {markError ? (
              <Alert accessibilityRole="none" variant="destructive">
                <AlertDescription>{copy.markAllFailed}</AlertDescription>
              </Alert>
            ) : null}
            {loading ? (
              <View className="flex-row flex-wrap items-center gap-2">
                <ActivityIndicator color={colors.primary} accessible={false} />
                <Text size="sm" variant="muted">
                  {copy.loading}
                </Text>
              </View>
            ) : null}
          </View>
        }
        ListEmptyComponent={
          loading || loadError ? undefined : (
            <Text className="rounded-xl border border-border px-4 py-6 text-center">
              {caughtUp ? copy.caughtUp : copy.empty}
            </Text>
          )
        }
        renderItem={({ item }) => {
          const context = [item.source, item.time].filter(Boolean).join(' · ')
          return (
            <ListItem
              accessible
              accessibilityLabel={[
                item.title,
                item.message,
                item.source,
                item.time,
                item.read ? copy.read : copy.unread,
              ]
                .filter(Boolean)
                .join(', ')}
              onPress={onOpen ? () => onOpen(item.id) : undefined}
              className="items-start px-0 py-4"
            >
              <View aria-hidden className={cn('mt-2 size-2 rounded-full', !item.read && 'bg-primary')} />
              <ListItemContent>
                {context ? <ListItemDescription>{context}</ListItemDescription> : null}
                <ListItemTitle className={item.read ? undefined : 'font-semibold'}>{item.title}</ListItemTitle>
                {item.message ? (
                  <ListItemDescription numberOfLines={stackMeta || !onOpen ? undefined : 3}>
                    {item.message}
                  </ListItemDescription>
                ) : null}
              </ListItemContent>
            </ListItem>
          )
        }}
      />
    </View>
  )
}
components/blocks/notification-inbox/index.ts
export {
  NotificationInbox,
  type NotificationInboxEntry,
  type NotificationInboxFilter,
  type NotificationInboxProps,
} from './NotificationInbox'

Dependencies

Browse accounts and messaging