UIPackage React Native
Search
Menu

Delivery Instructions

Edit delivery handoff and optional notes with a caller-owned save and recoverable drafts.

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 delivery-instructions

Source files

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

components/blocks/delivery-instructions/DeliveryInstructions.tsx
import { useRef, useState } from 'react'
import { View, type ViewProps } from 'react-native'
import { Button } from '@/components/ui/button'
import { FormField } from '@/components/ui/form-field'
import { RadioGroup, RadioGroupItem } from '@/components/ui/radio-group'
import { Sheet, SheetClose, SheetContent, SheetTrigger } from '@/components/ui/sheet'
import { Text } from '@/components/ui/text'
import { Textarea } from '@/components/ui/textarea'
import { useAnnouncement } from '@/lib/accessibility'
import { cn } from '@/lib/utils'

export interface DeliveryHandoffOption {
  id: string
  label: string
  unavailableReason?: string
}

export interface DeliveryInstructionsValue {
  handoff: string | null
  note?: string
}

export interface DeliveryInstructionsProps extends Omit<ViewProps, 'children'> {
  className?: string
  title?: string
  value: DeliveryInstructionsValue
  /** Caller-owned options with unique and nonempty IDs. */
  options?: readonly DeliveryHandoffOption[]
  /** Return false or reject to retain the draft. Update value when saving succeeds. */
  onSave: (draft: DeliveryInstructionsValue) => void | boolean | Promise<void | boolean>
  labels?: Partial<
    Record<
      | 'edit'
      | 'close'
      | 'handoff'
      | 'unavailable'
      | 'empty'
      | 'choose'
      | 'note'
      | 'cancel'
      | 'save'
      | 'failed'
      | 'saved',
      string
    >
  >
}

const standardHandoff: readonly DeliveryHandoffOption[] = [
  { id: 'leave-at-door', label: 'Leave at the door' },
  { id: 'hand-it-to-me', label: 'Hand it to me' },
]

export function DeliveryInstructions({
  className,
  title = 'Delivery instructions',
  value,
  options = standardHandoff,
  onSave,
  labels,
  ...props
}: DeliveryInstructionsProps) {
  const submitting = useRef(false)
  const [draft, setDraft] = useState<DeliveryInstructionsValue | null>(null)
  const [saving, setSaving] = useState(false)
  const [failed, setFailed] = useState(false)
  const [saved, setSaved] = useState(false)
  const persisted = options.find((option) => option.id === value.handoff && !option.unavailableReason)
  const handoff = options.find((option) => option.id === draft?.handoff && !option.unavailableReason)
  const hasChoices = options.some((option) => !option.unavailableReason)
  const edit = labels?.edit ?? 'Edit delivery instructions'
  const saveLabel = labels?.save ?? 'Save instructions'
  const cancel = labels?.cancel ?? 'Cancel'
  const failedMessage = labels?.failed ?? 'Couldn’t save your instructions. Try again.'
  useAnnouncement(failed ? failedMessage : saved ? (labels?.saved ?? 'Delivery instructions saved') : undefined)

  async function save() {
    if (!draft || !handoff || submitting.current) return
    submitting.current = true
    setSaving(true)
    setFailed(false)
    try {
      if ((await onSave({ handoff: handoff.id, note: draft.note?.trim() ?? '' })) === false) {
        setFailed(true)
        return
      }
      setDraft(null)
      setSaved(true)
    } catch {
      setFailed(true)
    } finally {
      submitting.current = false
      setSaving(false)
    }
  }

  return (
    <View {...props} className={cn('gap-[12px]', className)}>
      <View className="gap-[4px]">
        <Text size="title" accessibilityRole="header">
          {title}
        </Text>
        <Text className="font-medium">{persisted?.label ?? labels?.choose ?? 'Choose a handoff method.'}</Text>
        {value.note?.trim() ? <Text variant="muted">{value.note}</Text> : null}
      </View>
      <Sheet
        open={draft !== null}
        onOpenChange={(open) => {
          if (submitting.current) return
          setFailed(false)
          setSaved(false)
          setDraft(open ? { ...value } : null)
        }}
      >
        <SheetTrigger variant="outline" accessibilityLabel={edit}>
          {edit}
        </SheetTrigger>
        <SheetContent
          title={edit}
          closeLabel={labels?.close ?? 'Close delivery instructions'}
          dismissOnBackdropPress={!saving}
        >
          {draft ? (
            <>
              <View className="gap-[4px]">
                <Text size="sm" className="font-semibold">
                  {labels?.handoff ?? 'Handoff method'}
                </Text>
                {options.length > 0 ? (
                  <RadioGroup
                    value={handoff?.id ?? ''}
                    accessibilityLabel={labels?.handoff ?? 'Handoff method'}
                    disabled={saving}
                    onValueChange={(next) => {
                      if (!submitting.current) setDraft((current) => current && { ...current, handoff: next })
                    }}
                    className="gap-0"
                  >
                    {options.map(({ id, label, unavailableReason }) => (
                      <RadioGroupItem
                        key={id}
                        value={id}
                        label={label}
                        disabled={Boolean(unavailableReason)}
                        accessibilityLabel={unavailableReason ? `${label}, ${unavailableReason}` : label}
                        className={unavailableReason && !saving ? 'opacity-100' : undefined}
                      >
                        {unavailableReason ? (
                          <Text size="sm" variant="muted">
                            {unavailableReason}
                          </Text>
                        ) : null}
                      </RadioGroupItem>
                    ))}
                  </RadioGroup>
                ) : null}
                {!hasChoices ? (
                  <Text size="sm" variant="muted">
                    {labels?.empty ?? 'No handoff methods are available.'}
                  </Text>
                ) : draft.handoff !== null && !handoff ? (
                  <Text size="sm" variant="muted">
                    {labels?.unavailable ?? 'Your previous method is unavailable. Choose another.'}
                  </Text>
                ) : null}
              </View>
              <FormField label={labels?.note ?? 'Delivery note (optional)'}>
                {(control) => (
                  <Textarea
                    {...control}
                    editable={!saving}
                    value={draft.note ?? ''}
                    onChangeText={(note) => {
                      if (!submitting.current) setDraft((current) => current && { ...current, note })
                    }}
                  />
                )}
              </FormField>
              {failed ? (
                <Text accessibilityRole="alert" className="text-destructive">
                  {failedMessage}
                </Text>
              ) : null}
              <View className="gap-[8px]">
                <Button
                  accessibilityLabel={saveLabel}
                  disabled={!handoff}
                  loading={saving}
                  onPress={() => {
                    void save()
                  }}
                >
                  {saveLabel}
                </Button>
                <SheetClose variant="outline" accessibilityLabel={cancel} disabled={saving}>
                  {cancel}
                </SheetClose>
              </View>
            </>
          ) : null}
        </SheetContent>
      </Sheet>
    </View>
  )
}
components/blocks/delivery-instructions/index.ts
export {
  DeliveryInstructions,
  type DeliveryHandoffOption,
  type DeliveryInstructionsProps,
  type DeliveryInstructionsValue,
} from './DeliveryInstructions'

Dependencies

Browse shopping and reservations