Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -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
Expand Down
60 changes: 60 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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';

<HibiraProvider appKey="YOUR_APP_KEY" options={{ userAuthentication: { endpoint: 'https://api.example.com/pusher/user-auth' } }}>
<Chat />
</HibiraProvider>;

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 (
<FlatList
data={room.messages}
keyExtractor={(m) => String(m.seq)}
renderItem={({ item }) => <Text>{item.deleted_at ? 'Message deleted' : messageText(item, myLanguage)}</Text>}
onStartReached={room.loadOlder}
onViewableItemsChanged={() => room.markRead()}
ListFooterComponent={room.typingUsers.length ? <Text>{room.typingUsers.join(', ')} typing…</Text> : 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
Expand Down
194 changes: 194 additions & 0 deletions chat.d.ts
Original file line number Diff line number Diff line change
@@ -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<string, unknown>;
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<string, unknown>;
created_at: string;
edited_at?: string;
deleted_at?: string;
/** Each emoji and the members who reacted, in order. */
reactions?: Record<string, string[]>;
attachments?: ChatAttachment[];
visible_to?: string[];
/** The language text was written in. */
language?: string;
/** The text translated, by BCP 47 language tag. */
translations?: Record<string, string>;
}

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<string, unknown>;
attachments?: Pick<ChatAttachment, 'id' | 'name' | 'content_type'>[];
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<string>);
/** 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<string>;
conversations(options?: { limit?: number; before?: string } & Opts): Promise<{ conversations: ChatConversation[]; next: string }>;
conversation(id: string, options?: Opts): Promise<ChatConversation>;
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<string, unknown> }): Promise<ChatMessage>;
remove(id: string, seq: number): Promise<ChatMessage>;
react(id: string, seq: number, emoji: string, on?: boolean): Promise<ChatMessage>;
report(id: string, seq: number, reason?: string): Promise<ChatReport>;
read(id: string, seq: number): Promise<{ read_seq: number }>;
typing(id: string, typing?: boolean): Promise<unknown>;
translate(id: string, seq: number, language: string): Promise<ChatMessage>;
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<ChatAttachment>;
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<string, number>;
/** 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<void>;
apply: ChatEventHandler;
loadOlder(): Promise<void>;
send(message: string | SendInput): Promise<ChatMessage>;
edit(seq: number, change: string | { text?: string; metadata?: Record<string, unknown> }): Promise<ChatMessage>;
remove(seq: number): Promise<ChatMessage>;
translate(seq: number, language: string): Promise<ChatMessage>;
toggleReaction(seq: number, emoji: string): Promise<ChatMessage>;
markRead(): Promise<void>;
/** Call on every keystroke. */
typing(): void;
stopTyping(): Promise<void>;
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<void>;
apply: ChatEventHandler;
loadMore(): Promise<void>;
}

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<ChatClientOptions, 'pusher'>): ChatClient;
export function useChatConversation(
client: ChatClient,
id: string,
options?: { pageSize?: number },
): Omit<ConversationStore, 'get' | 'subscribe' | 'start' | 'stop'> & Omit<ConversationState, 'typing'> & { typingUsers: string[] };
export function useChatConversations(
client: ChatClient,
options?: { pageSize?: number },
): Omit<ConversationListStore, 'get' | 'subscribe' | 'start' | 'stop'> & ConversationListState;
Loading
Loading