@poolse/react 3.2.0 → 3.4.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/dist/index.js CHANGED
@@ -5,6 +5,178 @@ import { createContext, useRef, useMemo, useEffect, useContext, useState, useCal
5
5
  import { jsx } from 'react/jsx-runtime';
6
6
 
7
7
  // src/provider.tsx
8
+
9
+ // src/conversations-store.ts
10
+ var ConversationsStore = class {
11
+ constructor(chat) {
12
+ this.chat = chat;
13
+ }
14
+ chat;
15
+ state = { conversations: [], loading: true, error: null };
16
+ listeners = /* @__PURE__ */ new Set();
17
+ loaded = false;
18
+ inflight = null;
19
+ unbind = null;
20
+ getSnapshot() {
21
+ return this.state;
22
+ }
23
+ subscribe(listener) {
24
+ this.listeners.add(listener);
25
+ if (this.listeners.size === 1) this.activate();
26
+ return () => {
27
+ if (!this.listeners.delete(listener)) return;
28
+ if (this.listeners.size === 0) this.deactivate();
29
+ };
30
+ }
31
+ /** Reload the list from REST. Shows `loading` until it lands. */
32
+ refetch() {
33
+ return this.load(true);
34
+ }
35
+ async create(attrs) {
36
+ const conv = await this.chat.conversations.create(attrs);
37
+ this.setConversations((prev) => prepend(prev, conv));
38
+ return conv;
39
+ }
40
+ /** Zero a conversation's unread and mention counts. */
41
+ markRead(conversationId) {
42
+ this.setConversations(
43
+ (prev) => patchRow(
44
+ prev,
45
+ conversationId,
46
+ (c) => c.unread_count === 0 && !c.mention_unread_count ? c : { ...c, unread_count: 0, mention_unread_count: 0 }
47
+ )
48
+ );
49
+ }
50
+ /** Apply a `conversation:read` push. */
51
+ applyRead(evt) {
52
+ this.setConversations(
53
+ (prev) => patchRow(prev, evt.conversation_id, (c) => ({
54
+ ...c,
55
+ unread_count: evt.unread_count,
56
+ mention_unread_count: evt.mention_unread_count
57
+ }))
58
+ );
59
+ }
60
+ /** Merge a `conversation:updated` push. */
61
+ applyUpdated(conversation, fromMe) {
62
+ this.setConversations((prev) => mergeUpdated(prev, conversation, fromMe));
63
+ }
64
+ /** Add (or replace) a row from `conversation:created`. */
65
+ applyCreated(conversation) {
66
+ this.setConversations((prev) => prepend(prev, conversation));
67
+ }
68
+ activate() {
69
+ void this.load(!this.loaded).catch(() => {
70
+ });
71
+ let off = null;
72
+ let boundId = null;
73
+ const bind = (me) => {
74
+ if (me.id === boundId) return;
75
+ off?.();
76
+ boundId = me.id;
77
+ off = this.bindRealtime(me.id);
78
+ };
79
+ const known = this.chat.me.peek();
80
+ if (known) bind(known);
81
+ const offMe = this.chat.me.onChange(bind);
82
+ this.unbind = () => {
83
+ offMe();
84
+ off?.();
85
+ };
86
+ }
87
+ deactivate() {
88
+ this.unbind?.();
89
+ this.unbind = null;
90
+ }
91
+ bindRealtime(meId) {
92
+ const realtime = this.chat.realtime;
93
+ const user = realtime.user(meId);
94
+ const offCreated = user.onConversationCreated((conv) => this.applyCreated(conv));
95
+ const offUpdated = user.onConversationUpdated(
96
+ ({ conversation, by_user_id }) => this.applyUpdated(conversation, by_user_id === meId)
97
+ );
98
+ const offRead = user.onConversationRead((evt) => this.applyRead(evt));
99
+ let wasConnected = realtime.getStatus() === "connected";
100
+ let connectedBefore = wasConnected;
101
+ const offStatus = realtime.onStatus((status) => {
102
+ const reconnected = status === "connected" && !wasConnected && connectedBefore;
103
+ connectedBefore ||= status === "connected";
104
+ wasConnected = status === "connected";
105
+ if (reconnected) void this.load(false).catch(() => {
106
+ });
107
+ });
108
+ return () => {
109
+ offCreated();
110
+ offUpdated();
111
+ offRead();
112
+ offStatus();
113
+ };
114
+ }
115
+ load(showLoading) {
116
+ if (showLoading && !this.state.loading) this.set({ ...this.state, loading: true });
117
+ if (this.inflight) return this.inflight;
118
+ const run = this.chat.conversations.list().then(
119
+ (list) => {
120
+ this.loaded = true;
121
+ this.set({ conversations: list.data, loading: false, error: null });
122
+ },
123
+ (err) => {
124
+ this.set({
125
+ ...this.state,
126
+ loading: false,
127
+ error: err instanceof Error ? err : new Error(String(err))
128
+ });
129
+ }
130
+ ).finally(() => {
131
+ if (this.inflight === run) this.inflight = null;
132
+ });
133
+ this.inflight = run;
134
+ return run;
135
+ }
136
+ setConversations(fn) {
137
+ const next = fn(this.state.conversations);
138
+ if (next !== this.state.conversations) this.set({ ...this.state, conversations: next });
139
+ }
140
+ set(state) {
141
+ this.state = state;
142
+ for (const l of this.listeners) l();
143
+ }
144
+ };
145
+ function patchRow(prev, id, fn) {
146
+ const idx = prev.findIndex((c) => c.id === id);
147
+ if (idx === -1) return prev;
148
+ const row = fn(prev[idx]);
149
+ if (row === prev[idx]) return prev;
150
+ const next = prev.slice();
151
+ next[idx] = row;
152
+ return next;
153
+ }
154
+ function prepend(prev, conv) {
155
+ const idx = prev.findIndex((c) => c.id === conv.id);
156
+ if (idx === -1) return [conv, ...prev];
157
+ const next = prev.slice();
158
+ next[idx] = conv;
159
+ return next;
160
+ }
161
+ function mergeUpdated(prev, next, fromMe) {
162
+ const idx = prev.findIndex((c) => c.id === next.id);
163
+ if (idx === -1) return [next, ...prev];
164
+ const existing = prev[idx];
165
+ const wireUnread = typeof next.unread_count === "number" ? next.unread_count : null;
166
+ const unread_count = wireUnread !== null ? wireUnread : fromMe ? 0 : (existing.unread_count ?? 0) + 1;
167
+ const merged = {
168
+ ...existing,
169
+ last_message_at: next.last_message_at,
170
+ last_message_preview: next.last_message_preview,
171
+ last_sequence: next.last_sequence,
172
+ unread_count
173
+ };
174
+ if (typeof next.mention_unread_count === "number") {
175
+ merged.mention_unread_count = next.mention_unread_count;
176
+ }
177
+ const rest = prev.slice(0, idx).concat(prev.slice(idx + 1));
178
+ return [merged, ...rest];
179
+ }
8
180
  var PoolseContext = createContext(null);
9
181
  function PoolseProvider({ config, children }) {
10
182
  const configRef = useRef(config);
@@ -54,17 +226,23 @@ function PoolseProvider({ config, children }) {
54
226
  chat.destroy();
55
227
  };
56
228
  }, [chat]);
