@lynkoria/react 0.1.2 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,22 @@
1
1
  # @lynkoria/react
2
2
 
3
+ ## 0.2.0
4
+
5
+ ### Minor Changes
6
+
7
+ - General-purpose messaging primitives. Conversations gain `description`, product `metadata`, `visibility` (`private` | `public`) and a read-only archive state; members gain `owner` | `admin` | `member` | `viewer` roles (viewers are read-only) and a per-user `notificationLevel`. Messages carry `mentions` (validated against current members), pins with sequenced `message.pinned`/`message.unpinned` events, one-level `thread` summaries, and events report their `actorId`. Conversation views include member counts, dm members and the caller's role, `unreadCount` and `mentionCount`.
8
+
9
+ - `@lynkoria/client`: `conversations.get`, `conversations.members`, `conversations.list({ scope: 'public', query })`, `conversations.setNotificationLevel`, `messages.get`, `messages.pin`/`unpin`/`pins`, `messages.search`, mentions on `send`/`edit`, and `history` filters (`threadId`, `topLevel`, `withAttachments`).
10
+ - `@lynkoria/server`: `conversations.get`/`update`/`members`/`setRole`, `addMembers(..., { role })`, `sessions.revoke`, `users.setPresence`, `users.removeFromTenant`, and an auto-batching, idempotent `import` API (`messages`, `readPositions`, `attachment`) for keys with the new `messaging:import` scope.
11
+ - `@lynkoria/react`: `useConversation(id, { threadId | topLevel })` keeps thread summaries current and shares ordering state between views; `send` accepts mentions; new `useConversationList` hook with live unread and mention badges.
12
+ - Messaging tokens accept `scopes` (`presence`, `public_conversations`) so products can mint restricted guest tokens.
13
+
14
+ ### Patch Changes
15
+
16
+ - Updated dependencies
17
+ - Updated dependencies
18
+ - @lynkoria/client@0.3.0
19
+
3
20
  ## 0.1.2
4
21
 
5
22
  ### Patch Changes
package/README.md CHANGED
@@ -8,7 +8,13 @@ React hooks for Lynkoria messaging, presence, typing and calls, built on
8
8
  subscriptions; the UI stays yours.
9
9
 
