From 9717bffdb42b3dd329521f2efff2187a9087848b Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 14:12:30 +0000 Subject: [PATCH] Add @hibira-io/react-native/chat for the Hibira Chat API (0.2.0) A client for the user routes with translations, live chat.* events from a signed-in pusher-js client, and stores and hooks for one conversation and the user's conversation list. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01SHtsCEQwpWuQjtxBkWhUuZ --- CHANGELOG.md | 9 + README.md | 60 +++++ chat.d.ts | 194 +++++++++++++++ chat.js | 573 ++++++++++++++++++++++++++++++++++++++++++++ package-lock.json | 4 +- package.json | 11 +- test/chat.test.mjs | 185 ++++++++++++++ test/types.test.tsx | 24 ++ version.js | 2 +- 9 files changed, 1057 insertions(+), 5 deletions(-) create mode 100644 chat.d.ts create mode 100644 chat.js create mode 100644 test/chat.test.mjs diff --git a/CHANGELOG.md b/CHANGELOG.md index 60d056e..d60fd4c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,14 @@ # Changelog +## 0.2.0 + +- `@hibira-io/react-native/chat`: a client for the Hibira Chat API's user + routes (including translations and the user's language), live `chat.*` + events from a signed-in pusher-js client, and `useChatConversation` / + `useChatConversations` (with `createConversationStore` / + `createConversationListStore` for use without React): history paging, + typing, read receipts, unread counts and catch-up after reconnects. + ## 0.1.1 - Fix: `HibiraProvider` with `appKey` crashed on React Native with diff --git a/README.md b/README.md index aa29dc9..a90e5b9 100644 --- a/README.md +++ b/README.md @@ -245,6 +245,66 @@ messaging().onTokenRefresh((token) => push.updateToken(token)); Pass `endpoint` for a self-hosted server. +## Chat + +`@hibira-io/react-native/chat` is a client for the +[Hibira Chat API](https://hibira.io/chat-api): conversations with stored +history, live messages, edits, reactions, typing, read receipts and +translations. Live events come from the provider's connection once the user +is signed in (`pusher.signin()`), so there is nothing else to wire. + +Your backend gives the app two things, both signed with the app secret: + +1. A **user token** for the HTTP calls: an HS256 JWT `{"sub": userId, "exp": ...}` + (or one from the Chat API's `POST /apps/{app_id}/chat/tokens`). +2. A **user authentication endpoint** for `pusher.signin()` + (`pusher.authenticateUser(socket_id, { id })` in the Node library), set as + `userAuthentication: { endpoint }` in the provider's options. + +```jsx +import { HibiraProvider, usePusher } from '@hibira-io/react-native'; +import { useChatClient, useChatConversation, useChatConversations, messageText } from '@hibira-io/react-native/chat'; + + + +; + +function Chat() { + const pusher = usePusher(); + useEffect(() => pusher?.signin(), [pusher]); + const chat = useChatClient({ appId: 'YOUR_APP_ID', token: () => api.fetchChatToken() }); + const { conversations, unread } = useChatConversations(chat); + // ... +} + +function Room({ chat, id }) { + const room = useChatConversation(chat, id); + return ( + String(m.seq)} + renderItem={({ item }) => {item.deleted_at ? 'Message deleted' : messageText(item, myLanguage)}} + onStartReached={room.loadOlder} + onViewableItemsChanged={() => room.markRead()} + ListFooterComponent={room.typingUsers.length ? {room.typingUsers.join(', ')} typing… : null} + /> + ); + // In the composer: onChangeText={() => room.typing()} and room.send(text). +} +``` + +The conversation re-reads its newest messages each time the connection +comes back, so edits, deletes and reactions made while the app was in the +background show up. The client has every user route (`conversations`, +`messages`, `search`, `send`, `edit`, `remove`, `react`, `report`, `read`, +`typing`, `translate`, `setLanguage`, `upload` from a picker's `{ uri }`), +and `createConversationStore` / `createConversationListStore` work without +React. Set the user's language with `chat.setLanguage('ja')` and messages +from others arrive translated a moment later; `messageText(m, 'ja')` picks +the translation (translation needs a Chat add-on on the hosted service). + +中文摘要:`@hibira-io/react-native/chat` 是 Hibira Chat API 的 React Native 用戶端。`useChatClient` 用 provider 的連線收 `chat.*` 即時事件(使用者需先 `pusher.signin()`),`useChatConversation` 提供單一對話的訊息、往前翻頁、輸入中、已讀與翻譯,重連後自動補齊;`useChatConversations` 提供含未讀數的對話列表。App 需要你的後端提供使用者 token(用 app secret 簽的 JWT)和使用者認證端點;建立對話、加成員仍由你的後端呼叫。 + ## Example [`example/`](example) is an Expo app with a live order feed, presence, a diff --git a/chat.d.ts b/chat.d.ts new file mode 100644 index 0000000..2a5768e --- /dev/null +++ b/chat.d.ts @@ -0,0 +1,194 @@ +export const DEFAULT_CHAT_HOST: string; +export const CHAT_EVENTS: readonly string[]; +export const TYPING_SHOW_MS: number; + +export interface ChatMember { + user_id: string; + read_seq: number; + role?: string; +} + +export interface ChatConversation { + id: string; + name?: string; + metadata?: Record; + members: ChatMember[]; + last_seq: number; + created_at: string; + updated_at: string; + /** In conversation lists: messages after the user's read_seq that are not system messages. */ + unread?: number; +} + +export interface ChatAttachment { + id: string; + name: string; + content_type: string; + size?: number; + /** A download link, valid for an hour. */ + url?: string; +} + +export interface ChatMessage { + id: string; + seq: number; + /** The sender's user ID; absent on system messages. */ + sender?: string; + name?: string; + /** "text", or "system" for messages your server posts. */ + kind?: string; + text: string; + metadata?: Record; + created_at: string; + edited_at?: string; + deleted_at?: string; + /** Each emoji and the members who reacted, in order. */ + reactions?: Record; + attachments?: ChatAttachment[]; + visible_to?: string[]; + /** The language text was written in. */ + language?: string; + /** The text translated, by BCP 47 language tag. */ + translations?: Record; +} + +export interface ChatReport { + id: string; + conversation_id: string; + seq: number; + reported_by: string; + reason: string; + message: ChatMessage; +} + +export interface SendInput { + text?: string; + name?: string; + metadata?: Record; + attachments?: Pick[]; + visible_to?: string[]; +} + +/** A Blob, or what an image or document picker returns. */ +export type UploadFile = Blob | { uri: string; name?: string; type?: string; size?: number }; + +export interface ChatClientOptions { + /** The Hibira app ID. */ + appId: string; + /** The user token, or a function returning one; called again before it expires and after a 401. */ + token?: string | (() => string | Promise); + /** Instead of token: a URL on your server that answers { token }. */ + tokenUrl?: string; + /** A pusher-js client signed in as the user (pusher.signin()), for live events. */ + pusher?: unknown; + /** The HTTP API host (default api.hibira.io); may include http://. */ + host?: string; + fetch?: typeof fetch; +} + +type Opts = { signal?: AbortSignal }; +export type ChatEventHandler = (event: string, data: any) => void; + +export interface ChatClient { + /** The token's user (sub), once a token is known. */ + user(): string; + currentUser(): Promise; + conversations(options?: { limit?: number; before?: string } & Opts): Promise<{ conversations: ChatConversation[]; next: string }>; + conversation(id: string, options?: Opts): Promise; + messages(id: string, options?: { after?: number; last?: number; limit?: number } & Opts): Promise<{ messages: ChatMessage[]; last_seq: number }>; + search(id: string, q: string, options?: { before?: number | string; limit?: number } & Opts): Promise<{ messages: ChatMessage[]; next: string }>; + send(id: string, message: string | SendInput): Promise<{ message: ChatMessage; push?: { users: number; error?: string } }>; + edit(id: string, seq: number, change: string | { text?: string; metadata?: Record }): Promise; + remove(id: string, seq: number): Promise; + react(id: string, seq: number, emoji: string, on?: boolean): Promise; + report(id: string, seq: number, reason?: string): Promise; + read(id: string, seq: number): Promise<{ read_seq: number }>; + typing(id: string, typing?: boolean): Promise; + translate(id: string, seq: number, language: string): Promise; + me(): Promise<{ user_id: string; language?: string | null }>; + setLanguage(language: string | null): Promise<{ user_id: string; language?: string | null }>; + upload(id: string, file: UploadFile, options?: { name?: string; type?: string; size?: number }): Promise; + on(handler: ChatEventHandler): () => void; + onLive(handler: () => void): () => void; + handleEvent(event: string, data: unknown): boolean; + notifyLive(): void; + attach(pusher: unknown): () => void; +} + +export class ChatApiError extends Error { + status: number; + constructor(status: number, message?: string); +} + +export function createChatClient(options: ChatClientOptions): ChatClient; +export function tokenUser(token: string): string; +export function messageText(message: ChatMessage | null | undefined, lang?: string | null): string; + +export interface ConversationState { + conversation: ChatConversation | null; + messages: ChatMessage[]; + loading: boolean; + loadingOlder: boolean; + hasOlder: boolean; + /** Members typing right now (not the user). */ + typing: string[]; + /** Each member's read_seq. */ + reads: Record; + /** Deleted, or the user was removed. */ + closed: boolean; + error: unknown; +} + +export interface ConversationStore { + get(): ConversationState; + subscribe(fn: () => void): () => void; + start(): void; + stop(): void; + refresh(): Promise; + apply: ChatEventHandler; + loadOlder(): Promise; + send(message: string | SendInput): Promise; + edit(seq: number, change: string | { text?: string; metadata?: Record }): Promise; + remove(seq: number): Promise; + translate(seq: number, language: string): Promise; + toggleReaction(seq: number, emoji: string): Promise; + markRead(): Promise; + /** Call on every keystroke. */ + typing(): void; + stopTyping(): Promise; + readBy(seq: number): string[]; +} + +export interface ConversationListState { + conversations: ChatConversation[]; + loading: boolean; + loadingMore: boolean; + hasMore: boolean; + /** Unread messages across the loaded conversations. */ + unread: number; + error: unknown; +} + +export interface ConversationListStore { + get(): ConversationListState; + subscribe(fn: () => void): () => void; + start(): void; + stop(): void; + refresh(): Promise; + apply: ChatEventHandler; + loadMore(): Promise; +} + +export function createConversationStore(client: ChatClient, id: string, options?: { pageSize?: number }): ConversationStore; +export function createConversationListStore(client: ChatClient, options?: { pageSize?: number }): ConversationListStore; + +export function useChatClient(options: Omit): ChatClient; +export function useChatConversation( + client: ChatClient, + id: string, + options?: { pageSize?: number }, +): Omit & Omit & { typingUsers: string[] }; +export function useChatConversations( + client: ChatClient, + options?: { pageSize?: number }, +): Omit & ConversationListState; diff --git a/chat.js b/chat.js new file mode 100644 index 0000000..55f9941 --- /dev/null +++ b/chat.js @@ -0,0 +1,573 @@ +// The Hibira Chat API for React Native and Expo: a client for the user +// routes (/apps/{appId}/chat/me), live chat.* events from a pusher-js +// client signed in as the user (pusher.signin()), and stores and hooks that +// keep one conversation, or the user's conversation list, up to date. + +import { useEffect, useMemo, useRef, useSyncExternalStore } from 'react'; +import { usePusher } from '@hibira-io/react'; + +export const DEFAULT_CHAT_HOST = 'api.hibira.io'; + +/** Chat API events, sent to each member's user channel. */ +export const CHAT_EVENTS = Object.freeze([ + 'chat.message', + 'chat.message_updated', + 'chat.typing', + 'chat.read', + 'chat.conversation', + 'chat.left', + 'chat.deleted', +]); + +/** How long a typing indicator shows without another chat.typing. */ +export const TYPING_SHOW_MS = 8_000; + +function base64Decode(s) { + if (typeof atob === 'function') return atob(s); + return globalThis.Buffer.from(s, 'base64').toString('binary'); +} + +function claims(token) { + try { + const part = String(token).split('.')[1].replace(/-/g, '+').replace(/_/g, '/'); + const bin = base64Decode(part.padEnd(part.length + ((4 - (part.length % 4)) % 4), '=')); + const json = decodeURIComponent( + Array.from(bin, (c) => '%' + c.charCodeAt(0).toString(16).padStart(2, '0')).join(''), + ); + return JSON.parse(json) ?? {}; + } catch { + return {}; + } +} + +/** The user ID (sub) inside a user token, or '' when it cannot be read. */ +export const tokenUser = (token) => String(claims(token).sub ?? ''); + +/** An error answered by the Chat API, with its HTTP status (0: no answer). */ +export class ChatApiError extends Error { + constructor(status, message) { + super(message || `Chat API request failed (${status})`); + this.name = 'ChatApiError'; + this.status = status; + } +} + +/** The text to show a reader of `lang`: its translation, else the text. */ +export function messageText(message, lang) { + if (!message) return ''; + return (lang && message.translations?.[lang]) || message.text || ''; +} + +/** + * The Chat API as the signed-in user. + * + * options: + * appId the Hibira app ID (required) + * token the user token, or a function returning one (or a promise), + * called again before it expires and after a 401 + * tokenUrl instead of token: a URL on your server that answers {token} + * pusher a pusher-js client signed in as the user, for live events + * host the HTTP API host (default api.hibira.io); may include http:// + * fetch a fetch implementation (default globalThis.fetch) + */ +export function createChatClient(options = {}) { + if (!options.appId) throw new TypeError('createChatClient: appId is required'); + if (!options.token && !options.tokenUrl) throw new TypeError('createChatClient: token or tokenUrl is required'); + const doFetch = options.fetch ?? ((...a) => globalThis.fetch(...a)); + let host = String(options.host ?? DEFAULT_CHAT_HOST); + while (host.endsWith('/')) host = host.slice(0, -1); + const base = `${/^https?:\/\//.test(host) ? host : `https://${host}`}/apps/${encodeURIComponent(options.appId)}/chat/me`; + let token = typeof options.token === 'string' ? options.token : null; + let pending = null; + const listeners = new Set(); + const liveListeners = new Set(); + let detach = () => {}; + + async function fetchToken() { + if (typeof options.token === 'string') return options.token; + if (typeof options.token === 'function') return options.token(); + const res = await doFetch(options.tokenUrl, { credentials: 'include', headers: { Accept: 'application/json' } }); + if (!res.ok) throw new ChatApiError(res.status, `token endpoint answered ${res.status}`); + return (await res.json()).token; + } + + function currentToken(force) { + const exp = token ? claims(token).exp ?? 0 : 0; + if (!force && token && (exp === 0 || exp - Date.now() / 1000 > 30)) return Promise.resolve(token); + pending ??= Promise.resolve(fetchToken()) + .then((t) => (token = t)) + .finally(() => (pending = null)); + return pending; + } + + async function call(method, path, { body, query, signal } = {}) { + const params = Object.entries(query ?? {}).filter(([, v]) => v !== undefined && v !== null && v !== ''); + const qs = params.map(([k, v]) => `${encodeURIComponent(k)}=${encodeURIComponent(String(v))}`).join('&'); + const url = base + path + (qs ? `?${qs}` : ''); + for (let attempt = 0; ; attempt++) { + const t = await currentToken(attempt > 0); + let res; + try { + res = await doFetch(url, { + method, + signal, + headers: { + Authorization: `Bearer ${t}`, + Accept: 'application/json', + ...(body !== undefined ? { 'Content-Type': 'application/json' } : {}), + }, + body: body !== undefined ? JSON.stringify(body) : undefined, + }); + } catch (err) { + if (err?.name === 'AbortError') throw err; + throw new ChatApiError(0, err?.message); + } + if (res.status === 401 && attempt === 0 && typeof options.token !== 'string') continue; + const data = await res.json().catch(() => ({})); + if (!res.ok) throw new ChatApiError(res.status, data?.error); + return data; + } + } + + const conv = (id) => `/conversations/${encodeURIComponent(id)}`; + + const client = { + /** The token's user, once a token is known ('' before). */ + user: () => (token ? tokenUser(token) : ''), + /** Fetches the token if needed and returns its user. */ + currentUser: () => currentToken(false).then(tokenUser), + conversations: ({ limit, before, signal } = {}) => call('GET', '/conversations', { query: { limit, before }, signal }), + conversation: (id, { signal } = {}) => call('GET', conv(id), { signal }).then((d) => d.conversation), + messages: (id, { after, last, limit, signal } = {}) => + call('GET', `${conv(id)}/messages`, { query: { after, last, limit }, signal }), + search: (id, q, { before, limit, signal } = {}) => call('GET', `${conv(id)}/search`, { query: { q, before, limit }, signal }), + send: (id, message) => call('POST', `${conv(id)}/messages`, { body: typeof message === 'string' ? { text: message } : message }), + edit: (id, seq, change) => + call('PUT', `${conv(id)}/messages/${seq}`, { body: typeof change === 'string' ? { text: change } : change }).then((d) => d.message), + remove: (id, seq) => call('DELETE', `${conv(id)}/messages/${seq}`).then((d) => d.message), + react: (id, seq, emoji, on = true) => + (on + ? call('POST', `${conv(id)}/messages/${seq}/reactions`, { body: { emoji } }) + : call('DELETE', `${conv(id)}/messages/${seq}/reactions`, { query: { emoji } }) + ).then((d) => d.message), + report: (id, seq, reason) => call('POST', `${conv(id)}/messages/${seq}/reports`, { body: { reason } }).then((d) => d.report), + read: (id, seq) => call('POST', `${conv(id)}/read`, { body: { seq } }), + typing: (id, typing = true) => call('POST', `${conv(id)}/typing`, { body: { typing } }), + /** Translates one message into a BCP 47 language and keeps it on the message. */ + translate: (id, seq, language) => + call('POST', `${conv(id)}/messages/${seq}/translations`, { body: { language } }).then((d) => d.message), + /** The user's settings: {user_id, language}. */ + me: () => call('GET', '/'), + /** Sets the language messages are translated into for this user (null for none). */ + setLanguage: (language) => call('PUT', '/', { body: { language: language ?? null } }), + /** + * Uploads a file straight to storage (up to 25 MB): `file` is a Blob, or + * { uri, name, type, size } from an image or document picker. Send the + * result in a message's attachments. + */ + async upload(id, file, { name, type, size } = {}) { + const fileName = name ?? file?.name ?? 'file'; + const contentType = type ?? file?.type ?? 'application/octet-stream'; + let body = file; + if (file && typeof file.uri === 'string' && !(typeof Blob !== 'undefined' && file instanceof Blob)) { + body = await (await doFetch(file.uri)).blob(); + } + const bytes = size ?? file?.size ?? body?.size; + const { attachment, upload } = await call('POST', `${conv(id)}/attachments`, { + body: { name: fileName, content_type: contentType, size: bytes }, + }); + const res = await doFetch(upload.url, { method: upload.method ?? 'PUT', headers: upload.headers ?? {}, body }); + if (!res.ok) throw new ChatApiError(res.status, 'Upload failed'); + return attachment; + }, + + /** Calls handler(event, data) for each chat event; returns unsubscribe. */ + on(handler) { + listeners.add(handler); + return () => listeners.delete(handler); + }, + /** Calls handler() each time the realtime connection is (back) up. */ + onLive(handler) { + liveListeners.add(handler); + return () => liveListeners.delete(handler); + }, + /** Feeds an event from the user's channel; returns true for chat events. */ + handleEvent(event, data) { + if (!CHAT_EVENTS.includes(event)) return false; + let d = data; + if (typeof d === 'string') { + try { + d = JSON.parse(d); + } catch { + return false; + } + } + if (!d || typeof d !== 'object') return false; + const id = event === 'chat.conversation' ? d.conversation?.id : d.conversation_id; + if (!id) return false; + listeners.forEach((fn) => fn(event, d)); + return true; + }, + notifyLive() { + liveListeners.forEach((fn) => fn()); + }, + /** Takes live events from a pusher-js client signed in as the user. */ + attach(pusher) { + detach(); + detach = () => {}; + const user = pusher?.user; + if (!user?.bind) return () => {}; + const fns = CHAT_EVENTS.map((e) => { + const fn = (data) => client.handleEvent(e, data); + user.bind(e, fn); + return [e, fn]; + }); + const state = ({ current } = {}) => current === 'connected' && client.notifyLive(); + pusher.connection?.bind?.('state_change', state); + detach = () => { + fns.forEach(([e, fn]) => user.unbind?.(e, fn)); + pusher.connection?.unbind?.('state_change', state); + }; + return detach; + }, + }; + if (options.pusher) client.attach(options.pusher); + return client; +} + +function mergeMessages(list, page) { + if (!page?.length) return list; + const bySeq = new Map(list.map((m) => [m.seq, m])); + for (const m of page) if (m && typeof m.seq === 'number') bySeq.set(m.seq, m); + return [...bySeq.values()].sort((a, b) => a.seq - b.seq); +} + +const lastSeq = (list) => (list.length ? list[list.length - 1].seq : 0); + +/** + * One conversation kept up to date: the newest page of messages, older + * pages on demand, live messages, edits, reactions, typing and read + * receipts, and a catch-up read each time the connection comes back. + */ +export function createConversationStore(client, id, { pageSize = 50 } = {}) { + let state = { + conversation: null, + messages: [], + loading: true, + loadingOlder: false, + hasOlder: false, + typing: [], + reads: {}, + closed: false, + error: null, + }; + const subscribers = new Set(); + const typingTimers = new Map(); + let floor = -1; + let inflight = null; + let again = false; + let unsubs = []; + let typingSentAt = 0; + let typingOff = null; + + const set = (patch) => { + state = { ...state, ...patch }; + subscribers.forEach((fn) => fn()); + }; + const addMessages = (page) => set({ messages: mergeMessages(state.messages, page) }); + const setRead = (user, seq) => { + if (user && seq > (state.reads[user] ?? 0)) set({ reads: { ...state.reads, [user]: seq } }); + }; + const clearTyping = (user) => { + clearTimeout(typingTimers.get(user)); + typingTimers.delete(user); + if (state.typing.includes(user)) set({ typing: state.typing.filter((u) => u !== user) }); + }; + + async function load() { + try { + if (!state.conversation || !state.messages.length) { + const c = await client.conversation(id); + const reads = { ...state.reads }; + for (const m of c.members ?? []) reads[m.user_id] = Math.max(m.read_seq ?? 0, reads[m.user_id] ?? 0); + set({ conversation: c, reads }); + } + let after = lastSeq(state.messages); + while (after > 0) { + const page = await client.messages(id, { after, limit: 200 }); + addMessages(page.messages); + if ((page.messages?.length ?? 0) < 200) break; + after = page.messages[page.messages.length - 1].seq; + } + const count = Math.min(200, Math.max(pageSize, state.messages.length)); + const page = await client.messages(id, { last: count }); + if (floor < 0) floor = page.messages?.length ? page.messages[0].seq : (page.last_seq ?? 0) + 1; + set({ messages: mergeMessages(state.messages, page.messages), loading: false, hasOlder: floor > 1, error: null }); + } catch (err) { + set({ loading: false, error: err, ...(err?.status === 404 ? { closed: true } : {}) }); + } + } + + function refresh() { + if (inflight) { + again = true; + return inflight; + } + inflight = (async () => { + do { + again = false; + await load(); + } while (again); + })().finally(() => (inflight = null)); + return inflight; + } + + function apply(event, d) { + if ((event === 'chat.conversation' ? d.conversation?.id : d.conversation_id) !== id) return; + switch (event) { + case 'chat.message': + clearTyping(d.message?.sender); + setRead(d.message?.sender, d.message?.seq); + addMessages([d.message]); + break; + case 'chat.message_updated': + if (state.messages.some((m) => m.seq === d.message?.seq)) addMessages([d.message]); + break; + case 'chat.typing': + if (d.user_id === client.user()) return; + if (d.typing !== false) { + clearTimeout(typingTimers.get(d.user_id)); + typingTimers.set(d.user_id, setTimeout(() => clearTyping(d.user_id), TYPING_SHOW_MS)); + if (!state.typing.includes(d.user_id)) set({ typing: [...state.typing, d.user_id] }); + } else { + clearTyping(d.user_id); + } + break; + case 'chat.read': + setRead(d.user_id, d.read_seq); + break; + case 'chat.conversation': { + const reads = { ...state.reads }; + for (const m of d.conversation.members ?? []) reads[m.user_id] = Math.max(m.read_seq ?? 0, reads[m.user_id] ?? 0); + set({ conversation: d.conversation, reads }); + break; + } + default: + set({ closed: true }); + } + } + + async function stopTyping() { + clearTimeout(typingOff); + if (!typingSentAt) return; + typingSentAt = 0; + await client.typing(id, false).catch(() => {}); + } + + async function keep(promise) { + const m = await promise; + addMessages([m]); + return m; + } + + return { + get: () => state, + subscribe(fn) { + subscribers.add(fn); + return () => subscribers.delete(fn); + }, + start() { + if (unsubs.length) return; + unsubs = [client.on(apply), client.onLive(() => refresh())]; + refresh(); + }, + stop() { + unsubs.forEach((fn) => fn()); + unsubs = []; + typingTimers.forEach((t) => clearTimeout(t)); + typingTimers.clear(); + clearTimeout(typingOff); + }, + refresh, + apply, + /** Loads the page of messages before the oldest one loaded. */ + async loadOlder() { + if (floor <= 1 || state.loadingOlder) return; + set({ loadingOlder: true }); + try { + const after = Math.max(0, floor - 1 - pageSize); + const page = await client.messages(id, { after, limit: floor - 1 - after }); + floor = after + 1; + set({ messages: mergeMessages(state.messages, page.messages), loadingOlder: false, hasOlder: floor > 1 }); + } catch (err) { + set({ loadingOlder: false, error: err }); + } + }, + /** Sends a message (text, or {text, metadata, attachments}) and adds the stored copy. */ + async send(message) { + await stopTyping(); + const out = await client.send(id, message); + addMessages([out.message]); + return out.message; + }, + edit: (seq, change) => keep(client.edit(id, seq, change)), + remove: (seq) => keep(client.remove(id, seq)), + translate: (seq, language) => keep(client.translate(id, seq, language)), + /** Adds the user's reaction, or takes it back if they already reacted. */ + async toggleReaction(seq, emoji) { + const me = await client.currentUser(); + const mine = state.messages.find((m) => m.seq === seq)?.reactions?.[emoji]?.includes(me) ?? false; + return keep(client.react(id, seq, emoji, !mine)); + }, + /** Marks everything loaded as read, when it is not already. */ + async markRead() { + const seq = lastSeq(state.messages); + const me = await client.currentUser(); + if (!seq || (state.reads[me] ?? 0) >= seq) return; + const { read_seq: readSeq = seq } = await client.read(id, seq); + setRead(me, readSeq); + }, + /** Call on every keystroke: says "typing" at most every 3 s, and stops after 5 s idle. */ + typing() { + const now = Date.now(); + if (now - typingSentAt > 3000) { + typingSentAt = now; + client.typing(id, true).catch(() => {}); + } + clearTimeout(typingOff); + typingOff = setTimeout(() => void stopTyping(), 5000); + }, + stopTyping, + /** Members other than the user who have read message seq. */ + readBy: (seq) => Object.entries(state.reads).filter(([u, s]) => u !== client.user() && s >= seq).map(([u]) => u), + }; +} + +/** + * The user's conversations kept up to date: new messages move one to the + * top and count as unread, reads clear the count, and conversations come + * and go as the user joins, leaves or they are deleted. + */ +export function createConversationListStore(client, { pageSize = 30 } = {}) { + let state = { conversations: [], loading: true, loadingMore: false, hasMore: false, unread: 0, error: null }; + const subscribers = new Set(); + let next = ''; + let unsubs = []; + + const set = (patch) => { + const s = { ...state, ...patch }; + s.unread = s.conversations.reduce((n, c) => n + (c.unread ?? 0), 0); + s.hasMore = !!next; + state = s; + subscribers.forEach((fn) => fn()); + }; + + async function refresh() { + try { + const page = await client.conversations({ limit: pageSize }); + next = page.next ?? ''; + set({ conversations: page.conversations ?? [], loading: false, error: null }); + } catch (err) { + set({ loading: false, error: err }); + } + } + + function apply(event, d) { + const me = client.user(); + const list = state.conversations; + if (event === 'chat.message') { + const c = list.find((x) => x.id === d.conversation_id); + if (!c) return void refresh(); + const m = d.message ?? {}; + const unread = m.sender === me ? 0 : (c.unread ?? 0) + (m.kind === 'system' ? 0 : 1); + const moved = { ...c, last_seq: Math.max(c.last_seq ?? 0, m.seq ?? 0), updated_at: m.created_at ?? c.updated_at, unread }; + set({ conversations: [moved, ...list.filter((x) => x.id !== c.id)] }); + } else if (event === 'chat.read') { + if (d.user_id !== me) return; + set({ + conversations: list.map((c) => (c.id === d.conversation_id && d.read_seq >= (c.last_seq ?? 0) ? { ...c, unread: 0 } : c)), + }); + } else if (event === 'chat.conversation') { + const old = list.find((x) => x.id === d.conversation.id); + const updated = { ...d.conversation, unread: old?.unread ?? 0 }; + set({ conversations: old ? list.map((c) => (c.id === updated.id ? updated : c)) : [updated, ...list] }); + } else if (event === 'chat.left' || event === 'chat.deleted') { + set({ conversations: list.filter((c) => c.id !== d.conversation_id) }); + } + } + + return { + get: () => state, + subscribe(fn) { + subscribers.add(fn); + return () => subscribers.delete(fn); + }, + start() { + if (unsubs.length) return; + unsubs = [client.on(apply), client.onLive(() => refresh())]; + refresh(); + }, + stop() { + unsubs.forEach((fn) => fn()); + unsubs = []; + }, + refresh, + apply, + /** Loads the next page, if there is one. */ + async loadMore() { + if (!next || state.loadingMore) return; + set({ loadingMore: true }); + try { + const page = await client.conversations({ limit: pageSize, before: next }); + next = page.next ?? ''; + const have = new Set(state.conversations.map((c) => c.id)); + set({ conversations: [...state.conversations, ...(page.conversations ?? []).filter((c) => !have.has(c.id))], loadingMore: false }); + } catch (err) { + set({ loadingMore: false, error: err }); + } + }, + }; +} + +/** + * A chat client for the components inside , taking live + * events from its connection (sign the user in with pusher.signin()). + * Pass the same options as createChatClient(), without pusher. + */ +export function useChatClient(options) { + const pusher = usePusher(); + const ref = useRef(options); + ref.current = options; + const client = useMemo( + () => + createChatClient({ + ...ref.current, + token: typeof ref.current.token === 'function' ? () => ref.current.token() : ref.current.token, + }), + [options.appId, options.host, typeof options.token === 'string' ? options.token : null, options.tokenUrl], + ); + useEffect(() => (pusher ? client.attach(pusher) : undefined), [client, pusher]); + return client; +} + +function useStore(store) { + useEffect(() => { + store.start(); + return () => store.stop(); + }, [store]); + const state = useSyncExternalStore(store.subscribe, store.get, store.get); + return { ...store, ...state }; +} + +/** One conversation, live: { messages, typingUsers, reads, hasOlder, loadOlder, send, markRead, typing(), ... }. */ +export function useChatConversation(client, id, { pageSize = 50 } = {}) { + const store = useMemo(() => createConversationStore(client, id, { pageSize }), [client, id, pageSize]); + const live = useStore(store); + return { ...live, typingUsers: live.typing, typing: store.typing }; +} + +/** The user's conversations, live: { conversations, unread, loadMore, refresh, ... }. */ +export function useChatConversations(client, { pageSize = 30 } = {}) { + const store = useMemo(() => createConversationListStore(client, { pageSize }), [client, pageSize]); + return useStore(store); +} diff --git a/package-lock.json b/package-lock.json index 146da88..b4877a8 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "@hibira-io/react-native", - "version": "0.1.1", + "version": "0.2.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "@hibira-io/react-native", - "version": "0.1.1", + "version": "0.2.0", "license": "MIT", "dependencies": { "@hibira-io/react": "^0.1.1" diff --git a/package.json b/package.json index 1522b2b..26e7111 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "name": "@hibira-io/react-native", - "version": "0.1.1", - "description": "React Native and Expo hooks for Hibira and other Pusher-compatible servers: channels, events, presence, LLM streams, chunked payloads that fit 4 KB messages, and push notifications through Hibira Push", + "version": "0.2.0", + "description": "React Native and Expo hooks for Hibira and other Pusher-compatible servers: channels, events, presence, LLM streams, chunked payloads that fit 4 KB messages, push notifications through Hibira Push, and the Hibira Chat API", "keywords": [ "react-native", "expo", @@ -14,6 +14,9 @@ "push notifications", "expo-notifications", "beams", + "chat", + "chat-api", + "messaging", "hibira" ], "homepage": "https://hibira.io", @@ -51,6 +54,10 @@ "types": "./chunk.d.ts", "default": "./chunk.js" }, + "./chat": { + "types": "./chat.d.ts", + "default": "./chat.js" + }, "./package.json": "./package.json" }, "files": [ diff --git a/test/chat.test.mjs b/test/chat.test.mjs new file mode 100644 index 0000000..696ddca --- /dev/null +++ b/test/chat.test.mjs @@ -0,0 +1,185 @@ +import { test } from 'node:test'; +import assert from 'node:assert/strict'; +import * as React from 'react'; +import TestRenderer from 'react-test-renderer'; +import { + createChatClient, + createConversationListStore, + createConversationStore, + messageText, + tokenUser, + useChatConversation, + ChatApiError, +} from '../chat.js'; +import { fakePusher } from './fake-pusher.mjs'; + +const { act, createElement: h } = React; +globalThis.IS_REACT_ACT_ENVIRONMENT = true; + +const b64 = (s) => Buffer.from(s).toString('base64url'); +const jwt = (sub) => `${b64('{"alg":"HS256"}')}.${b64(JSON.stringify({ sub, exp: Math.floor(Date.now() / 1000) + 3600 }))}.sig`; +const msg = (seq, sender = 'bob', text = `m${seq}`) => ({ id: `id${seq}`, seq, sender, kind: 'text', text, created_at: `t${seq}` }); +const range = (a, b) => Array.from({ length: b - a + 1 }, (_, i) => a + i); + +function fakeFetch(route) { + const calls = []; + const fn = async (url, init = {}) => { + const u = new URL(url); + const path = u.pathname.replace('/apps/a/chat/me', '') + u.search; + calls.push({ method: init.method ?? 'GET', path, body: init.body ? JSON.parse(init.body) : undefined, headers: init.headers }); + const [status, body] = route(init.method ?? 'GET', path) ?? [404, { error: 'not found' }]; + return { ok: status < 400, status, json: async () => body }; + }; + fn.calls = calls; + return fn; +} + +test('reads the user from a token, and the text for a language', () => { + assert.equal(tokenUser(jwt('ann')), 'ann'); + assert.equal(tokenUser('nope'), ''); + const m = { text: 'hi', translations: { ja: 'やあ' } }; + assert.equal(messageText(m, 'ja'), 'やあ'); + assert.equal(messageText(m, 'ko'), 'hi'); +}); + +test('calls the user routes and refreshes the token after a 401', async () => { + let n = 0; + let tokens = 0; + const fetch = fakeFetch((method, path) => { + n++; + if (n === 1) return [401, { error: 'expired' }]; + if (path === '/conversations/trip%201/messages') return [201, { message: msg(4, 'ann', 'hi'), push: { users: 1 } }]; + if (path === '/') return [200, { user_id: 'ann', language: 'ja' }]; + if (path === '/conversations/c/typing') return [403, { error: 'you are muted' }]; + if (path === '/conversations/c/messages/3/translations') return [200, { message: { seq: 3, text: 'hi', translations: { ja: 'やあ' } } }]; + }); + const client = createChatClient({ appId: 'a', token: () => (tokens++, jwt('ann')), fetch }); + const out = await client.send('trip 1', { text: 'hi', metadata: { reply_to: 2 } }); + assert.equal(out.message.seq, 4); + assert.equal(tokens, 2); + assert.equal(client.user(), 'ann'); + assert.deepEqual(fetch.calls[1].body, { text: 'hi', metadata: { reply_to: 2 } }); + assert.match(fetch.calls[1].headers.Authorization, /^Bearer ey/); + assert.deepEqual(await client.setLanguage('ja'), { user_id: 'ann', language: 'ja' }); + assert.equal(fetch.calls[2].method, 'PUT'); + assert.equal((await client.translate('c', 3, 'ja')).translations.ja, 'やあ'); + await assert.rejects(client.typing('c'), (e) => e instanceof ChatApiError && e.status === 403 && e.message === 'you are muted'); +}); + +test('takes events from a signed-in pusher-js client', async () => { + const pusher = fakePusher(); + const userHandlers = new Map(); + pusher.user = { + bind: (e, fn) => userHandlers.set(e, fn), + unbind: (e) => userHandlers.delete(e), + }; + const client = createChatClient({ appId: 'a', token: jwt('ann'), pusher, fetch: fakeFetch(() => undefined) }); + const got = []; + let lives = 0; + client.on((e, d) => got.push([e, d.user_id])); + client.onLive(() => lives++); + userHandlers.get('chat.typing')({ conversation_id: 'c', user_id: 'bob', typing: true }); + pusher.setState('connected'); + assert.deepEqual(got, [['chat.typing', 'bob']]); + assert.equal(lives, 1); + assert.equal(client.handleEvent('other', {}), false); + assert.equal(client.handleEvent('chat.left', '{}'), false); +}); + +function conversationFetch() { + return fakeFetch((method, path) => { + if (path === '/conversations/c') + return [200, { conversation: { id: 'c', members: [{ user_id: 'ann', read_seq: 3 }, { user_id: 'bob', read_seq: 5 }], last_seq: 120 } }]; + if (path === '/conversations/c/messages?last=50') return [200, { messages: range(71, 120).map((s) => msg(s)), last_seq: 120 }]; + if (path === '/conversations/c/messages?after=20&limit=50') return [200, { messages: range(21, 70).map((s) => msg(s)), last_seq: 120 }]; + if (path === '/conversations/c/messages?after=0&limit=20') return [200, { messages: range(1, 20).map((s) => msg(s)), last_seq: 120 }]; + if (path.startsWith('/conversations/c/messages?after=121')) return [200, { messages: [msg(121)], last_seq: 121 }]; + if (path.startsWith('/conversations/c/messages?last=')) return [200, { messages: [msg(120, 'bob', 'edited'), msg(121)], last_seq: 121 }]; + if (path === '/conversations/c/read') return [200, { read_seq: 121 }]; + if (path === '/conversations/c/messages' && method === 'POST') return [201, { message: msg(122, 'ann', 'hello') }]; + }); +} + +test('a conversation store pages, applies events and catches up', async () => { + const fetch = conversationFetch(); + const client = createChatClient({ appId: 'a', token: jwt('ann'), fetch }); + const c = createConversationStore(client, 'c'); + await c.refresh(); + assert.equal(c.get().messages.length, 50); + assert.equal(c.get().hasOlder, true); + assert.equal(c.get().reads.bob, 5); + await c.loadOlder(); + await c.loadOlder(); + assert.deepEqual(c.get().messages.map((m) => m.seq), range(1, 120)); + assert.equal(c.get().hasOlder, false); + + c.start(); + await c.refresh(); + client.handleEvent('chat.typing', { conversation_id: 'c', user_id: 'bob', typing: true }); + assert.deepEqual(c.get().typing, ['bob']); + client.handleEvent('chat.message', { conversation_id: 'c', message: msg(121) }); + assert.equal(c.get().messages.at(-1).seq, 121); + assert.deepEqual(c.get().typing, []); + client.handleEvent('chat.message', { conversation_id: 'x', message: msg(500) }); + client.handleEvent('chat.read', { conversation_id: 'c', user_id: 'bob', read_seq: 121 }); + assert.deepEqual(c.readBy(121), ['bob']); + + client.notifyLive(); + await c.refresh(); + assert.equal(c.get().messages.find((m) => m.seq === 120).text, 'edited'); + assert.ok(fetch.calls.some((x) => x.path.startsWith('/conversations/c/messages?after=121'))); + await c.markRead(); + assert.equal(c.get().reads.ann, 121); + assert.equal((await c.send('hello')).seq, 122); + assert.equal(c.get().messages.at(-1).seq, 122); + client.handleEvent('chat.left', { conversation_id: 'c' }); + assert.equal(c.get().closed, true); + c.stop(); +}); + +test('the list store moves conversations and counts unread', async () => { + const client = createChatClient({ + appId: 'a', + token: jwt('ann'), + fetch: fakeFetch(() => [200, { conversations: [{ id: 'a', last_seq: 3, unread: 0 }, { id: 'b', last_seq: 9, unread: 2 }], next: '' }]), + }); + const l = createConversationListStore(client); + l.start(); + await l.refresh(); + assert.deepEqual(l.get().conversations.map((c) => c.id), ['a', 'b']); + client.handleEvent('chat.message', { conversation_id: 'b', message: msg(10) }); + assert.deepEqual(l.get().conversations.map((c) => c.id), ['b', 'a']); + assert.equal(l.get().unread, 3); + client.handleEvent('chat.read', { conversation_id: 'b', user_id: 'ann', read_seq: 10 }); + assert.equal(l.get().unread, 0); + client.handleEvent('chat.deleted', { conversation_id: 'a' }); + assert.deepEqual(l.get().conversations.map((c) => c.id), ['b']); + l.stop(); +}); + +test('useChatConversation renders the live conversation', async () => { + const client = createChatClient({ appId: 'a', token: jwt('ann'), fetch: conversationFetch() }); + const out = {}; + function Probe() { + out.value = useChatConversation(client, 'c'); + return null; + } + let r; + await act(async () => { + r = TestRenderer.create(h(Probe)); + }); + await act(async () => { + await new Promise((res) => setTimeout(res, 20)); + }); + assert.equal(out.value.messages.length, 50); + assert.equal(typeof out.value.typing, 'function'); + await act(async () => { + client.handleEvent('chat.typing', { conversation_id: 'c', user_id: 'bob', typing: true }); + }); + assert.deepEqual(out.value.typingUsers, ['bob']); + await act(async () => { + await out.value.loadOlder(); + }); + assert.equal(out.value.messages.length, 100); + await act(async () => r.unmount()); +}); diff --git a/test/types.test.tsx b/test/types.test.tsx index 9baf8fe..52045ec 100644 --- a/test/types.test.tsx +++ b/test/types.test.tsx @@ -46,3 +46,27 @@ async function server(pusher: { trigger(c: string, e: string, d: any, p?: { sock return n + s + RegistrationState.PERMISSION_DENIED + chunkPayload({}).length + createChunkAssembler().pending; } void server; + +import { + createChatClient, + messageText, + useChatClient, + useChatConversation, + useChatConversations, + type ChatMessage, +} from '@hibira-io/react-native/chat'; + +const chat = createChatClient({ appId: 'a', token: async () => 'jwt' }); +chat.on((event, data) => event + data); + +function ChatScreen() { + const client = useChatClient({ appId: 'a', tokenUrl: 'https://app/chat-token' }); + const room = useChatConversation(client, 'trip-1'); + const list = useChatConversations(chat); + const first: ChatMessage | undefined = room.messages[0]; + room.typing(); + void room.send({ text: 'hi', metadata: { reply_to: 1 } }); + void room.loadOlder(); + return [messageText(first, 'ja'), room.typingUsers.join(','), list.unread.toFixed(), room.hasOlder]; +} +void ChatScreen; diff --git a/version.js b/version.js index bd4cc7e..e1ba5d7 100644 --- a/version.js +++ b/version.js @@ -1 +1 @@ -export const SDK_VERSION = '0.1.1'; +export const SDK_VERSION = '0.2.0';