57
- const value = useMemo(() => ({ chat }), [chat]);
229
+ const value = useMemo(() => ({ chat, conversations: new ConversationsStore(chat) }), [chat]);
58
230
  return /* @__PURE__ */ jsx(PoolseContext.Provider, { value, children });
59
231
  }
60
232
  function usePoolse() {
233
+ return usePoolseContext("usePoolse").chat;
234
+ }
235
+ function useConversationsStore() {
236
+ return usePoolseContext("useConversations").conversations;
237
+ }
238
+ function usePoolseContext(hook) {
61
239
  const value = useContext(PoolseContext);
62
240
  if (!value) {
63
241
  throw new Error(
64
- "usePoolse(): no <PoolseProvider> in the tree. Wrap your component with `<PoolseProvider config={{apiUrl, getToken}}>` first."
242
+ `${hook}(): no <PoolseProvider> in the tree. Wrap your component with \`<PoolseProvider config={{apiUrl, getToken}}>\` first.`
65
243
  );
66
244
  }
67
- return value.chat;
245
+ return value;
68
246
  }
69
247
  function useMe() {
70
248
  const chat = usePoolse();
@@ -134,99 +312,44 @@ function useConversation(id) {
134
312
  return { conversation, loading, error, refetch };
135
313
  }
136
314
  function useConversations() {
137
- const chat = usePoolse();
138
- const { me } = useMe();
139
- const [conversations, setConversations] = useState([]);
140
- const [loading, setLoading] = useState(true);
141
- const [error, setError] = useState(null);
142
- const refetch = useCallback(async () => {
143
- setLoading(true);
144
- try {
145
- const list = await chat.conversations.list();
146
- setConversations(list.data);
147
- setError(null);
148
- } catch (err) {
149
- setError(err instanceof Error ? err : new Error(String(err)));
150
- } finally {
151
- setLoading(false);
152
- }
153
- }, [chat]);
154
- const create = useCallback(
155
- async (attrs) => {
156
- const conv = await chat.conversations.create(attrs);
157
- setConversations((prev) => prepend(prev, conv));
158
- return conv;
159
- },
160
- [chat]
161
- );
162
- useEffect(() => {
163
- void refetch();
164
- }, [refetch]);
315
+ const store = useConversationsStore();
316
+ useMe();
317
+ const [snapshot, setSnapshot] = useState(() => store.getSnapshot());
165
318
  useEffect(() => {
166
- if (!me) return;
167
- const userChan = chat.realtime.user(me.id);
168
- const offCreated = userChan.onConversationCreated((conv) => {
169
- setConversations((prev) => prepend(prev, conv));
170
- });
171
- const offUpdated = userChan.onConversationUpdated(({ conversation, by_user_id }) => {
172
- const fromMe = by_user_id === me.id;
173
- setConversations((prev) => mergeUpdated(prev, conversation, fromMe));
174
- });
175
- let wasConnected = chat.realtime.getStatus() === "connected";
176
- let connectedBefore = wasConnected;
177
- const offStatus = chat.realtime.onStatus((status) => {
178
- const reconnected = status === "connected" && !wasConnected && connectedBefore;
179
- connectedBefore ||= status === "connected";
180
- if (reconnected) {
181
- chat.conversations.list().then((list) => setConversations(list.data)).catch(() => {
182
- });
183
- }
184
- wasConnected = status === "connected";
185
- });
186
- return () => {
187
- offCreated();
188
- offUpdated();
189
- offStatus();
190
- };
191
- }, [chat, me]);
192
- const markConversationRead = useCallback((conversationId) => {
193
- setConversations(
194
- (prev) => prev.map((c) => c.id === conversationId ? { ...c, unread_count: 0 } : c)
195
- );
196
- }, []);
197
- const unreadCounts = useMemo(() => {
198
- const out = {};
199
- for (const c of conversations) {
200
- if (typeof c.unread_count === "number" && c.unread_count > 0) {
201
- out[c.id] = c.unread_count;
202
- }
203
- }
204
- return out;
205
- }, [conversations]);
206
- return { conversations, loading, error, refetch, create, unreadCounts, markConversationRead };
207
- }
208
- function prepend(prev, conv) {
209
- const idx = prev.findIndex((c) => c.id === conv.id);
210
- if (idx === -1) return [conv, ...prev];
211
- const next = prev.slice();
212
- next[idx] = conv;
213
- return next;
214
- }
215
- function mergeUpdated(prev, next, fromMe) {
216
- const idx = prev.findIndex((c) => c.id === next.id);
217
- if (idx === -1) return [next, ...prev];
218
- const existing = prev[idx];
219
- const wireUnread = typeof next.unread_count === "number" ? next.unread_count : null;
220
- const unread_count = wireUnread !== null ? wireUnread : fromMe ? 0 : (existing.unread_count ?? 0) + 1;
221
- const merged = {
222
- ...existing,
223
- last_message_at: next.last_message_at,
224
- last_message_preview: next.last_message_preview,
225
- last_sequence: next.last_sequence,
226
- unread_count
319
+ const off = store.subscribe(() => setSnapshot(store.getSnapshot()));
320
+ setSnapshot(store.getSnapshot());
321
+ return off;
322
+ }, [store]);
323
+ const refetch = useCallback(() => store.refetch(), [store]);
324
+ const create = useCallback((attrs) => store.create(attrs), [store]);
325
+ const markConversationRead = useCallback(
326
+ (conversationId) => store.markRead(conversationId),
327
+ [store]
328
+ );
329
+ const { conversations, loading, error } = snapshot;
330
+ const unreadCounts = useMemo(() => countsOf(conversations, "unread_count"), [conversations]);
331
+ const mentionUnreadCounts = useMemo(
332
+ () => countsOf(conversations, "mention_unread_count"),
333
+ [conversations]
334
+ );
335
+ return {
336
+ conversations,
337
+ loading,
338
+ error,
339
+ refetch,
340
+ create,
341
+ unreadCounts,
342
+ mentionUnreadCounts,
343
+ markConversationRead
227
344
  };
228
- const rest = prev.slice(0, idx).concat(prev.slice(idx + 1));
229
- return [merged, ...rest];
345
+ }
346
+ function countsOf(conversations, key) {
347
+ const out = {};
348
+ for (const c of conversations) {
349
+ const n = c[key];
350
+ if (typeof n === "number" && n > 0) out[c.id] = n;
351
+ }
352
+ return out;
230
353
  }
