Command palette

@yasinsensoy/native

React Native · Components

Chat

Chat screen: messaging like WhatsApp or an AI chat like ChatGPT, with the same message data and prop names as web.

40 exports

Live example

The preview runs in the browser with the web component; the native component takes the same props and looks the same on iOS and Android.

Preview

AY
Ayşe Yılmazonline
Thursday, November 5
Messages are end-to-end encrypted
I sent the notes from yesterday's meeting, did you get a chance to look?
I did, it looks great 👏
Friday, November 6
And this is the final design. I lightened the colors a bit, the old palette was too dark.
Lovely! Let's show the client tomorrowedited
0:14
😂
The meeting is at 10:00, don't forget

Code

import { Chat, ChatHeader } from "@yasinsensoy/native";

<Chat
  messages={mesajlar}
  users={contacts}
  currentUserId="ben"
  header={<ChatHeader title="Ayşe Yılmaz" subtitle="online" />}
  onSend={send}
  onReact={(m, e) => update(m.id, { reactions: toggleReaction(m.reactions, e, "me") })}
  onEdit={edit}
  onDelete={remove}
  composer={{ attachments: true, voice: true }}
/>

Events

  1. Events appear here when you interact with the preview.

Import

import {
  TypingIndicator,
  Chat,
  ChatComposer,
  parseStreamData,
  toggleReaction,
  readChatStream,
  applyStreamPart,
  defaultChatMessages,
  enChatMessages,
  useChat,
} from "@yasinsensoy/native";

Chat

component

Chat screen: messaging like WhatsApp or an AI chat like ChatGPT, with the same message data and prop names as web. Grouping, day headers, text formatting and stream reading live in the shared core (@yasinsensoy/core/chat).

  • List: an inverted FlatList; the newest message at the bottom, onLoadMore when scrolling up. While scrolled up, a "jump to latest" button and the new message count.
  • Message: press and hold for a menu (react, reply, copy, edit, delete…), swipe right to reply, reaction chips, read ticks, attachments.
  • AI: thinking time, tool calls, sources, error and retry; copy / regenerate / rate below the response.
  • Keyboard: on iOS the composer moves above the keyboard.
Chat({ messages, mode, currentUserId, users, group: groupProp, status, onSend, onStop, onReact, onEdit, onDelete, onForward, onStar, onPin, onRetry, onRegenerate, onFeedback, onCopy, actions, customActions, canEdit, canDelete, confirmDelete, quickReactions, typing, hasMore, onLoadMore, unreadFrom, suggestions, empty, header, composer, groupWindow, collapseAfter, swipeToReply, timeZone, texts: textsProp, onOpenAttachment, style, }: ChatProps): JSX.Element

Examples

const chat = useChat({ send: ({ messages, signal }) => fetch(API, { method: "POST", body: JSON.stringify({ messages }), signal }) });
<Chat mode="assistant" {...chat.props} suggestions={["What's the weather today?"]} />

<Chat messages={messages} currentUserId={me} users={people} typing={typingUsers}
  onSend={send} onReact={(m, e) => react(m.id, toggleReaction(m.reactions, e, me))} />

Three bouncing dots (same as web). Chat shows it itself; it can also be used on its own in a header or contact list.

TypingIndicator({ label, color, style }: TypingIndicatorProps): JSX.Element

Examples

`<TypingIndicator label="Jane is typing…" />`

ChatComposer

component

The chat's composer: for messaging and AI prompts. Grows as you type (up to 6 lines), attachments show with small previews, reply and edit bars appear on top; while streaming the send button becomes "Stop". Chat renders it itself; it can also be used on its own.

ChatComposer({ onSend, value, defaultValue, onValueChange, variant, placeholder, disabled, status, onStop, onPickFiles, maxFiles, replyTo, replyAuthor, replyColor, onCancelReply, editing, onCancelEdit, maxLength, toolbar, footer, onTyping, autoFocus, ref, messages: overrides, }: ChatComposerProps): JSX.Element

Examples

<ChatComposer variant="assistant" status={status} onStop={stop}
  onSend={({ text }) => ask(text)} />

