UIPackage React Native
Search

Message Composer

A native multiline composer with optional attachment controls and draft retention after a failed send.

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 message-composer

Source files

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

components/ui/message-composer/MessageComposer.tsx
import * as React from 'react'
import { TextInput, View, type ViewProps } from 'react-native'
import { Button } from '@/components/ui/button'
import { Text } from '@/components/ui/text'
import { Textarea, type TextareaProps } from '@/components/ui/textarea'
import { useAnnouncement } from '@/lib/accessibility'
import { cn } from '@/lib/utils'

const defaultLabels = {
  input: 'Message',
  placeholder: 'Write a message',
  attach: 'Add attachment',
  send: 'Send message',
  sending: 'Sending…',
  failed: 'Message could not be sent. Your draft is still here.',
}

export interface MessageComposerProps extends Omit<ViewProps, 'children'> {
  className?: string
  value: string
  onChangeText: (value: string) => void
  /** Return false or reject to keep the draft and offer a retry. */
  onSend: (message: string) => void | boolean | Promise<void | boolean>
  onAttach?: () => void
  attachment?: (state: { disabled: boolean }) => React.ReactNode
  /** Enable this for an attachment that can be sent without text. */
  allowEmptyMessage?: boolean
  disabled?: boolean
  inputProps?: Omit<
    TextareaProps,
    'value' | 'defaultValue' | 'onChangeText' | 'editable' | 'readOnly' | 'submitBehavior' | 'onSubmitEditing'
  >
  labels?: Partial<typeof defaultLabels>
}

function SendFailure({ message }: { message: string }) {
  useAnnouncement(message)
  return (
    <Text size="sm" className="text-destructive">
      {message}
    </Text>
  )
}

export const MessageComposer = React.forwardRef<React.ComponentRef<typeof TextInput>, MessageComposerProps>(
  (
    {
      className,
      value,
      onChangeText,
      onSend,
      onAttach,
      attachment,
      allowEmptyMessage = false,
      disabled = false,
      inputProps,
      labels,
      ...props
    },
    ref,
  ) => {
    const copy = { ...defaultLabels, ...labels }
    const [sending, setSending] = React.useState(false)
    const [failure, setFailure] = React.useState<{ attempt: number; draft: string }>()
    const request = React.useRef({ attempt: 0, pending: false })
    const active = React.useRef(false)
    const latest = React.useRef({ value, onChangeText })
    React.useLayoutEffect(() => {
      latest.current = { value, onChangeText }
    }, [value, onChangeText])
    React.useLayoutEffect(() => {
      active.current = true
      return () => {
        active.current = false
      }
    }, [])

    const blocked = disabled || sending
    const canSend = allowEmptyMessage || value.trim() !== ''
    const action = sending ? copy.sending : copy.send

    async function send() {
      const draft = latest.current.value
      const message = draft.trim()
      if (blocked || request.current.pending || (!allowEmptyMessage && !message)) return
      const attempt = ++request.current.attempt
      request.current.pending = true
      setSending(true)
      setFailure(undefined)
      try {
        const accepted = (await onSend(message)) !== false
        if (!active.current) return
        if (!accepted) {
          setFailure({ attempt, draft })
        } else if (latest.current.value === draft) {
          latest.current.onChangeText('')
        }
      } catch {
        if (active.current) setFailure({ attempt, draft })
      } finally {
        request.current.pending = false
        if (active.current) setSending(false)
      }
    }

    return (
      <View {...props} className={cn('gap-2', className)}>
        <Textarea
          ref={ref}
          accessibilityLabel={copy.input}
          placeholder={copy.placeholder}
          returnKeyType="default"
          {...inputProps}
          className={cn('max-h-[168px] min-h-[72px]', inputProps?.className)}
          editable={!blocked}
          value={value}
          submitBehavior="newline"
          onChangeText={(draft) => {
            if (blocked || request.current.pending) return
            setFailure(undefined)
            onChangeText(draft)
          }}
        />
        {attachment?.({ disabled: blocked })}
        {failure?.draft === value ? <SendFailure key={failure.attempt} message={copy.failed} /> : null}
        <View className={cn('flex-row flex-wrap items-center gap-2', onAttach ? 'justify-between' : 'justify-end')}>
          {onAttach ? (
            <Button
              accessibilityLabel={copy.attach}
              variant="outline"
              disabled={blocked}
              onPress={() => {
                if (!blocked && !request.current.pending) onAttach()
              }}
            >
              {copy.attach}
            </Button>
          ) : null}
          <Button accessibilityLabel={action} disabled={!canSend || disabled} loading={sending} onPress={send}>
            {action}
          </Button>
        </View>
      </View>
    )
  },
)
MessageComposer.displayName = 'MessageComposer'
components/ui/message-composer/index.ts
export { MessageComposer, type MessageComposerProps } from './MessageComposer'

Dependencies

Browse forms and selection