231
354
  function useMembers(conversationId) {
232
355
  const chat = usePoolse();
@@ -326,12 +449,17 @@ function useMembers(conversationId) {
326
449
  var PAGE_SIZE = 50;
327
450
  function useMessages(conversationId) {
328
451
  const chat = usePoolse();
452
+ const conversationsStore = useConversationsStore();
329
453
  const { me } = useMe();
330
454
  const [messages, setMessages] = useState([]);
331
455
  const [loading, setLoading] = useState(true);
332
456
  const [error, setError] = useState(null);
333
457
  const [hasMore, setHasMore] = useState(true);
334
458
  const oldestSequenceRef = useRef(null);
459
+ const messagesRef = useRef(messages);
460
+ messagesRef.current = messages;
461
+ const hasMoreRef = useRef(hasMore);
462
+ hasMoreRef.current = hasMore;
335
463
  const refetchRef = useRef(null);
336
464
  const meIdRef = useRef(me?.id ?? null);
337
465
  meIdRef.current = me?.id ?? null;
@@ -429,6 +557,30 @@ function useMessages(conversationId) {
429
557
  setHasMore(page.data.length === PAGE_SIZE);
430
558
  oldestSequenceRef.current = older[0]?.sequence ?? oldestSequenceRef.current;
431
559
  }, [chat, conversationId, hasMore, loading]);
560
+ const loadUntil = useCallback(
561
+ async (messageId, maxPages = 20) => {
562
+ if (messagesRef.current.some((m) => m.id === messageId)) return true;
563
+ const handle = chat.conversations.one(conversationId).messages;
564
+ for (let i = 0; i < maxPages; i++) {
565
+ const before = oldestSequenceRef.current;
566
+ if (before === null || !hasMoreRef.current) return false;
567
+ const page = await handle.list({ limit: PAGE_SIZE, before });
568
+ const older = [...page.data].reverse();
569
+ if (older.length > 0) {
570
+ setMessages((prev) => {
571
+ const have = new Set(prev.map((m) => m.id));
572
+ return [...older.filter((m) => !have.has(m.id)), ...prev];
573
+ });
574
+ oldestSequenceRef.current = older[0].sequence;
575
+ }
576
+ hasMoreRef.current = page.data.length === PAGE_SIZE;
577
+ setHasMore(hasMoreRef.current);
578
+ if (older.some((m) => m.id === messageId)) return true;
579
+ }
580
+ return false;
581
+ },
582
+ [chat, conversationId]
583
+ );
432
584
  const send = useCallback(
433
585
  async (attrs) => {
434
586
  const id = attrs.id ?? safeUuid();
@@ -523,8 +675,9 @@ function useMessages(conversationId) {
523
675
  const markReadUpTo = useCallback(
524
676
  async (messageId) => {
525
677
  await chat.conversations.one(conversationId).messages.markRead(messageId);
678
+ conversationsStore.markRead(conversationId);
526
679
  },
527
- [chat, conversationId]
680
+ [chat, conversationId, conversationsStore]
528
681
  );
529
682
  const refetch = useCallback(async () => {
530
683
  const fn = refetchRef.current;
@@ -537,6 +690,7 @@ function useMessages(conversationId) {
537
690
  error,
538
691
  hasMore,
539
692
  loadMore,
693
+ loadUntil,
540
694
  send,
541
695
  edit,
542
696
  delete: deleteMessage,
@@ -1092,6 +1246,7 @@ function useAttachmentUrl(attachmentId) {
1092
1246
  var EMPTY = { profile: null, loading: false };
1093
1247
  function useUser(externalId) {
1094
1248
  const chat = usePoolse();
1249
+ const shownForRef = useRef(null);
1095
1250
  const [state, setState] = useState(() => {
1096
1251
  if (!externalId) return EMPTY;
1097
1252
  const cached = chat.users.peek(externalId);
@@ -1106,9 +1261,11 @@ function useUser(externalId) {
1106
1261
  const apply = () => {
1107
1262
  const cached = chat.users.peek(externalId);
1108
1263
  if (cached === void 0) {
1109
- setState({ profile: null, loading: true });
1264
+ const keep = shownForRef.current === externalId;
1265
+ setState((prev) => ({ profile: keep ? prev.profile : null, loading: true }));
1110
1266
  void chat.users.get(externalId);
1111
1267
  } else {
1268
+ shownForRef.current = externalId;
1112
1269
  setState({ profile: cached, loading: false });
1113
1270
  }
1114
1271
  };
@@ -1118,6 +1275,12 @@ function useUser(externalId) {
1118
1275
  }, [chat, externalId]);
1119
1276
  return state;
1120
1277
  }
1278
+ function useAppEvent(handler) {
1279
+ const chat = usePoolse();
1280
+ const handlerRef = useRef(handler);
1281
+ handlerRef.current = handler;
1282
+ useEffect(() => chat.onAppEvent((evt) => handlerRef.current(evt)), [chat]);
1283
+ }
1121
1284
  function computeGroupPosition(msg, prev, next, windowMs) {
1122
1285
  const continuesPrev = sameGroup(msg, prev, windowMs);
1123
1286
  const continuesNext = sameGroup(next, msg, windowMs);
@@ -1483,6 +1646,6 @@ function canEditOwnMessage(args) {
1483
1646
  return Number.isFinite(sent) && (args.now ?? Date.now()) - sent < EDIT_WINDOW_MS;
1484
1647
  }
1485
1648
 
1486
- export { EDIT_WINDOW_MS, PoolseProvider, canEditOwnMessage, computeGroupPosition, formatDayLabel, receiptsOf, sameDay, sameGroup, useAttachmentUpload, useAttachmentUrl, useCallRoom, useConversation, useConversations, useLiveCall, useMe, useMembers, useMessageStreams, useMessages, usePoolse, usePresence, useReactions, useReadReceipts, useRealtimeStatus, useRoom, useThread, useTyping, useUser };
1649
+ export { EDIT_WINDOW_MS, PoolseProvider, canEditOwnMessage, computeGroupPosition, formatDayLabel, receiptsOf, sameDay, sameGroup, useAppEvent, useAttachmentUpload, useAttachmentUrl, useCallRoom, useConversation, useConversations, useLiveCall, useMe, useMembers, useMessageStreams, useMessages, usePoolse, usePresence, useReactions, useReadReceipts, useRealtimeStatus, useRoom, useThread, useTyping, useUser };
1487
1650
  //# sourceMappingURL=index.js.map
1488
1651
  //# sourceMappingURL=index.js.map