Turns an SSE data: line into a part. Recognizes your own part objects (type field), OpenAI (choices[0].delta.content), Anthropic (delta.text, delta.thinking) and { text | content | delta }; when it is not JSON it is the text itself. [DONE] and unknown ones are null.

parseStreamData(data: string): ChatStreamPart | null

Toggles a reaction and returns the new list (does not mutate the array). With single (default, like WhatsApp) the person's previous reaction is removed.

toggleReaction(reactions: readonly ChatReaction[] | undefined, emoji: string, userId: string, options?: { single?: boolean; }): ChatReaction[]

Examples

onReact={(message, emoji) =>
  update(message.id, { reactions: toggleReaction(message.reactions, emoji, myId) })
}

Turns a stream into parts: Response (fetch), ReadableStream, AsyncIterable or a single text. In SSE responses data: lines are decoded with parse (default parseStreamData).

readChatStream(source: ChatStreamSource, options?: { parse?: (data: string) => ChatStreamPart | null; signal?: { readonly aborted: boolean; }; }): AsyncGenerator<ChatStreamPart>

Examples

for await (const part of readChatStream(await fetch("/api/chat"))) { ... }

Applies a part to a message and returns the new message.

applyStreamPart(message: M, part: ChatStreamPart): M

Turkish chat texts.

defaultChatMessages: ChatMessages

English chat texts (the web en dictionary and React Native use the same text).

enChatMessages: ChatMessages

useChat

function

