UIPackage React Native
Search

Offline Changes

Caller-owned offline changes with waiting, syncing, failed, synced, and recovery states.

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 offline-changes

Source files

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

components/blocks/offline-changes/OfflineChanges.tsx
import * as React from 'react'
import { View, type ViewProps } from 'react-native'
import { Alert, AlertDescription, AlertTitle } from '@/components/ui/alert'
import { Badge } from '@/components/ui/badge'
import { Button } from '@/components/ui/button'
import { Text } from '@/components/ui/text'
import { useAnnouncement } from '@/lib/accessibility'
import { cn } from '@/lib/utils'

export type OfflineChange = {
  id: string
  title: string
  detail?: string
} & ({ status: 'waiting' | 'sending' | 'synced' } | { status: 'failed'; reason: string })

export interface OfflineChangesProps extends ViewProps {
  className?: string
  title?: string
  changes?: readonly OfflineChange[]
  offline?: boolean
  /** Return your request promise or update the supplied row to syncing when a retry starts. */
  onRetry?: (id: string) => void | Promise<void>
  labels?: Partial<OfflineChangesLabels>
}

interface OfflineChangesLabels {
  offlineTitle: string
  offlineDescription: string
  emptyTitle: string
  emptyDescription: string
  waiting: string
  sending: string
  failed: string
  synced: string
  retry: string
  retryAction: (title: string) => string
}

const sample: OfflineChange[] = [
  { id: 'checklist', title: 'Workshop checklist', detail: 'Two updates', status: 'waiting' },
  { id: 'notes', title: 'Equipment notes', status: 'failed', reason: 'The server did not respond.' },
]

const defaultLabels: OfflineChangesLabels = {
  offlineTitle: 'You’re offline',
  offlineDescription: 'Reconnect to sync the changes waiting to send.',
  emptyTitle: 'No changes to sync',
  emptyDescription: 'Offline updates will appear here when they’re ready to send.',
  waiting: 'Waiting',
  sending: 'Syncing',
  failed: 'Needs attention',
  synced: 'Synced',
  retry: 'Retry',
  retryAction: (title) => `Retry ${title}`,
}

export function OfflineChanges({
  className,
  title = 'Offline changes',
  changes = sample,
  offline = false,
  onRetry,
  labels,
  ...props
}: OfflineChangesProps) {
  const copy = React.useMemo(() => ({ ...defaultLabels, ...labels }), [labels])
  const previous = React.useRef(new Map(changes.map(({ id, status }) => [id, status])))
  const requests = React.useRef(new Set<string>())
  const [pending, setPending] = React.useState<ReadonlySet<string>>(new Set())
  const [statement, setStatement] = React.useState('')
  useAnnouncement(statement)

  React.useEffect(() => {
    const updates = changes.filter(({ id, status }) => previous.current.has(id) && previous.current.get(id) !== status)
    previous.current = new Map(changes.map(({ id, status }) => [id, status]))
    if (updates.length) setStatement(updates.map(({ title, status }) => `${title}. ${copy[status]}`).join('. '))
  }, [changes, copy])

  async function retry(id: string) {
    if (offline || !onRetry || requests.current.has(id)) return
    requests.current.add(id)
    setPending(new Set(requests.current))
    try {
      await onRetry(id)
    } catch {
      // The caller owns the failure details and can keep or replace the failed row.
    } finally {
      requests.current.delete(id)
      setPending(new Set(requests.current))
    }
  }

  return (
    <View {...props} className={cn('gap-4', className)}>
      <Text size="title" accessibilityRole="header">
        {title}
      </Text>
      {offline ? (
        <Alert>
          <AlertTitle>{copy.offlineTitle}</AlertTitle>
          <AlertDescription>{copy.offlineDescription}</AlertDescription>
        </Alert>
      ) : null}
      {changes.length === 0 ? (
        <View className="gap-1 rounded-lg border border-border bg-card p-4">
          <Text className="font-semibold">{copy.emptyTitle}</Text>
          <Text size="sm" variant="muted">
            {copy.emptyDescription}
          </Text>
        </View>
      ) : (
        <View className="overflow-hidden rounded-xl border border-border bg-card">
          {changes.map((change, index) => (
            <View key={change.id} className={cn('gap-2 p-4', index > 0 && 'border-t border-border')}>
              <View className="flex-row flex-wrap items-start justify-between gap-2">
                <View className="min-w-[144px] flex-1 gap-1">
                  <Text className="font-semibold">{change.title}</Text>
                  {change.detail ? (
                    <Text size="sm" variant="muted">
                      {change.detail}
                    </Text>
                  ) : null}
                </View>
                <Badge variant={change.status === 'failed' ? 'outline' : 'secondary'} text={copy[change.status]} />
              </View>
              {change.status === 'failed' ? (
                <>
                  <Text size="sm" variant="muted">
                    {change.reason}
                  </Text>
                  {onRetry ? (
                    <Button
                      variant="outline"
                      className="self-start"
                      disabled={offline}
                      loading={pending.has(change.id)}
                      accessibilityLabel={copy.retryAction(change.title)}
                      onPress={() => {
                        void retry(change.id)
                      }}
                    >
                      {copy.retry}
                    </Button>
                  ) : null}
                </>
              ) : null}
            </View>
          ))}
        </View>
      )}
    </View>
  )
}
components/blocks/offline-changes/index.ts
export { OfflineChanges, type OfflineChange, type OfflineChangesProps } from './OfflineChanges'

Dependencies

Browse work and productivity