10
10
  **[Documentation](https://lynkoria.com/docs/)** · [React SDK guide](https://lynkoria.com/docs/react-sdk/) ·
11
- [Next.js](https://lynkoria.com/docs/nextjs/) · [TanStack Start](https://lynkoria.com/docs/tanstack/)
11
+ [Getting started](https://lynkoria.com/docs/getting-started/) · [Next.js](https://lynkoria.com/docs/nextjs/) ·
12
+ [TanStack Start](https://lynkoria.com/docs/tanstack/)
13
+
14
+ **Before you start:** your backend needs a Lynkoria project and service key from the
15
+ [Lynkoria Console](https://console.lynkoria.com), and your app's origin must be listed in the environment's
16
+ allowed origins. [Getting started](https://lynkoria.com/docs/getting-started/) walks through the setup and a
17
+ first test.
12
18
 
13
19
  ## Install
14
20
 
@@ -50,15 +56,16 @@ function Chat({ conversationId }: { conversationId: string }) {
50
56
 
51
57
  ## Hooks
52
58
 
53
- | Hook | Returns |
54
- | --------------------------- | -------------------------------------------------------------------------------------------- |
55
- | `useLynkoria()` | The client from the provider |
56
- | `useConnectionState()` | `idle`, `connecting`, `connected`, `reconnecting` or `disconnected` |
57
- | `useConversation(id)` | `{ messages, loading, error, hasMore, loadOlder, send, markRead }`, ordered and deduplicated |
58
- | `usePresence(userId)` | Latest presence or `null` |
59
- | `useTyping(conversationId)` | User IDs currently typing |
60
- | `useCall()` | `{ session, state, error, join, leave }`; leaves on unmount |
61
- | `useCallParticipants(s)` | Live participants of a call session |
59
+ | Hook | Returns |
60
+ | ----------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------- |
61
+ | `useLynkoria()` | The client from the provider |
62
+ | `useConnectionState()` | `idle`, `connecting`, `connected`, `reconnecting` or `disconnected` |
63
+ | `useConversation(id, { threadId?, topLevel? })` | `{ messages, loading, error, hasMore, loadOlder, send, markRead }`, ordered and deduplicated; thread summaries stay current |
64
+ | `useConversationList()` | The user's conversations with live unread and mention badges |
65
+ | `usePresence(userId)` | Latest presence or `null` |
66
+ | `useTyping(conversationId)` | User IDs currently typing |
67
+ | `useCall()` | `{ session, state, error, join, leave }`; leaves on unmount |
68
+ | `useCallParticipants(s)` | Live participants of a call session |
62
69
 
63
70
  Render a call by passing `session.room` to `@livekit/components-react`. Details and edge cases are in the
64
71
  [React SDK guide](https://lynkoria.com/docs/react-sdk/).
package/dist/index.d.ts CHANGED
@@ -1,7 +1,11 @@
1
1
  import { ReactNode } from "react";
2
- import { CallConnectionState, CallParticipant, CallSession, ConnectionState, ConversationEvent, JoinCallOptions, LynkoriaClient, LynkoriaError, Message, Presence } from "@lynkoria/client";
3
- /** Pure merge of a conversation event into a seq-ordered message list (edits/deletes replace by id). */
4
- export declare function applyEvent(messages: readonly Message[], event: ConversationEvent): Message[];
2
+ import { CallConnectionState, CallParticipant, CallSession, ConnectionState, Conversation, ConversationEvent, JoinCallOptions, LynkoriaClient, LynkoriaError, Message, Presence } from "@lynkoria/client";
3
+ /**
4
+ * Pure merge of a conversation event into a seq-ordered message list (edits/deletes/pins replace
5
+ * by id). Messages rejected by `include` are not added, but replies still update their parent's
6
+ * thread summary.
7
+ */
8
+ export declare function applyEvent(messages: readonly Message[], event: ConversationEvent, include?: (m: Message) => boolean): Message[];
5
9
  export declare function mergeHistory(messages: readonly Message[], older: readonly Message[]): Message[];
6
10
  /**
7
11
  * Connects the client while mounted. Disconnecting is deferred by one task, so Strict Mode's
@@ -19,14 +23,42 @@ export type ConversationState = {
19
23
  error: LynkoriaError | null;
20
24
  hasMore: boolean;
21
25
  loadOlder: () => Promise<void>;
22
- send: (text: string, options?: {
23
- attachmentIds?: string[];
24
- parentMessageId?: string;
25
- }) => Promise<Message>;
26
+ send: (text: string, options?: SendOptions) => Promise<Message>;
26
27
  markRead: () => Promise<void>;
27
28
  };
29
+ export type SendOptions = {
30
+ attachmentIds?: string[];
31
+ parentMessageId?: string;
32
+ mentions?: string[];
33
+ /** Reuse when retrying the same logical message. */
34
+ clientMessageId?: string;
35
+ };
36
+ /**
37
+ * Which messages a conversation view shows. `threadId`: the replies of one message (fetch the root
38
+ * with `client.messages.get`). `topLevel`: the main timeline without thread replies; replies still
39
+ * keep their parent's `thread` summary current.
40
+ */
41
+ export type ConversationViewOptions = {
42
+ threadId?: string;
43
+ topLevel?: boolean;
44
+ };
28
45
  /** Live, ordered message list for one conversation: history + realtime events + gap resync. */
29
- export declare function useConversation(conversationId: string): ConversationState;
46
+ export declare function useConversation(conversationId: string, options?: ConversationViewOptions): ConversationState;
47
+ export type ConversationListState = {
48
+ conversations: Conversation[];
49
+ loading: boolean;
50
+ error: LynkoriaError | null;
51
+ hasMore: boolean;
52
+ loadMore: () => Promise<void>;
53
+ refresh: () => Promise<void>;
54
+ };
55
+ /**
56
+ * The user's conversations by recent activity with unread and mention badges, kept current: new
57
+ * messages, reads, membership and metadata changes and reconnects refresh the loaded pages.
58
+ */
59
+ export declare function useConversationList(options?: {
60
+ pageSize?: number;
61
+ }): ConversationListState;
30
62
  export declare function usePresence(userId: string | null | undefined): Presence | null;
31
63
  /** User ids currently typing in a conversation (entries expire after 6 s without a refresh). */
32
64
  export declare function useTyping(conversationId: string): string[];
package/dist/index.js CHANGED
@@ -2,16 +2,49 @@
2
2
  import { createContext, useCallback, useContext, useEffect, useRef, useState, useSyncExternalStore } from "react";
3
3
  import { jsx } from "react/jsx-runtime";
4
4
  // src/messages.ts
5
- /** Pure merge of a conversation event into a seq-ordered message list (edits/deletes replace by id). */
6
- function applyEvent(messages, event) {
5
+ /** Keeps a parent's thread summary current as replies arrive or are deleted. */
6
+ function updateThread(messages, reply, created) {
7
+ const idx = messages.findIndex((m) => m.id === reply.parentMessageId);
8
+ if (idx < 0) return messages;
9
+ const parent = messages[idx];
10
+ const prev = parent.thread ?? {
11
+ replyCount: 0,
12
+ lastReplyAt: null,
13
+ participantIds: []
14
+ };
15
+ const thread = created ? {
16
+ replyCount: prev.replyCount + 1,
17
+ lastReplyAt: reply.createdAt,
18
+ participantIds: [reply.senderId, ...prev.participantIds.filter((id) => id !== reply.senderId)].slice(0, 5)
19
+ } : {
20
+ ...prev,
21
+ replyCount: Math.max(0, prev.replyCount - 1)
22
+ };
23
+ const next = messages.slice();
24
+ next[idx] = {
25
+ ...parent,
26
+ thread: thread.replyCount > 0 ? thread : null
27
+ };
28
+ return next;
29
+ }
30
+ /**
31
+ * Pure merge of a conversation event into a seq-ordered message list (edits/deletes/pins replace
32
+ * by id). Messages rejected by `include` are not added, but replies still update their parent's
33
+ * thread summary.
34
+ */
35
+ function applyEvent(messages, event, include = () => true) {
7
36
  const incoming = event.message;
8
- const idx = messages.findIndex((m) => m.id === incoming.id);
37
+ let list = messages;
38
+ if (incoming.parentMessageId && event.type === "message.created") list = updateThread(list, incoming, true);
39
+ if (incoming.parentMessageId && event.type === "message.deleted") list = updateThread(list, incoming, false);
40
+ const idx = list.findIndex((m) => m.id === incoming.id);
9
41
  if (idx >= 0) {
10
- const next = messages.slice();
42
+ const next = list.slice();
11
43
  next[idx] = incoming;
12
44
  return next;
13
45
  }
14
- const next = [...messages, incoming];
46
+ if (!include(incoming)) return list;
47
+ const next = [...list, incoming];
15
48
  next.sort((a, b) => a.seq - b.seq);
16
49
  return next;
17
50
  }
@@ -22,6 +55,19 @@ function mergeHistory(messages, older) {
22
55
  }
23
56
  // src/index.tsx
24
57
  const LynkoriaContext = createContext(null);
58
+ /** Views of the same conversation share the client's ordering state; untrack after the last one. */
59
+ const tracking = /* @__PURE__ */ new WeakMap();
60
+ function hold(client, conversationId) {
61
+ const counts = tracking.get(client) ?? /* @__PURE__ */ new Map();
62
+ tracking.set(client, counts);
63
+ counts.set(conversationId, (counts.get(conversationId) ?? 0) + 1);
64
+ return () => {
65
+ const left = (counts.get(conversationId) ?? 1) - 1;
66
+ if (left > 0) return void counts.set(conversationId, left);
67
+ counts.delete(conversationId);
68
+ client.conversations.untrack(conversationId);
69
+ };
70
+ }
25
71
  const pendingDisconnect = /* @__PURE__ */ new WeakMap();
26
72
  /**
27
73
  * Connects the client while mounted. Disconnecting is deferred by one task, so Strict Mode's
@@ -61,32 +107,42 @@ const emptyConversation = (id) => ({
61
107
  messages: [],
62
108
  loading: true,
63
109
  error: null,
64
- hasMore: false
110
+ hasMore: false,
111
+ lastSeq: 0
65
112
  });
66
113
  /** Live, ordered message list for one conversation: history + realtime events + gap resync. */
67
- function useConversation(conversationId) {
114
+ function useConversation(conversationId, options = {}) {
68
115
  const client = useLynkoria();
69
- const [data, setData] = useState(() => emptyConversation(conversationId));
70
- const current = data.id === conversationId ? data : emptyConversation(conversationId);
116
+ const { threadId, topLevel } = options;
117
+ const key = `${conversationId}|${threadId ?? ""}|${topLevel ? "top" : ""}`;
118
+ const [data, setData] = useState(() => emptyConversation(key));
119
+ const current = data.id === key ? data : emptyConversation(key);
71
120
  useEffect(() => {
72
121
  let active = true;
73
- const update = (fn) => setData((prev) => fn(prev.id === conversationId ? prev : emptyConversation(conversationId)));
122
+ const release = hold(client, conversationId);
123
+ const include = (m) => threadId ? m.parentMessageId === threadId : topLevel ? !m.parentMessageId : true;
124
+ const update = (fn) => setData((prev) => fn(prev.id === key ? prev : emptyConversation(key)));
74
125
  const off = client.onMessage((event) => {
75
126
  if (event.conversationId === conversationId) update((d) => ({
76
127
  ...d,
77
- messages: applyEvent(d.messages, event)
128
+ messages: applyEvent(d.messages, event, include),
129
+ lastSeq: Math.max(d.lastSeq, event.seq)
78
130
  }));
79
131
  });
80
132
  (async () => {
81
133
  try {
82
- const page = await client.messages.history(conversationId);
134
+ const page = await client.messages.history(conversationId, {
135
+ ...threadId ? { threadId } : {},
136
+ ...topLevel ? { topLevel } : {}
137
+ });
83
138
  if (!active) return;
84
139
  const older = page.items.map((e) => e.message);
85
140
  update((d) => ({
86
141
  ...d,
87
142
  messages: mergeHistory(d.messages, older),
88
143
  hasMore: page.hasMore,
89
- loading: false
144
+ loading: false,
145
+ lastSeq: Math.max(d.lastSeq, page.lastSeq)
90
146
  }));
91
147
  } catch (err) {
92
148
  if (active) update((d) => ({
@@ -99,16 +155,26 @@ function useConversation(conversationId) {
99
155
  return () => {
100
156
  active = false;
101
157
  off();
102
- client.conversations.untrack(conversationId);
158
+ release();
103
159
  };
104
- }, [client, conversationId]);
160
+ }, [
161
+ client,
162
+ conversationId,
163
+ key,
164
+ threadId,
165
+ topLevel
166
+ ]);
105
167
  const oldestSeq = current.messages[0]?.seq;
106
- const newestSeq = current.messages.at(-1)?.seq;
168
+ const lastSeq = current.lastSeq;
107
169
  const loadOlder = useCallback(async () => {
108
170
  if (oldestSeq === void 0) return;
109
- const page = await client.messages.history(conversationId, { beforeSeq: oldestSeq });
171
+ const page = await client.messages.history(conversationId, {
172
+ beforeSeq: oldestSeq,
173
+ ...threadId ? { threadId } : {},
174
+ ...topLevel ? { topLevel } : {}
175
+ });
110
176
  const older = page.items.map((e) => e.message);
111
- setData((prev) => prev.id === conversationId ? {
177
+ setData((prev) => prev.id === key ? {
112
178
  ...prev,
113
179
  messages: mergeHistory(prev.messages, older),
114
180
  hasMore: page.hasMore
@@ -116,20 +182,28 @@ function useConversation(conversationId) {
116
182
  }, [
117
183
  client,
118
184
  conversationId,
119
- oldestSeq
185
+ key,
186
+ oldestSeq,
187
+ threadId,
188
+ topLevel
120
189
  ]);
121
- const send = useCallback((text, options = {}) => client.messages.send({
190
+ const send = useCallback((text, sendOptions = {}) => client.messages.send({
122
191
  conversationId,
123
192
  text,
124
193
  clientMessageId: client.ids.create(),
125
- ...options
126
- }), [client, conversationId]);
194
+ ...threadId ? { parentMessageId: threadId } : {},
195
+ ...sendOptions
196
+ }), [
197
+ client,
198
+ conversationId,
199
+ threadId
200
+ ]);
127
201
  const markRead = useCallback(async () => {
128
- if (newestSeq !== void 0) await client.messages.markRead(conversationId, newestSeq);
202
+ if (lastSeq > 0) await client.messages.markRead(conversationId, lastSeq);
129
203
  }, [
130
204
  client,
131
205
  conversationId,
132
- newestSeq
206
+ lastSeq
133
207
  ]);
134
208
  return {
135
209
  messages: current.messages,
@@ -141,6 +215,85 @@ function useConversation(conversationId) {
141
215
  markRead
142
216
  };
143
217
  }
218
+ /**
219
+ * The user's conversations by recent activity with unread and mention badges, kept current: new
220
+ * messages, reads, membership and metadata changes and reconnects refresh the loaded pages.
221
+ */
222
+ function useConversationList(options = {}) {
223
+ const client = useLynkoria();
224
+ const pageSize = Math.min(100, options.pageSize ?? 50);
225
+ const [state, setState] = useState({
226
+ items: [],
227
+ cursor: null,
228
+ loading: true,
229
+ error: null
230
+ });
231
+ const loaded = useRef(pageSize);
232
+ const generation = useRef(0);
233
+ const fetchPages = useCallback(async () => {
234
+ const attempt = ++generation.current;
235
+ try {
236
+ const items = [];
237
+ let cursor;
238
+ do {
239
+ const page = await client.conversations.list({
240
+ limit: Math.min(100, loaded.current - items.length),
241
+ ...cursor ? { cursor } : {}
242
+ });
243
+ items.push(...page.items);
244
+ cursor = page.nextCursor ?? void 0;
245
+ } while (cursor && items.length < loaded.current);
246
+ if (generation.current === attempt) setState({
247
+ items,
248
+ cursor: cursor ?? null,
249
+ loading: false,
250
+ error: null
251
+ });
252
+ } catch (err) {
253
+ if (generation.current === attempt) setState((s) => ({
254
+ ...s,
255
+ loading: false,
256
+ error: err
257
+ }));
258
+ }
259
+ }, [client]);
260
+ useEffect(() => {
261
+ let timer;
262
+ const schedule = () => {
263
+ clearTimeout(timer);
264
+ timer = setTimeout(() => void fetchPages(), 300);
265
+ };
266
+ fetchPages();
267
+ const offs = [
268
+ client.onMessage((e) => {
269
+ if (e.type === "message.created" || e.type === "message.deleted") schedule();
270
+ }),
271
+ client.onRead(schedule),
272
+ client.onConversationUpdated(schedule),
273
+ client.onConnectionState((s) => {
274
+ if (s === "connected") schedule();
275
+ })
276
+ ];
277
+ const gen = generation;
278
+ return () => {
279
+ clearTimeout(timer);
280
+ gen.current++;
281
+ for (const off of offs) off();
282
+ };
283
+ }, [client, fetchPages]);
284
+ const loadMore = useCallback(async () => {
285
+ loaded.current += pageSize;
286
+ await fetchPages();
287
+ }, [fetchPages, pageSize]);
288
+ return {
289
+ conversations: state.items,
290
+ loading: state.loading,
291
+ error: state.error,
292
+ hasMore: state.cursor !== null,
293
+ loadMore,
294
+ refresh: fetchPages
295
+ };
296
+ }
144
297
  function usePresence(userId) {
145
298
  const client = useLynkoria();
146
299
  const [state, setState] = useState(null);
@@ -264,4 +417,4 @@ function useCallParticipants(session) {
264
417
  })), [session]);
265
418
  return state.session === session ? state.list : session?.participants ?? noParticipants;
266
419
  }
267
- export { LynkoriaProvider, applyEvent, mergeHistory, useCall, useCallParticipants, useConnectionState, useConversation, useLynkoria, usePresence, useTyping };
420
+ export { LynkoriaProvider, applyEvent, mergeHistory, useCall, useCallParticipants, useConnectionState, useConversation, useConversationList, useLynkoria, usePresence, useTyping };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lynkoria/react",
3
- "version": "0.1.2",
3
+ "version": "0.2.0",
4
4
  "description": "React hooks for Lynkoria calls, messages and presence",
5
5
  "license": "Apache-2.0",
6
6
  "type": "module",
@@ -23,12 +23,12 @@
23
23
  "access": "public"
24
24
  },
25
25
  "devDependencies": {
26
- "@lynkoria/client": "0.2.0",
26
+ "@lynkoria/client": "0.3.1",
27
27
  "@lynkoria/config": "0.0.0",
28
28
  "@testing-library/react": "^16.3.3",
29
29
  "@types/react": "^19.3.0",
30
30
  "@types/react-dom": "^19.3.0",
31
- "jsdom": "31.0.0",
31
+ "jsdom": "31.0.1",
32
32
  "react": "^19.3.1",
33
33
  "react-dom": "^19.3.1",
34
34
  "tsdown": "^0.23.7",
@@ -36,7 +36,7 @@
36
36
  "vitest": "^5.1.0"
37
37
  },
38
38
  "peerDependencies": {
39
- "@lynkoria/client": "^0.2.0",
39
+ "@lynkoria/client": "^0.3.1",
40
40
  "react": "^18.2.0 || ^19.0.0"
41
41
  },
42
42
  "scripts": {