Manages the state of an AI chat (same API as web's useChat): keeps the messages, reads the response as a stream, stops, regenerates and edits. Chunks render once per frame; thinking time is measured.

useChat(options: UseChatOptions): UseChatResult

Examples

const chat = useChat({
  send: ({ messages, signal }) =>
    fetch(API, { method: "POST", body: JSON.stringify({ messages }), signal }),
});
return <Chat mode="assistant" {...chat.props} />;

Chat type: messaging like WhatsApp or an AI chat like ChatGPT.

type ChatMode = "messaging" | "assistant"

Suggestion chip: text, or a separate label + prompt.

type ChatSuggestion = string | { label: ReactNode; prompt: string; }

ChatProps

interface

Props of Chat (same names as web).

NameTypeDefaultDescription
messagesreadonly ChatMessage[]Messages, oldest to newest.
mode?ChatMode"messaging"Type.
currentUserId?stringYour own user ID: whether a message is drawn on the right or the left.
users?readonly ChatUser[]People (name, avatar).
group?booleantrue` if there are more than 2 peopleGroup chat: names and avatars are shown.
status?ChatStatusAI status.
onSend?(draft: ChatDraft) => unknownWhen a message is sent.
onStop?() => voidWhen "Stop" is pressed.
onReact?(message: ChatMessage, emoji: string) => voidWhen a reaction is given (toggle with toggleReaction).
onEdit?(message: ChatMessage, text: string) => unknownWhen a message is edited.
onDelete?(message: ChatMessage) => unknownWhen a message is deleted.
onForward?(message: ChatMessage) => voidForward.
onStar?(message: ChatMessage) => voidStar.
onPin?(message: ChatMessage) => voidPin.
onRetry?(message: ChatMessage) => voidWhen a failed message or an errored response is tapped.
onRegenerate?(message: ChatMessage) => voidRegenerate the response.
onFeedback?(message: ChatMessage, value: "up" | "down" | null) => void👍/👎.
onCopy?(message: ChatMessage) => voidCopy: the app writes to the clipboard (no extra dependency). The action is hidden if not given.
actions?readonly ChatActionName[]Only these actions are shown.
customActions?readonly ChatCustomAction[]Custom actions added to the menu.
canEdit?(message: ChatMessage) => booleanown messages that are not deletedCan a message be edited?
canDelete?(message: ChatMessage) => booleanown messages that are not deletedCan a message be deleted?
confirmDelete?booleantrueAsk before deleting.
quickReactions?readonly string[]Quick reactions in the menu.
typing?readonly string[]IDs of the people typing ("Jane is typing…").
hasMore?booleanfalseAre there older messages?
onLoadMore?() => unknownFetches older messages when scrolling up; the indicator spins until the Promise settles.
unreadFrom?string"Unread" divider starting from this message.
suggestions?readonly ChatSuggestion[]Suggestion chips in an empty chat.
empty?ReactNodeContent shown when empty.
header?ReactNodeHeader at the top (e.g. person name, avatar).
composer?Partial<Omit<ChatComposerProps, "onSend">> | falseComposer settings; false hides it.
groupWindow?number5 minutesMessages from the same person within this time (ms) form one block.
collapseAfter?number700Messages longer than this many characters are shortened with "Read more".
swipeToReply?booleantrueSwipe a message right to reply.
timeZone?stringTime zone.
texts?Partial<ChatMessages>Texts of this chat.
onOpenAttachment?(attachment: ChatAttachment, message: ChatMessage) => voidWhen an attachment (image, file) is tapped; fullscreen or opening is up to the app.
style?StyleProp<ViewStyle>Container style.

Three bouncing dots: the "typing…" and "thinking" state.

NameTypeDefaultDescription
label?stringText read by screen readers (e.g. "Jane is typing…").
color?stringthe muted text colorDot color.
style?StyleProp<ViewStyle>Container style.

Composer look: messaging or an AI prompt.

type ChatComposerVariant = "messaging" | "assistant"

Methods of the ChatComposer ref.

NameTypeDescription
focus() => voidFocuses the input.
addFiles(files: Iterable<ChatFile>) => voidAdds files (at most maxFiles).
insertText(text: string) => voidAppends to the end of the text.
clear() => voidClears the text and attachments.

Props of ChatComposer (same names as web).

NameTypeDefaultDescription
onSend(draft: ChatDraft) => unknownWith the draft when sent.
value?stringText (controlled).
defaultValue?stringInitial text.
onValueChange?(value: string) => voidWhen the text changes.
variant?ChatComposerVariant"messaging"Look.
placeholder?stringPlaceholder.
disabled?booleanDisabled.
status?ChatStatus"ready"AI status; while streaming the send button becomes "Stop".
onStop?() => voidWhen "Stop" is pressed.
onPickFiles?() => Promise<readonly ChatFile[] | undefined | null> | readonly ChatFile[]Paperclip button: called on tap; return the chosen files (your own image/document picker). The component uses no extra dependency.
maxFiles?number10Maximum files in one message.
replyTo?ChatMessage | nullThe message being replied to.
replyAuthor?ReactNodeAuthor of the message being replied to.
replyColor?stringColor of the reply bar.
onCancelReply?() => voidWhen the reply is dismissed.
editing?ChatMessage | nullThe message being edited.
onCancelEdit?() => voidWhen editing is dismissed.
maxLength?numberMaximum characters.
toolbar?ReactNodeExtra buttons to the left of the input.
footer?ReactNodeContent below the input.
onTyping?() => voidCalled while typing (at most once every 3 seconds): for the "typing…" status.
autoFocus?booleanFocus on mount.
ref?Ref<ChatComposerHandle>Control functions.
messages?Partial<ChatMessages>Texts of this composer.

ChatMessages

interface

Texts of the chat components (Chat, ChatComposer, EmojiPicker). Replace them app-wide in the dictionary's ui.chat namespace, or for one chat with the messages prop. Placeholders such as {count} and {name} are filled at runtime.

NameTypeDefaultDescription
liststring"Mesajlar"Screen reader name of the message list.
youstring"Sen"Author of your own messages (in quotes, reactions).
unreadstring"{count} okunmamış mesaj"Unread messages separator.
jumpToLateststring"En yeni mesajlara git"Scroll down button.
newMessagesstring"{count} yeni mesaj"Count of new messages that arrived while scrolled up.
loadingOlderstring"Eski mesajlar yükleniyor…"While older messages load.
editedstring"düzenlendi"Note next to the time of an edited message.
deletedstring"Bu mesaj silindi"Deleted message.
deletedOwnstring"Bu mesajı sildin"Your own deleted message.
forwardedstring"İletildi"Note above a forwarded message.
readMorestring"Devamını oku"Link that expands a long message.
sendingstring"Gönderiliyor"Delivery status.
sentstring"Gönderildi"Delivery status: single tick.
deliveredstring"Teslim edildi"Delivery status: double tick.
readstring"Okundu"Delivery status: blue double tick.
failedstring"Gönderilemedi. Yeniden denemek için dokun."Message that failed to send.
starredstring"Yıldızlı"Starred message marker.
pinnedstring"Sabitlendi"Pinned message marker.
reactstring"Tepki ver"Reaction button.
replystring"Yanıtla"Reply action.
copystring"Kopyala"Copy action.
copiedstring"Kopyalandı"After copying.
editstring"Düzenle"Edit action.
deletestring"Sil"Delete action.
forwardstring"İlet"Forward action.
starstring"Yıldızla"Star action.
unstarstring"Yıldızı kaldır"Unstar action.
pinstring"Sabitle"Pin action.
unpinstring"Sabitlemeyi kaldır"Unpin action.
retrystring"Yeniden dene"Retry action.
regeneratestring"Yeniden oluştur"Regenerate response action.
goodstring"İyi yanıt"Like button.
badstring"Kötü yanıt"Dislike button.
morestring"Diğer"More actions menu.
moreReactionsstring"Diğer emojiler"+ button in the reaction bar.
messageActionsstring"Mesaj eylemleri"Screen reader name of the action panel.
deleteTitlestring"Mesaj silinsin mi?"Delete confirmation title.
deleteDescriptionstring"Mesaj herkes için silinir."Delete confirmation description.
reactedBystring"{names} tepki verdi"Tooltip of a reaction chip.
typingstring"{name} yazıyor…"While one person types.
typingTwostring"{a} ve {b} yazıyor…"While two people type.
typingManystring"{count} kişi yazıyor…"While three or more people type.
thinkingstring"Düşünüyor…"While thinking.
thoughtstring"Düşünme"Thinking section of unknown duration.
thoughtForstring"{seconds} sn düşündü"Thinking duration.
toolRunningstring"Çalışıyor"Tool running.
toolDonestring"Tamamlandı"Tool finished.
toolErrorstring"Hata"Tool failed.
toolInputstring"Girdi"Tool input title.
toolOutputstring"Çıktı"Tool output title.
sourcesstring"Kaynaklar"Sources list.
errorTitlestring"Yanıt alınamadı"Default text of the error box.
placeholderstring"Mesaj yaz"Placeholder of the input in messaging.
placeholderAssistantstring"Bir şey sor…"Placeholder in AI chat.
sendstring"Gönder"Send button.
stopstring"Durdur"Stop response button.
attachstring"Dosya ekle"Attach file button.
emojistring"Emoji"Emoji button.
recordstring"Sesli mesaj kaydet"Record button.
sendRecordingstring"Sesli mesajı gönder"Finish and send the recording.
cancelRecordingstring"Kaydı sil"Cancel the recording.
recordingstring"Kaydediliyor"While recording.
micDeniedstring"Mikrofona erişilemedi"When there is no microphone permission.
replyingTostring"{name} yanıtlanıyor"Reply bar.
cancelReplystring"Yanıtı iptal et"Close the reply bar.
editingstring"Mesajı düzenliyorsun"Edit bar.
cancelEditstring"Düzenlemeyi iptal et"Close the edit bar.
removeFilestring"{name} kaldır"Remove button in the attachment preview.
dropFilesstring"Dosyaları buraya bırak"Drag and drop area.
tooManyFilesstring"En fazla {max} dosya eklenebilir"When the file limit is exceeded.
fileTooLargestring"{name} çok büyük (en fazla {max})"When the size limit is exceeded.
fileNotAcceptedstring"{name} desteklenmiyor"When the type is not accepted.
voiceMessagestring"Sesli mesaj"Voice message attachment.
photostring"Fotoğraf"Image attachment (in quotes).
videostring"Video"Video attachment (in quotes).
filestring"Dosya"File attachment (in quotes).
playstring"Oynat"Play the voice message.
pausestring"Duraklat"Pause the voice message.
speedstring"Oynatma hızı"Speed button.
downloadstring"İndir"Download the file.
openMediastring"Tam ekran aç"Open the image/video full screen.
moreMediastring"+{count}"Count of attachments that do not fit the grid.
emptyTitlestring"Henüz mesaj yok"Empty messaging.
emptyAssistantstring"Nasıl yardımcı olabilirim?"Empty AI chat.
suggestionsstring"Öneriler"Screen reader name of the suggestion chips.
emojiRecentstring"Son kullanılanlar"Emoji category.
emojiSmileysstring"Yüzler"Emoji category.
emojiPeoplestring"İnsanlar"Emoji category.
emojiNaturestring"Doğa"Emoji category.
emojiFoodstring"Yiyecek"Emoji category.
emojiActivitystring"Etkinlik"Emoji category.
emojiTravelstring"Seyahat"Emoji category.
emojiObjectsstring"Nesneler"Emoji category.
emojiSymbolsstring"Semboller"Emoji category.

A part coming from the stream. A plain text part (string) is appended to the response.

  • { type: "text", text }: Text appended to the response.
  • { type: "reasoning", text }: Text appended to the thinking section.
  • { type: "tool", id, ... }: A tool call; the same id is updated.
  • { type: "source", url, title }: Adds a source.
  • { type: "message", message }: Changes message fields directly (e.g. { attachments }, { body }).
  • { type: "error", error }: The response ends with an error.
type ChatStreamPart = string | { type: "text"; text: string; } | { type: "reasoning"; text: string; } | ({ type: "tool"; } & ChatToolCall) | ({ type: "source"; } & ChatSource) | { type: "message"; message: Partial<Omit<ChatMessage, "id">>; } | { type: "error"; error: string; }

Values accepted as dates: Date, an ISO string or milliseconds.

type ChatDate = Date | string | number

Role of the message author.

  • "user": The person using the app (on the right).
  • "assistant": The AI or the other party (on the left).
  • "system": Small info line in the middle ("Ayşe joined the group").
type ChatRole = "user" | "assistant" | "system"

A tool call by the AI.

type ChatToolCall = Core.ChatToolCall<ReactNode>

A source the response is based on.

type ChatSource = Core.ChatSource<ReactNode>

Link preview.

type ChatLinkPreview = Core.ChatLinkPreview<ReactNode>

A chat message (same fields as web).

type ChatMessage = Core.ChatMessage<ReactNode>

Delivery status of a message; shows as ticks next to the time of your own messages (like WhatsApp).

  • "sending": Sending (clock icon).
  • "sent": Reached the server (single tick).
  • "delivered": Reached the recipient (double tick).
  • "read": Read (blue double tick).
  • "failed": Failed to send (red warning; tap to retry).
type ChatMessageStatus = "sending" | "sent" | "delivered" | "read" | "failed"

ChatFile

interface

A file added to the composer. The app provides the picker (e.g. your own image picker); the component only shows and sends it.

NameTypeDescription
uristringURL of the file (file://, content://, https://).
name?stringFile name.
type?stringMIME type (image/jpeg).
size?numberSize (bytes).
width?numberImage width (px).
height?numberImage height (px).

ChatUser

interface

A person in the chat.

NameTypeDescription
idstringUnique id; matches the messages' authorId.
namestringDisplay name.
avatar?stringProfile photo.
color?stringName color in group chats (e.g. "#e11d48", "var(--ui-primary)"). When omitted, a stable color is picked from the id.
status?"online" | "away" | "busy" | "offline"Online status; a dot on the avatar's corner.

Custom action added to the message menu.

NameTypeDescription
labelstringDisplay name.
icon?IconPropIcon.
tone?"neutral" | "danger"Red (dangerous) action.
onSelect(message: ChatMessage) => voidCalled with the message when chosen.
when?(message: ChatMessage) => booleanShow only on these messages.

Attachment kind. When omitted, it is derived from type (MIME) or the file name.

  • "image", "video": Thumbnail in a grid; full screen on click.
  • "audio": Voice message player (waveform, speed).
  • "file": File card (icon, name, size, download).
type ChatAttachmentKind = "image" | "video" | "audio" | "file"

ChatDraft

interface

Draft sent from the composer (same as web; files are ChatFile).

NameTypeDescription
textstringText (trimmed).
filesChatFile[]Attached files.
replyTo?ChatMessageThe message being replied to.

Message attachment: image, video, audio or file.

NameTypeDescription
id?stringUnique id. When omitted, url or the name is used.
name?stringFile name.
url?stringAddress (download, playback, full screen). A local preview can be given while uploading.
type?stringMIME type (e.g. "image/png", "audio/webm").
kind?ChatAttachmentKindKind. See ChatAttachmentKind.
size?numberSize (bytes).
thumbnail?stringThumbnail (shown in the grid instead of url).
width?numberNatural width (px); when given, space is reserved before the image loads, so nothing shifts.
height?numberNatural height (px).
duration?numberDuration of audio and video (seconds).
waveform?readonly number[]Waveform of a voice message: samples between 0 and 1 (30-60 are enough). When omitted, a fixed pattern is drawn.
progress?numberUpload progress (0-1). When given, a ring shows over the attachment.

ChatReaction

interface

A reaction: the emoji and who reacted.

NameTypeDescription
emojistringEmoji (e.g. "👍").
usersreadonly string[]Ids of the people who reacted. The count is its length.

ChatReasoning

interface

A thinking step of the AI.

NameTypeDescription
textstringThinking text (Markdown).
duration?numberThinking duration (seconds); written as "Thought for 12 s".

Names of the actions on a message. ChatProps.actions picks which actions show.

type ChatActionName = "react" | "reply" | "copy" | "edit" | "delete" | "forward" | "star" | "pin" | "retry" | "regenerate" | "feedback"

Chat state (AI). While "submitted" and "streaming", the send button becomes "Stop".

  • "ready": Ready.
  • "submitted": Request sent, waiting for the first part (three dots).
  • "streaming": The response is streaming.
  • "error": The last request failed.
type ChatStatus = "ready" | "submitted" | "streaming" | "error"

Info passed to UseChatOptions.send.

NameTypeDescription
messagesChatMessage[]History to respond to: the last message is the user's new message.
signalAbortSignalAborted when "Stop" is pressed; pass it to fetch.
filesChatFile[]Files the user attached (to the last message).

Responses the send function can return: a fetch response (read even if it does not stream; SSE, OpenAI and Anthropic formats are recognized), a stream, an async function* generator or text.

type ChatSendResult = ChatStreamSource

Options of useChat (same as web).

NameTypeDescription
send(context: ChatSendContext) => ChatSendResult | Promise<ChatSendResult>Produces the response.
initialMessages?readonly ChatMessage[]Initial messages.
parse?(data: string) => ChatStreamPart | nullParsing of an SSE data: line.
onFinish?(message: ChatMessage, messages: ChatMessage[]) => voidWhen the response ends (even if stopped).
onError?(error: unknown) => voidWhen the request fails.
onFeedback?(message: ChatMessage, value: "up" | "down" | null) => voidWhen the user gives 👍/👎.
attachment?(file: ChatFile) => ChatAttachment | Promise<ChatAttachment>Turns an added file into a message attachment (e.g. upload and return its URL). Defaults to the local URL.
generateId?() => stringGenerates a new message ID.

UseChatResult

interface

Result of useChat (same as web).

NameTypeDescription
messagesChatMessage[]Messages.
setMessages(messages: ChatMessage[] | ((current: ChatMessage[]) => ChatMessage[])) => voidChanges the messages directly.
statusChatStatusStatus.
errorunknownLast error.
send(input: string | ChatDraft) => Promise<void>Sends a message (text or a draft).
stop() => voidStops the streaming response.
regenerate(message?: ChatMessage) => Promise<void>Regenerates the last (or the given) response.
edit(message: ChatMessage, text: string) => Promise<void>Edits a user message and regenerates what follows.
props{ messages: ChatMessage[]; status: ChatStatus; onSend: (draft: ChatDraft) => Promise<void>; onStop: () => void; onRegenerate: (message: ChatMessage) => void; onRetry: (message: ChatMessage) => void; onEdit: (message: ChatMessage, text: string) => Promise<void>; onFeedback: (message: ChatMessage, value: "up" | "down" | null) => void; }Props to spread onto Chat: <Chat mode="assistant" {...chat.props} />.