Notification Preferences
A caller-owned settings section with draft topic switches, explicit apply and discard, and recoverable save errors.
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-preferencesSource files
Expand a file to read the source the installer copies into your app.
components/blocks/notification-preferences/NotificationPreferences.tsx
import * as React from 'react'
import { View, type ViewProps } from 'react-native'
import { Alert, AlertDescription } from '@/components/ui/alert'
import { Button } from '@/components/ui/button'
import {
List,
ListItem,
ListItemContent,
ListItemDescription,
ListItemTitle,
ListSeparator,
} from '@/components/ui/list'
import { Switch } from '@/components/ui/switch'
import { Text } from '@/components/ui/text'
import { useAnnouncement } from '@/lib/accessibility'
import { cn } from '@/lib/utils'
type Preferences = Readonly<Record<string, boolean>>
const defaultLabels = {
applied: 'All changes applied',
pending: (count: number) => `${count} unsaved ${count === 1 ? 'change' : 'changes'}`,
apply: 'Apply changes',
applying: 'Applying changes…',
discard: 'Discard changes',
retry: 'Try again',
empty: 'No notification preferences available.',
}
export interface NotificationPreferencesProps extends ViewProps {
className?: string
/** NotificationPreference children with unique names. */
children?: React.ReactNode
applied: Preferences
draft: Preferences
onDraftChange: (name: string, checked: boolean) => void
onApply: (values: Record<string, boolean>) => void
onDiscard?: () => void
applying?: boolean
disabled?: boolean
/** Keeps the draft available for retry or discard. */
error?: string
labels?: Partial<typeof defaultLabels>
}
export interface NotificationPreferenceProps extends ViewProps {
className?: string
name: string
label: string
description?: string
disabled?: boolean
}
const PreferencesContext = React.createContext<{
values: Preferences
blocked: boolean
change: (name: string, value: boolean) => void
} | null>(null)
function preferenceRows(children: React.ReactNode): React.ReactElement<NotificationPreferenceProps>[] {
return React.Children.toArray(children).flatMap((child) => {
if (!React.isValidElement<{ children?: React.ReactNode }>(child)) return []
if (child.type === React.Fragment) return preferenceRows(child.props.children)
return child.type === NotificationPreference ? [child as React.ReactElement<NotificationPreferenceProps>] : []
})
}
export function NotificationPreferences({
className,
children,
applied,
draft,
onDraftChange,
onApply,
onDiscard,
applying = false,
disabled = false,
error,
labels,
...props
}: NotificationPreferencesProps) {
const rows = preferenceRows(children)
const copy = { ...defaultLabels, ...labels }
const blocked = applying || disabled
const values = { ...applied }
let changes = 0
for (const row of rows) {
const { name, disabled: unavailable } = row.props
const before = applied[name] === true
const next = unavailable ? before : (draft[name] ?? before)
values[name] = next
if (next !== before) changes++
}
const [requested, setRequested] = React.useState(false)
const message = applying ? copy.applying : changes ? copy.pending(changes) : copy.applied
const actionLabel = applying ? copy.applying : error ? copy.retry : copy.apply
useAnnouncement(applying ? message : error || (requested && !changes ? copy.applied : undefined))
return (
<PreferencesContext.Provider
value={{
values,
blocked,
change(name, checked) {
if (!blocked) onDraftChange(name, checked)
},
}}
>
<View {...props} className={cn('gap-3', className)}>
{rows.length ? (
<>
<List>
{rows.map((row, index) => (
<React.Fragment key={row.props.name}>
{index ? <ListSeparator /> : null}
{row}
</React.Fragment>
))}
</List>
<Text size="sm" variant="muted">
{message}
</Text>
{error && !applying ? (
<Alert variant="destructive">
<AlertDescription>{error}</AlertDescription>
</Alert>
) : null}
<Button
accessibilityLabel={actionLabel}
disabled={disabled || !changes}
loading={applying}
onPress={() => {
if (blocked || !changes) return
setRequested(true)
onApply({ ...values })
}}
>
{actionLabel}
</Button>
{changes && onDiscard ? (
<Button
variant="ghost"
accessibilityLabel={copy.discard}
disabled={blocked}
onPress={() => {
if (blocked) return
setRequested(false)
onDiscard()
}}
>
{copy.discard}
</Button>
) : null}
</>
) : (
<View className="items-center rounded-xl border border-border px-4 py-8">
<Text className="text-center font-medium">{copy.empty}</Text>
</View>
)}
</View>
</PreferencesContext.Provider>
)
}
export function NotificationPreference({
className,
name,
label,
description,
disabled,
accessibilityLabel,
accessibilityState,
...props
}: NotificationPreferenceProps) {
const group = React.useContext(PreferencesContext)
if (!group) throw new Error('NotificationPreference must be inside NotificationPreferences')
const checked = group.values[name] === true
const blocked = group.blocked || !!disabled
return (
<ListItem
{...props}
accessible
accessibilityRole="switch"
accessibilityLabel={accessibilityLabel ?? [label, description].filter(Boolean).join(', ')}
accessibilityState={{ ...accessibilityState, checked, disabled: blocked }}
disabled={blocked}
onPress={blocked ? undefined : () => group.change(name, !checked)}
className={cn('gap-3', className)}
>
<ListItemContent>
<ListItemTitle>{label}</ListItemTitle>
{description ? <ListItemDescription>{description}</ListItemDescription> : null}
</ListItemContent>
<View
aria-hidden
pointerEvents="none"
accessibilityElementsHidden
importantForAccessibility="no-hide-descendants"
>
<Switch checked={checked} accessible={false} focusable={false} tabIndex={-1} />
</View>
</ListItem>
)
}
components/blocks/notification-preferences/index.ts
export {
NotificationPreference,
NotificationPreferences,
type NotificationPreferenceProps,
type NotificationPreferencesProps,
} from './NotificationPreferences'