@poolse/react 3.7.1 → 3.8.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 +21 -0
- package/README.md +52 -25
- package/dist/index.cjs +385 -50
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +170 -8
- package/dist/index.d.ts +170 -8
- package/dist/index.js +363 -54
- package/dist/index.js.map +1 -1
- package/package.json +2 -2
package/dist/index.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
'use client';
|
|
2
|
-
import { Poolse, toTombstone, markQuoteDeleted, safeUuid, mergeMessage, isCallLogMessage, applyThreadUpdate } from '@poolse/sdk';
|
|
3
|
-
export { ApiError, AuthError, NetworkError, PoolseError, RateLimitedError, callLogDisplayFor, describeCallLog, formatCallDuration, formatCallLogPreview, isCallLogMessage, isMessageVisibleTo, isTombstone, mergeMessage, parseCallLog, parseCallLogBody, toTombstone } from '@poolse/sdk';
|
|
4
|
-
import { createContext, useRef, useMemo, useEffect, useContext, useState, useCallback } from 'react';
|
|
2
|
+
import { Poolse, MessageQueuedError, toTombstone, markQuoteDeleted, safeUuid, mergeMessage, isCallLogMessage, applyThreadUpdate } from '@poolse/sdk';
|
|
3
|
+
export { ApiError, AuthError, MessageDiscardedError, MessageQueuedError, NetworkError, Poolse, PoolseError, RateLimitedError, callLogDisplayFor, createIndexedDbStorage, describeCallLog, formatCallDuration, formatCallLogPreview, isCallLogMessage, isMessageVisibleTo, isTombstone, memoryStorage, mergeMessage, parseCallLog, parseCallLogBody, toTombstone } from '@poolse/sdk';
|
|
4
|
+
import { createContext, useRef, useMemo, useEffect, useContext, useState, useCallback, useSyncExternalStore } from 'react';
|
|
5
5
|
import { jsx } from 'react/jsx-runtime';
|
|
6
6
|
|
|
7
7
|
// src/provider.tsx
|
|
@@ -10,6 +10,10 @@ import { jsx } from 'react/jsx-runtime';
|
|
|
10
10
|
var ConversationsStore = class {
|
|
11
11
|
constructor(chat) {
|
|
12
12
|
this.chat = chat;
|
|
13
|
+
const cached = chat.cache.peekConversations();
|
|
14
|
+
if (cached && cached.length > 0) {
|
|
15
|
+
this.state = { ...this.state, conversations: cached, loading: false };
|
|
16
|
+
}
|
|
13
17
|
}
|
|
14
18
|
chat;
|
|
15
19
|
state = {
|
|
@@ -28,6 +32,14 @@ var ConversationsStore = class {
|
|
|
28
32
|
nextCursor = null;
|
|
29
33
|
/** Whether rows beyond the first page are held. */
|
|
30
34
|
pagedBeyondFirst = false;
|
|
35
|
+
destroyed = false;
|
|
36
|
+
hydrating = null;
|
|
37
|
+
/** Called by `chat.destroy()`. @internal */
|
|
38
|
+
destroy() {
|
|
39
|
+
this.destroyed = true;
|
|
40
|
+
this.deactivate();
|
|
41
|
+
this.listeners.clear();
|
|
42
|
+
}
|
|
31
43
|
getSnapshot() {
|
|
32
44
|
return this.state;
|
|
33
45
|
}
|
|
@@ -77,6 +89,7 @@ var ConversationsStore = class {
|
|
|
77
89
|
}
|
|
78
90
|
/** Zero a conversation's unread and mention counts. */
|
|
79
91
|
markRead(conversationId) {
|
|
92
|
+
this.chat.unread.apply(conversationId, 0, 0);
|
|
80
93
|
this.setConversations(
|
|
81
94
|
(prev) => patchRow(
|
|
82
95
|
prev,
|
|
@@ -104,8 +117,11 @@ var ConversationsStore = class {
|
|
|
104
117
|
this.setConversations((prev) => prepend(prev, conversation));
|
|
105
118
|
}
|
|
106
119
|
activate() {
|
|
107
|
-
|
|
120
|
+
if (this.destroyed) return;
|
|
121
|
+
const showing = this.state.conversations.length > 0;
|
|
122
|
+
void this.load(!this.loaded && !showing).catch(() => {
|
|
108
123
|
});
|
|
124
|
+
if (!this.loaded && !showing) this.hydrate();
|
|
109
125
|
let off = null;
|
|
110
126
|
let boundId = null;
|
|
111
127
|
const bind = (me) => {
|
|
@@ -122,6 +138,16 @@ var ConversationsStore = class {
|
|
|
122
138
|
off?.();
|
|
123
139
|
};
|
|
124
140
|
}
|
|
141
|
+
// Show the stored list (a previous session's) while the first fetch
|
|
142
|
+
// is out — or instead of it, offline.
|
|
143
|
+
hydrate() {
|
|
144
|
+
this.hydrating ??= this.chat.cache.loadConversations().then((rows) => {
|
|
145
|
+
if (this.destroyed || this.loaded || !rows || rows.length === 0) return;
|
|
146
|
+
if (this.state.conversations.length > 0) return;
|
|
147
|
+
this.chat.timings._once("cachedConversations");
|
|
148
|
+
this.set({ ...this.state, conversations: rows, loading: false });
|
|
149
|
+
});
|
|
150
|
+
}
|
|
125
151
|
deactivate() {
|
|
126
152
|
this.unbind?.();
|
|
127
153
|
this.unbind = null;
|
|
@@ -155,6 +181,7 @@ var ConversationsStore = class {
|
|
|
155
181
|
if (this.inflight) return this.inflight;
|
|
156
182
|
const run = this.chat.conversations.list().then(
|
|
157
183
|
(list) => {
|
|
184
|
+
if (this.destroyed) return;
|
|
158
185
|
this.loaded = true;
|
|
159
186
|
let conversations = list.data;
|
|
160
187
|
if (this.pagedBeyondFirst) {
|
|
@@ -175,6 +202,7 @@ var ConversationsStore = class {
|
|
|
175
202
|
});
|
|
176
203
|
},
|
|
177
204
|
(err) => {
|
|
205
|
+
if (this.destroyed) return;
|
|
178
206
|
this.set({
|
|
179
207
|
...this.state,
|
|
180
208
|
loading: false,
|
|
@@ -192,6 +220,10 @@ var ConversationsStore = class {
|
|
|
192
220
|
if (next !== this.state.conversations) this.set({ ...this.state, conversations: next });
|
|
193
221
|
}
|
|
194
222
|
set(state) {
|
|
223
|
+
if (state.conversations !== this.state.conversations) {
|
|
224
|
+
this.chat.unread.observe(state.conversations);
|
|
225
|
+
if (this.loaded) this.chat.cache.setConversations(state.conversations);
|
|
226
|
+
}
|
|
195
227
|
this.state = state;
|
|
196
228
|
for (const l of this.listeners) l();
|
|
197
229
|
}
|
|
@@ -231,12 +263,27 @@ function mergeUpdated(prev, next, fromMe) {
|
|
|
231
263
|
const rest = prev.slice(0, idx).concat(prev.slice(idx + 1));
|
|
232
264
|
return [merged, ...rest];
|
|
233
265
|
}
|
|
266
|
+
function conversationsStoreOf(chat) {
|
|
267
|
+
return chat.scoped("react:conversations", (c) => new ConversationsStore(c));
|
|
268
|
+
}
|
|
234
269
|
var PoolseContext = createContext(null);
|
|
235
|
-
function PoolseProvider({
|
|
270
|
+
function PoolseProvider({
|
|
271
|
+
client,
|
|
272
|
+
config: configProp,
|
|
273
|
+
background,
|
|
274
|
+
trackActivity = true,
|
|
275
|
+
children
|
|
276
|
+
}) {
|
|
277
|
+
if (!client && !configProp) {
|
|
278
|
+
throw new Error("<PoolseProvider>: pass `client` or `config`.");
|
|
279
|
+
}
|
|
280
|
+
const config = configProp ?? { getToken: () => null };
|
|
236
281
|
const configRef = useRef(config);
|
|
237
282
|
configRef.current = config;
|
|
238
283
|
const initialConnectionRef = useRef(null);
|
|
239
|
-
const
|
|
284
|
+
const externalRef = useRef(client !== void 0);
|
|
285
|
+
const ownChat = useMemo(() => {
|
|
286
|
+
if (externalRef.current) return null;
|
|
240
287
|
const initial = configRef.current;
|
|
241
288
|
initialConnectionRef.current = {
|
|
242
289
|
apiUrl: initial.apiUrl,
|
|
@@ -264,6 +311,9 @@ function PoolseProvider({ config, trackActivity = true, children }) {
|
|
|
264
311
|
...initial.userResolver ? { userResolver: (id) => configRef.current.userResolver(id) } : {}
|
|
265
312
|
});
|
|
266
313
|
}, []);
|
|
314
|
+
const chat = client ?? ownChat;
|
|
315
|
+
if (!chat)
|
|
316
|
+
throw new Error("<PoolseProvider>: `client` was removed after mount; remount instead.");
|
|
267
317
|
if (process.env.NODE_ENV !== "production") {
|
|
268
318
|
useEffect(() => {
|
|
269
319
|
const initial = initialConnectionRef.current;
|
|
@@ -276,17 +326,22 @@ function PoolseProvider({ config, trackActivity = true, children }) {
|
|
|
276
326
|
}, [config.apiUrl, config.wsUrl, config.socketPath]);
|
|
277
327
|
}
|
|
278
328
|
useEffect(() => {
|
|
329
|
+
if (!ownChat) return;
|
|
279
330
|
return () => {
|
|
280
|
-
|
|
331
|
+
void ownChat.destroy();
|
|
281
332
|
};
|
|
282
|
-
}, [
|
|
333
|
+
}, [ownChat]);
|
|
334
|
+
useEffect(() => {
|
|
335
|
+
if (background === void 0) return;
|
|
336
|
+
chat.setBackground(background);
|
|
337
|
+
}, [chat, background]);
|
|
283
338
|
const trackActivityRef = useRef(trackActivity);
|
|
284
339
|
useEffect(() => {
|
|
285
340
|
const opts = trackActivityRef.current;
|
|
286
341
|
if (opts === false) return;
|
|
287
342
|
return chat.presence.trackActivity(opts === true ? {} : opts);
|
|
288
343
|
}, [chat]);
|
|
289
|
-
const value = useMemo(() => ({ chat, conversations:
|
|
344
|
+
const value = useMemo(() => ({ chat, conversations: conversationsStoreOf(chat) }), [chat]);
|
|
290
345
|
return /* @__PURE__ */ jsx(PoolseContext.Provider, { value, children });
|
|
291
346
|
}
|
|
292
347
|
function usePoolse() {
|
|
@@ -295,6 +350,9 @@ function usePoolse() {
|
|
|
295
350
|
function useConversationsStore() {
|
|
296
351
|
return usePoolseContext("useConversations").conversations;
|
|
297
352
|
}
|
|
353
|
+
function useOptionalPoolse() {
|
|
354
|
+
return useContext(PoolseContext)?.chat ?? null;
|
|
355
|
+
}
|
|
298
356
|
function usePoolseContext(hook) {
|
|
299
357
|
const value = useContext(PoolseContext);
|
|
300
358
|
if (!value) {
|
|
@@ -335,42 +393,8 @@ function useMe() {
|
|
|
335
393
|
}, [chat]);
|
|
336
394
|
return state;
|
|
337
395
|
}
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
const [conversation, setConversation] = useState(null);
|
|
341
|
-
const [loading, setLoading] = useState(id !== null);
|
|
342
|
-
const [error, setError] = useState(null);
|
|
343
|
-
const fetcher = useCallback(
|
|
344
|
-
async (signal) => {
|
|
345
|
-
if (id === null) return;
|
|
346
|
-
setLoading(true);
|
|
347
|
-
setError(null);
|
|
348
|
-
try {
|
|
349
|
-
const conv = await chat.conversations.one(id).show(signal);
|
|
350
|
-
setConversation(conv);
|
|
351
|
-
} catch (err) {
|
|
352
|
-
if (err?.name === "AbortError") return;
|
|
353
|
-
setError(err instanceof Error ? err : new Error(String(err)));
|
|
354
|
-
} finally {
|
|
355
|
-
setLoading(false);
|
|
356
|
-
}
|
|
357
|
-
},
|
|
358
|
-
[chat, id]
|
|
359
|
-
);
|
|
360
|
-
useEffect(() => {
|
|
361
|
-
if (id === null) {
|
|
362
|
-
setConversation(null);
|
|
363
|
-
setLoading(false);
|
|
364
|
-
setError(null);
|
|
365
|
-
return;
|
|
366
|
-
}
|
|
367
|
-
const controller = new AbortController();
|
|
368
|
-
void fetcher(controller.signal);
|
|
369
|
-
return () => controller.abort();
|
|
370
|
-
}, [fetcher, id]);
|
|
371
|
-
const refetch = useCallback(() => fetcher(), [fetcher]);
|
|
372
|
-
return { conversation, loading, error, refetch };
|
|
373
|
-
}
|
|
396
|
+
|
|
397
|
+
// src/use-conversations.ts
|
|
374
398
|
function useConversations() {
|
|
375
399
|
const store = useConversationsStore();
|
|
376
400
|
useMe();
|
|
@@ -415,6 +439,189 @@ function countsOf(conversations, key) {
|
|
|
415
439
|
}
|
|
416
440
|
return out;
|
|
417
441
|
}
|
|
442
|
+
|
|
443
|
+
// src/use-unread.ts
|
|
444
|
+
function useUnreadTotals(client) {
|
|
445
|
+
const fromContext = useOptionalPoolse();
|
|
446
|
+
const chat = client ?? fromContext;
|
|
447
|
+
if (!chat) {
|
|
448
|
+
throw new Error("useUnreadTotals(): pass a client, or render inside a <PoolseProvider>.");
|
|
449
|
+
}
|
|
450
|
+
const subscribe = useCallback((fn) => chat.unread.subscribe(fn), [chat]);
|
|
451
|
+
const totals = useSyncExternalStore(subscribe, () => chat.unread.get());
|
|
452
|
+
const refresh = useCallback(() => chat.unread.refresh(), [chat]);
|
|
453
|
+
return useMemo(() => ({ ...totals, refresh }), [totals, refresh]);
|
|
454
|
+
}
|
|
455
|
+
function useUnreadQueue(opts = {}) {
|
|
456
|
+
const chat = usePoolse();
|
|
457
|
+
const { conversations, markConversationRead } = useConversations();
|
|
458
|
+
const { mentionsFirst = false, filter } = opts;
|
|
459
|
+
const [skipped, setSkipped] = useState(() => /* @__PURE__ */ new Set());
|
|
460
|
+
const [currentId, setCurrentId] = useState(null);
|
|
461
|
+
const queue = useMemo(
|
|
462
|
+
() => orderUnread(conversations, { mentionsFirst, ...filter ? { filter } : {} }),
|
|
463
|
+
[conversations, mentionsFirst, filter]
|
|
464
|
+
);
|
|
465
|
+
const offered = useMemo(() => queue.filter((c) => !skipped.has(c.id)), [queue, skipped]);
|
|
466
|
+
const pinned = currentId ? conversations.find((c) => c.id === currentId) ?? null : null;
|
|
467
|
+
const current = pinned ?? offered[0] ?? null;
|
|
468
|
+
useEffect(() => {
|
|
469
|
+
if (currentId && !pinned) setCurrentId(null);
|
|
470
|
+
}, [currentId, pinned]);
|
|
471
|
+
const markRead = useCallback(
|
|
472
|
+
async (conversationId) => {
|
|
473
|
+
markConversationRead(conversationId);
|
|
474
|
+
const page = await chat.conversations.one(conversationId).messages.list({ limit: 1 });
|
|
475
|
+
const latest = page.data[0];
|
|
476
|
+
if (latest) await chat.conversations.one(conversationId).messages.markRead(latest.id);
|
|
477
|
+
},
|
|
478
|
+
[chat, markConversationRead]
|
|
479
|
+
);
|
|
480
|
+
const after = (id) => offered.find((c) => c.id !== id) ?? null;
|
|
481
|
+
const next = () => {
|
|
482
|
+
if (current) void markRead(current.id).catch(() => {
|
|
483
|
+
});
|
|
484
|
+
const following = after(current?.id);
|
|
485
|
+
setCurrentId(following?.id ?? null);
|
|
486
|
+
return following;
|
|
487
|
+
};
|
|
488
|
+
const skip = () => {
|
|
489
|
+
const id = current?.id;
|
|
490
|
+
if (id) setSkipped((s) => new Set(s).add(id));
|
|
491
|
+
const following = after(id);
|
|
492
|
+
setCurrentId(following?.id ?? null);
|
|
493
|
+
return following;
|
|
494
|
+
};
|
|
495
|
+
const reset = useCallback(() => setSkipped(/* @__PURE__ */ new Set()), []);
|
|
496
|
+
return {
|
|
497
|
+
queue,
|
|
498
|
+
current,
|
|
499
|
+
remaining: offered.filter((c) => c.id !== current?.id).length,
|
|
500
|
+
next,
|
|
501
|
+
skip,
|
|
502
|
+
markRead,
|
|
503
|
+
reset
|
|
504
|
+
};
|
|
505
|
+
}
|
|
506
|
+
function orderUnread(conversations, opts = {}) {
|
|
507
|
+
const unread = conversations.filter(
|
|
508
|
+
(c) => (c.unread_count ?? 0) > 0 && (!opts.filter || opts.filter(c))
|
|
509
|
+
);
|
|
510
|
+
const at = (c) => c.last_message_at ? Date.parse(c.last_message_at) : 0;
|
|
511
|
+
return unread.sort((a, b) => {
|
|
512
|
+
if (opts.mentionsFirst) {
|
|
513
|
+
const ma = (a.mention_unread_count ?? 0) > 0 ? 1 : 0;
|
|
514
|
+
const mb = (b.mention_unread_count ?? 0) > 0 ? 1 : 0;
|
|
515
|
+
if (ma !== mb) return mb - ma;
|
|
516
|
+
}
|
|
517
|
+
return at(b) - at(a);
|
|
518
|
+
});
|
|
519
|
+
}
|
|
520
|
+
function useOutbox(opts = {}) {
|
|
521
|
+
const fromContext = useOptionalPoolse();
|
|
522
|
+
const chat = opts.client ?? fromContext;
|
|
523
|
+
if (!chat) throw new Error("useOutbox(): pass a client, or render inside a <PoolseProvider>.");
|
|
524
|
+
const subscribe = useCallback((fn) => chat.outbox.subscribe(fn), [chat]);
|
|
525
|
+
const all = useSyncExternalStore(subscribe, () => chat.outbox.entries());
|
|
526
|
+
const { conversationId } = opts;
|
|
527
|
+
const entries = useMemo(
|
|
528
|
+
() => conversationId ? all.filter((e) => e.conversationId === conversationId) : all,
|
|
529
|
+
[all, conversationId]
|
|
530
|
+
);
|
|
531
|
+
const retry = useCallback(
|
|
532
|
+
async (id) => {
|
|
533
|
+
try {
|
|
534
|
+
await chat.outbox.retry(id);
|
|
535
|
+
} catch (err) {
|
|
536
|
+
if (!(err instanceof MessageQueuedError)) throw err;
|
|
537
|
+
}
|
|
538
|
+
},
|
|
539
|
+
[chat]
|
|
540
|
+
);
|
|
541
|
+
const remove = useCallback((id) => chat.outbox.remove(id), [chat]);
|
|
542
|
+
const flush = useCallback(() => chat.outbox.flush(), [chat]);
|
|
543
|
+
return {
|
|
544
|
+
entries,
|
|
545
|
+
pending: entries.filter((e) => e.status !== "failed").length,
|
|
546
|
+
failed: entries.filter((e) => e.status === "failed").length,
|
|
547
|
+
retry,
|
|
548
|
+
remove,
|
|
549
|
+
flush
|
|
550
|
+
};
|
|
551
|
+
}
|
|
552
|
+
function useClientTimings(client) {
|
|
553
|
+
const fromContext = useOptionalPoolse();
|
|
554
|
+
const chat = client ?? fromContext;
|
|
555
|
+
if (!chat) {
|
|
556
|
+
throw new Error("useClientTimings(): pass a client, or render inside a <PoolseProvider>.");
|
|
557
|
+
}
|
|
558
|
+
const snapshot = useRef(null);
|
|
559
|
+
const subscribe = useCallback(
|
|
560
|
+
(fn) => chat.timings.on(() => {
|
|
561
|
+
snapshot.current = null;
|
|
562
|
+
fn();
|
|
563
|
+
}),
|
|
564
|
+
[chat]
|
|
565
|
+
);
|
|
566
|
+
const get = () => {
|
|
567
|
+
if (!snapshot.current || snapshot.current.chat !== chat) {
|
|
568
|
+
snapshot.current = { chat, value: chat.timings.get() };
|
|
569
|
+
}
|
|
570
|
+
return snapshot.current.value;
|
|
571
|
+
};
|
|
572
|
+
return useSyncExternalStore(subscribe, get);
|
|
573
|
+
}
|
|
574
|
+
|
|
575
|
+
// src/conversation-search.ts
|
|
576
|
+
function filterConversations(conversations, query, opts = {}) {
|
|
577
|
+
const needle = query.trim().toLowerCase();
|
|
578
|
+
if (!needle) return conversations.slice();
|
|
579
|
+
return conversations.filter((c) => {
|
|
580
|
+
const hay = [c.name ?? "", c.last_message_preview ?? ""];
|
|
581
|
+
for (const ext of c.member_external_ids ?? []) {
|
|
582
|
+
if (ext === opts.meExternalId) continue;
|
|
583
|
+
hay.push(ext);
|
|
584
|
+
if (opts.labelFor) hay.push(opts.labelFor(ext));
|
|
585
|
+
}
|
|
586
|
+
return hay.some((h) => h.toLowerCase().includes(needle));
|
|
587
|
+
});
|
|
588
|
+
}
|
|
589
|
+
function useConversation(id) {
|
|
590
|
+
const chat = usePoolse();
|
|
591
|
+
const [conversation, setConversation] = useState(null);
|
|
592
|
+
const [loading, setLoading] = useState(id !== null);
|
|
593
|
+
const [error, setError] = useState(null);
|
|
594
|
+
const fetcher = useCallback(
|
|
595
|
+
async (signal) => {
|
|
596
|
+
if (id === null) return;
|
|
597
|
+
setLoading(true);
|
|
598
|
+
setError(null);
|
|
599
|
+
try {
|
|
600
|
+
const conv = await chat.conversations.one(id).show(signal);
|
|
601
|
+
setConversation(conv);
|
|
602
|
+
} catch (err) {
|
|
603
|
+
if (err?.name === "AbortError") return;
|
|
604
|
+
setError(err instanceof Error ? err : new Error(String(err)));
|
|
605
|
+
} finally {
|
|
606
|
+
setLoading(false);
|
|
607
|
+
}
|
|
608
|
+
},
|
|
609
|
+
[chat, id]
|
|
610
|
+
);
|
|
611
|
+
useEffect(() => {
|
|
612
|
+
if (id === null) {
|
|
613
|
+
setConversation(null);
|
|
614
|
+
setLoading(false);
|
|
615
|
+
setError(null);
|
|
616
|
+
return;
|
|
617
|
+
}
|
|
618
|
+
const controller = new AbortController();
|
|
619
|
+
void fetcher(controller.signal);
|
|
620
|
+
return () => controller.abort();
|
|
621
|
+
}, [fetcher, id]);
|
|
622
|
+
const refetch = useCallback(() => fetcher(), [fetcher]);
|
|
623
|
+
return { conversation, loading, error, refetch };
|
|
624
|
+
}
|
|
418
625
|
function useMembers(conversationId) {
|
|
419
626
|
const chat = usePoolse();
|
|
420
627
|
const [members, setMembers] = useState([]);
|
|
@@ -515,10 +722,14 @@ function useMessages(conversationId) {
|
|
|
515
722
|
const chat = usePoolse();
|
|
516
723
|
const conversationsStore = useConversationsStore();
|
|
517
724
|
const { me } = useMe();
|
|
518
|
-
const [messages, setMessages] = useState(
|
|
519
|
-
|
|
725
|
+
const [messages, setMessages] = useState(
|
|
726
|
+
() => initialRows(chat, conversationId) ?? []
|
|
727
|
+
);
|
|
728
|
+
const [loading, setLoading] = useState(() => !initialRows(chat, conversationId));
|
|
520
729
|
const [error, setError] = useState(null);
|
|
521
730
|
const [hasMore, setHasMore] = useState(true);
|
|
731
|
+
const [fromCache, setFromCache] = useState(() => !!chat.cache.peekMessages(conversationId));
|
|
732
|
+
const rowsForRef = useRef(null);
|
|
522
733
|
const oldestSequenceRef = useRef(null);
|
|
523
734
|
const messagesRef = useRef(messages);
|
|
524
735
|
messagesRef.current = messages;
|
|
@@ -529,33 +740,77 @@ function useMessages(conversationId) {
|
|
|
529
740
|
meIdRef.current = me?.id ?? null;
|
|
530
741
|
const meExternalIdRef = useRef(me?.external_id ?? null);
|
|
531
742
|
meExternalIdRef.current = me?.external_id ?? null;
|
|
743
|
+
useEffect(() => {
|
|
744
|
+
if (rowsForRef.current !== conversationId) return;
|
|
745
|
+
if (messages.some((m) => m.conversation_id !== conversationId)) return;
|
|
746
|
+
if (loading) return;
|
|
747
|
+
chat.cache.setMessages(conversationId, messages);
|
|
748
|
+
}, [chat, conversationId, messages, loading]);
|
|
532
749
|
useEffect(() => {
|
|
533
750
|
let cancelled = false;
|
|
534
|
-
|
|
535
|
-
|
|
751
|
+
let fresh = false;
|
|
752
|
+
const cached = chat.cache.peekMessages(conversationId);
|
|
753
|
+
rowsForRef.current = conversationId;
|
|
536
754
|
setError(null);
|
|
537
755
|
setHasMore(true);
|
|
538
|
-
|
|
756
|
+
if (cached) {
|
|
757
|
+
setMessages(withOutbox(cached, chat, conversationId));
|
|
758
|
+
setLoading(false);
|
|
759
|
+
setFromCache(true);
|
|
760
|
+
oldestSequenceRef.current = cached[0]?.sequence ?? null;
|
|
761
|
+
chat.timings._once("cachedMessages");
|
|
762
|
+
} else {
|
|
763
|
+
setLoading(true);
|
|
764
|
+
setMessages(withOutbox([], chat, conversationId));
|
|
765
|
+
setFromCache(false);
|
|
766
|
+
oldestSequenceRef.current = null;
|
|
767
|
+
void chat.cache.loadMessages(conversationId).then((stored) => {
|
|
768
|
+
if (cancelled || fresh || !stored || stored.length === 0) return;
|
|
769
|
+
setMessages(withOutbox(stored, chat, conversationId));
|
|
770
|
+
setLoading(false);
|
|
771
|
+
setError(null);
|
|
772
|
+
setFromCache(true);
|
|
773
|
+
oldestSequenceRef.current = stored[0]?.sequence ?? null;
|
|
774
|
+
chat.timings._once("cachedMessages");
|
|
775
|
+
});
|
|
776
|
+
}
|
|
539
777
|
const handle = chat.conversations.one(conversationId).messages;
|
|
540
778
|
handle.list({ limit: PAGE_SIZE }).then((page) => {
|
|
541
779
|
if (cancelled) return;
|
|
780
|
+
fresh = true;
|
|
542
781
|
const ordered = [...page.data].reverse();
|
|
543
|
-
setMessages(ordered);
|
|
782
|
+
setMessages((prev) => keepLocal(ordered, prev));
|
|
544
783
|
setHasMore(page.data.length === PAGE_SIZE);
|
|
545
784
|
oldestSequenceRef.current = ordered[0]?.sequence ?? null;
|
|
546
785
|
setLoading(false);
|
|
786
|
+
setFromCache(false);
|
|
547
787
|
}).catch((err) => {
|
|
548
788
|
if (cancelled) return;
|
|
789
|
+
if (chat.cache.peekMessages(conversationId)) {
|
|
790
|
+
setLoading(false);
|
|
791
|
+
return;
|
|
792
|
+
}
|
|
549
793
|
setError(err instanceof Error ? err : new Error(String(err)));
|
|
550
794
|
setLoading(false);
|
|
551
795
|
});
|
|
552
796
|
refetchRef.current = async () => {
|
|
553
797
|
const page = await handle.list({ limit: PAGE_SIZE });
|
|
554
798
|
const ordered = [...page.data].reverse();
|
|
555
|
-
setMessages(ordered);
|
|
799
|
+
setMessages((prev) => keepLocal(ordered, prev));
|
|
556
800
|
setHasMore(page.data.length === PAGE_SIZE);
|
|
557
801
|
oldestSequenceRef.current = ordered[0]?.sequence ?? null;
|
|
802
|
+
setFromCache(false);
|
|
803
|
+
};
|
|
804
|
+
const syncOutbox = () => {
|
|
805
|
+
if (cancelled) return;
|
|
806
|
+
const entries = chat.outbox.entries(conversationId);
|
|
807
|
+
setMessages((prev) => applyOutbox(prev, entries));
|
|
558
808
|
};
|
|
809
|
+
const offOutbox = chat.outbox.subscribe(syncOutbox);
|
|
810
|
+
const offSent = chat.outbox.onSent((entry, sent) => {
|
|
811
|
+
if (cancelled || entry.conversationId !== conversationId) return;
|
|
812
|
+
setMessages((prev) => upsertById(prev, sent));
|
|
813
|
+
});
|
|
559
814
|
const conv = chat.realtime.conversation(conversationId);
|
|
560
815
|
const offNew = conv.onMessage((msg) => {
|
|
561
816
|
if (msg.thread_root_id) {
|
|
@@ -594,7 +849,10 @@ function useMessages(conversationId) {
|
|
|
594
849
|
connectedBefore ||= wasConnected;
|
|
595
850
|
if (!reconnected || cancelled) return;
|
|
596
851
|
handle.list({ limit: PAGE_SIZE }).then((page) => {
|
|
597
|
-
if (!cancelled)
|
|
852
|
+
if (!cancelled) {
|
|
853
|
+
setMessages((prev) => mergeLatest(prev, page.data));
|
|
854
|
+
setFromCache(false);
|
|
855
|
+
}
|
|
598
856
|
}).catch(() => {
|
|
599
857
|
});
|
|
600
858
|
});
|
|
@@ -605,6 +863,8 @@ function useMessages(conversationId) {
|
|
|
605
863
|
offDeleted();
|
|
606
864
|
offThread();
|
|
607
865
|
offStatus();
|
|
866
|
+
offOutbox();
|
|
867
|
+
offSent();
|
|
608
868
|
};
|
|
609
869
|
}, [chat, conversationId]);
|
|
610
870
|
const loadMore = useCallback(async () => {
|
|
@@ -686,6 +946,12 @@ function useMessages(conversationId) {
|
|
|
686
946
|
inserted_at: (/* @__PURE__ */ new Date()).toISOString(),
|
|
687
947
|
updated_at: (/* @__PURE__ */ new Date()).toISOString()
|
|
688
948
|
};
|
|
949
|
+
if (chat.outboxEnabled) {
|
|
950
|
+
setMessages((prev) => upsertById(prev, { ...tempMsg, local_status: "sending" }));
|
|
951
|
+
const sent = await chat.outbox.send(conversationId, { ...attrs, id }, tempMsg);
|
|
952
|
+
setMessages((prev) => upsertById(prev, sent));
|
|
953
|
+
return sent;
|
|
954
|
+
}
|
|
689
955
|
setMessages((prev) => [...prev, tempMsg]);
|
|
690
956
|
try {
|
|
691
957
|
const sent = await chat.conversations.one(conversationId).messages.send({ ...attrs, id });
|
|
@@ -751,6 +1017,24 @@ function useMessages(conversationId) {
|
|
|
751
1017
|
},
|
|
752
1018
|
[chat, conversationId, conversationsStore]
|
|
753
1019
|
);
|
|
1020
|
+
const retry = useCallback(
|
|
1021
|
+
async (messageId) => {
|
|
1022
|
+
try {
|
|
1023
|
+
await chat.outbox.retry(messageId);
|
|
1024
|
+
} catch (err) {
|
|
1025
|
+
if (err instanceof MessageQueuedError) return;
|
|
1026
|
+
throw err;
|
|
1027
|
+
}
|
|
1028
|
+
},
|
|
1029
|
+
[chat]
|
|
1030
|
+
);
|
|
1031
|
+
const discard = useCallback(
|
|
1032
|
+
(messageId) => {
|
|
1033
|
+
chat.outbox.remove(messageId);
|
|
1034
|
+
setMessages((prev) => prev.filter((m) => m.id !== messageId || !m.local_status));
|
|
1035
|
+
},
|
|
1036
|
+
[chat]
|
|
1037
|
+
);
|
|
754
1038
|
const refetch = useCallback(async () => {
|
|
755
1039
|
const fn = refetchRef.current;
|
|
756
1040
|
if (!fn) return;
|
|
@@ -764,12 +1048,37 @@ function useMessages(conversationId) {
|
|
|
764
1048
|
loadMore,
|
|
765
1049
|
loadUntil,
|
|
766
1050
|
send,
|
|
1051
|
+
retry,
|
|
1052
|
+
discard,
|
|
767
1053
|
edit,
|
|
768
1054
|
delete: deleteMessage,
|
|
769
1055
|
markReadUpTo,
|
|
1056
|
+
fromCache,
|
|
770
1057
|
refetch
|
|
771
1058
|
};
|
|
772
1059
|
}
|
|
1060
|
+
function initialRows(chat, conversationId) {
|
|
1061
|
+
const cached = chat.cache.peekMessages(conversationId);
|
|
1062
|
+
return cached ? withOutbox(cached, chat, conversationId) : null;
|
|
1063
|
+
}
|
|
1064
|
+
function withOutbox(rows, chat, conversationId) {
|
|
1065
|
+
return applyOutbox(rows, chat.outbox.entries(conversationId));
|
|
1066
|
+
}
|
|
1067
|
+
function applyOutbox(prev, entries) {
|
|
1068
|
+
const byId = new Map(entries.map((e) => [e.id, e]));
|
|
1069
|
+
let next = prev.filter((m) => !m.local_status || byId.has(m.id));
|
|
1070
|
+
for (const entry of entries) {
|
|
1071
|
+
const idx = next.findIndex((m) => m.id === entry.id);
|
|
1072
|
+
if (idx !== -1 && !next[idx].local_status) continue;
|
|
1073
|
+
if (idx !== -1 && next[idx] === entry.message) continue;
|
|
1074
|
+
next = upsertById(next, entry.message);
|
|
1075
|
+
}
|
|
1076
|
+
return next.length === prev.length && next.every((m, i) => m === prev[i]) ? prev : next;
|
|
1077
|
+
}
|
|
1078
|
+
function keepLocal(page, prev) {
|
|
1079
|
+
const local = prev.filter((m) => m.local_status && !page.some((p) => p.id === m.id));
|
|
1080
|
+
return local.length === 0 ? page : [...page, ...local];
|
|
1081
|
+
}
|
|
773
1082
|
function patchById(prev, id, fn) {
|
|
774
1083
|
const idx = prev.findIndex((m) => m.id === id);
|
|
775
1084
|
if (idx === -1) return prev;
|
|
@@ -1769,6 +2078,6 @@ function canEditOwnMessage(args) {
|
|
|
1769
2078
|
return Number.isFinite(sent) && (args.now ?? Date.now()) - sent < EDIT_WINDOW_MS;
|
|
1770
2079
|
}
|
|
1771
2080
|
|
|
1772
|
-
export { EDIT_WINDOW_MS, PoolseProvider, canEditOwnMessage, computeGroupPosition, formatDayLabel, receiptsOf, sameDay, sameGroup, useAppEvent, useAttachmentUpload, useAttachmentUrl, useCallRoom, useConversation, useConversationPresence, useConversations, useLiveCall, useMe, useMembers, useMessageStreams, useMessages, usePoolse, usePresence, usePresenceMany, useReactions, useReadReceipts, useRealtimeStatus, useRoom, useThread, useTyping, useUser, useUserPresence };
|
|
2081
|
+
export { EDIT_WINDOW_MS, PoolseProvider, canEditOwnMessage, computeGroupPosition, filterConversations, formatDayLabel, orderUnread, receiptsOf, sameDay, sameGroup, useAppEvent, useAttachmentUpload, useAttachmentUrl, useCallRoom, useClientTimings, useConversation, useConversationPresence, useConversations, useLiveCall, useMe, useMembers, useMessageStreams, useMessages, useOutbox, usePoolse, usePresence, usePresenceMany, useReactions, useReadReceipts, useRealtimeStatus, useRoom, useThread, useTyping, useUnreadQueue, useUnreadTotals, useUser, useUserPresence };
|
|
1773
2082
|
//# sourceMappingURL=index.js.map
|
|
1774
2083
|
//# sourceMappingURL=index.js.map
|