@marktiderman/genesis-chat 0.11.4 → 0.13.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/README.md +162 -4
- package/dist/{chunk-ZQFREERR.js → chunk-3UNYTK62.js} +3 -3
- package/dist/{chunk-ZQFREERR.js.map → chunk-3UNYTK62.js.map} +1 -1
- package/dist/{chunk-5XYDVUPS.js → chunk-GEEJMKQF.js} +29 -4
- package/dist/chunk-GEEJMKQF.js.map +1 -0
- package/dist/{chunk-D4RPOYB7.js → chunk-H4BRVJJ7.js} +193 -30
- package/dist/chunk-H4BRVJJ7.js.map +1 -0
- package/dist/{chunk-O2QSBRSH.js → chunk-SEMN3S6Q.js} +3 -3
- package/dist/{chunk-O2QSBRSH.js.map → chunk-SEMN3S6Q.js.map} +1 -1
- package/dist/{client-DP7rhJ1U.d.ts → client-DXWyDJ2u.d.ts} +29 -0
- package/dist/index.d.ts +4 -4
- package/dist/index.js +3 -3
- package/dist/native.d.ts +355 -145
- package/dist/native.js +701 -217
- package/dist/native.js.map +1 -1
- package/dist/{outbox-C4LnqpKT.d.ts → outbox-Ctngv6Yz.d.ts} +1 -1
- package/dist/push.d.ts +2 -2
- package/dist/react.d.ts +83 -6
- package/dist/react.js +3 -3
- package/dist/server.d.ts +1 -1
- package/dist/server.js +1 -1
- package/dist/{thread-CSzdqNR_.d.ts → thread-mZsRiIGz.d.ts} +1 -1
- package/dist/web.d.ts +24 -7
- package/dist/web.js +140 -67
- package/dist/web.js.map +1 -1
- package/migrations/0006_genesis_chat_read_receipts.sql +110 -0
- package/migrations/0007_genesis_chat_unread_and_delete_for_me.sql +455 -0
- package/migrations/tests/0006_genesis_chat_read_receipts.test.sql +131 -0
- package/migrations/tests/0007_genesis_chat_unread_and_delete_for_me.test.sql +178 -0
- package/package.json +17 -9
- package/src/__tests__/inbox-row-actions.test.tsx +251 -0
- package/src/__tests__/unread-delete-for-me.test.ts +84 -0
- package/src/__tests__/web.test.tsx +5 -2
- package/src/core/client.ts +30 -1
- package/src/core/types.ts +7 -0
- package/src/native/__tests__/bubble-native-feel.test.tsx +153 -0
- package/src/native/__tests__/composer-attach-menu.test.tsx +47 -0
- package/src/native/__tests__/inbox-screen-actions.test.tsx +131 -0
- package/src/native/__tests__/inbox-screen.test.tsx +29 -1
- package/src/native/__tests__/media-cache-key.test.tsx +21 -0
- package/src/native/__tests__/organise-screens.test.tsx +2 -0
- package/src/native/__tests__/receipts.test.ts +95 -0
- package/src/native/__tests__/review-lows.test.tsx +80 -0
- package/src/native/__tests__/sheets-fit.test.tsx +45 -0
- package/src/native/__tests__/stable-hooks.test.tsx +68 -0
- package/src/native/__tests__/thread-layout.test.ts +2 -2
- package/src/native/__tests__/thread-screen-audit.test.tsx +248 -0
- package/src/native/__tests__/thread-screen.test.tsx +111 -0
- package/src/native/__tests__/thread-title.test.tsx +59 -0
- package/src/native/composer.tsx +61 -26
- package/src/native/copy.ts +47 -10
- package/src/native/emoji-picker.tsx +1 -1
- package/src/native/inbox-screen.tsx +52 -27
- package/src/native/index.ts +7 -2
- package/src/native/media.tsx +7 -1
- package/src/native/message-actions-sheet.tsx +1 -1
- package/src/native/message-bubble.tsx +171 -19
- package/src/native/modules.ts +3 -1
- package/src/native/receipts.ts +102 -0
- package/src/native/schedule-sheet.tsx +8 -3
- package/src/native/stack-options.ts +35 -3
- package/src/native/thread-screen.tsx +243 -17
- package/src/native/thread-times.tsx +89 -0
- package/src/native/thread-title.tsx +111 -0
- package/src/native/typing-bubble.tsx +85 -0
- package/src/react/inbox-actions.ts +121 -0
- package/src/react/index.tsx +172 -23
- package/src/web/inbox.tsx +120 -11
- package/src/web/index.ts +1 -1
- package/src/web/memory-client.ts +40 -7
- package/dist/chunk-5XYDVUPS.js.map +0 -1
- package/dist/chunk-D4RPOYB7.js.map +0 -1
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @feat:chat
|
|
3
|
+
* Someone typing, the way iMessage shows it: a bubble of three dots on the other side, at the
|
|
4
|
+
* bottom of the thread, under the newest message. In a group the typer's avatar sits beside it,
|
|
5
|
+
* as it does beside their messages. The dots pulse in turn (held still with Reduce Motion), and the
|
|
6
|
+
* bubble reads as the activity line ("Sam is typing…") to VoiceOver and TalkBack.
|
|
7
|
+
*/
|
|
8
|
+
import { useEffect, useRef } from "react";
|
|
9
|
+
import { AccessibilityInfo, Animated, Platform, View } from "react-native";
|
|
10
|
+
import { NativeAvatar } from "@marktiderman/genesis-ui-native/components";
|
|
11
|
+
import { useThemeRoles } from "@marktiderman/genesis-ui-native/hooks";
|
|
12
|
+
import { initials, useChatNative } from "./context";
|
|
13
|
+
|
|
14
|
+
export interface ChatTypingBubbleProps {
|
|
15
|
+
/** Read out: "Sam is typing…". */
|
|
16
|
+
label: string;
|
|
17
|
+
/** Who is typing (the first, in a group): their avatar shows beside the bubble. */
|
|
18
|
+
userId?: string | null;
|
|
19
|
+
group: boolean;
|
|
20
|
+
reducedMotion: boolean;
|
|
21
|
+
testID: string;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
const DOT = 8;
|
|
25
|
+
/** The least time between two "is typing" announcements on iOS. */
|
|
26
|
+
const ANNOUNCE_GAP_MS = 4000;
|
|
27
|
+
|
|
28
|
+
export function ChatTypingBubble({ label, userId, group, reducedMotion, testID }: ChatTypingBubbleProps) {
|
|
29
|
+
const colors = useThemeRoles();
|
|
30
|
+
const { person } = useChatNative();
|
|
31
|
+
const typer = userId ? person(userId) : null;
|
|
32
|
+
const dots = useRef([new Animated.Value(0.4), new Animated.Value(0.4), new Animated.Value(0.4)]).current;
|
|
33
|
+
|
|
34
|
+
// iOS has no live regions: VoiceOver hears who is typing when it changes, at most every few seconds.
|
|
35
|
+
const lastSaid = useRef<{ label: string; at: number } | null>(null);
|
|
36
|
+
useEffect(() => {
|
|
37
|
+
if (Platform.OS !== "ios") return;
|
|
38
|
+
const now = Date.now();
|
|
39
|
+
const last = lastSaid.current;
|
|
40
|
+
if (last && (last.label === label || now - last.at < ANNOUNCE_GAP_MS)) return;
|
|
41
|
+
lastSaid.current = { label, at: now };
|
|
42
|
+
(AccessibilityInfo as { announceForAccessibility?: (t: string) => void }).announceForAccessibility?.(label);
|
|
43
|
+
}, [label]);
|
|
44
|
+
|
|
45
|
+
useEffect(() => {
|
|
46
|
+
if (reducedMotion) {
|
|
47
|
+
dots.forEach((d) => d.setValue(0.6));
|
|
48
|
+
return;
|
|
49
|
+
}
|
|
50
|
+
// One loop per dot, each a beat behind the one before (a hold at the low point is the beat).
|
|
51
|
+
const pulses = dots.map((d, i) =>
|
|
52
|
+
Animated.loop(
|
|
53
|
+
Animated.sequence([
|
|
54
|
+
Animated.timing(d, { toValue: 0.4, duration: i * 160, useNativeDriver: true }),
|
|
55
|
+
Animated.timing(d, { toValue: 1, duration: 300, useNativeDriver: true }),
|
|
56
|
+
Animated.timing(d, { toValue: 0.4, duration: 300, useNativeDriver: true }),
|
|
57
|
+
Animated.timing(d, { toValue: 0.4, duration: (dots.length - 1 - i) * 160, useNativeDriver: true }),
|
|
58
|
+
]),
|
|
59
|
+
),
|
|
60
|
+
);
|
|
61
|
+
pulses.forEach((p) => p.start());
|
|
62
|
+
return () => pulses.forEach((p) => p.stop());
|
|
63
|
+
}, [dots, reducedMotion]);
|
|
64
|
+
|
|
65
|
+
return (
|
|
66
|
+
<View
|
|
67
|
+
testID={testID}
|
|
68
|
+
accessible
|
|
69
|
+
accessibilityLabel={label}
|
|
70
|
+
accessibilityLiveRegion="polite"
|
|
71
|
+
style={{ flexDirection: "row", alignItems: "flex-end", paddingTop: 8, paddingBottom: 6, paddingHorizontal: 8 }}
|
|
72
|
+
>
|
|
73
|
+
{group ? (
|
|
74
|
+
<View style={{ width: 40, alignItems: "flex-start" }}>
|
|
75
|
+
<NativeAvatar size={32} src={typer?.avatarUrl ?? null} fallback={initials(typer?.name)} alt={typer?.name} recyclingKey={userId ?? undefined} />
|
|
76
|
+
</View>
|
|
77
|
+
) : null}
|
|
78
|
+
<View testID={`${testID}-bubble`} style={{ flexDirection: "row", alignItems: "center", gap: 5, paddingHorizontal: 14, paddingVertical: 12, borderRadius: 18, backgroundColor: colors.surface }}>
|
|
79
|
+
{dots.map((opacity, i) => (
|
|
80
|
+
<Animated.View key={i} testID={`${testID}-dot-${i}`} style={{ width: DOT, height: DOT, borderRadius: DOT / 2, backgroundColor: colors.secondaryLabel, opacity }} />
|
|
81
|
+
))}
|
|
82
|
+
</View>
|
|
83
|
+
</View>
|
|
84
|
+
);
|
|
85
|
+
}
|
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The inbox's row actions, built once for web and native (`inboxRowActions`): Messages' Mark as
|
|
3
|
+
* Unread (or Read) and Pin to the leading side, Hide Alerts and Delete for me to the trailing one,
|
|
4
|
+
* Archive in the menu only. ChatInboxScreen (native) and ChatInbox (web) both take them, and an app
|
|
5
|
+
* reshapes them with `rowActions(item, defaults)`.
|
|
6
|
+
*
|
|
7
|
+
* The look is Messages': Unread blue (`info`), Pin orange, Hide Alerts purple, Delete red.
|
|
8
|
+
*/
|
|
9
|
+
import type { RowSwipeAction } from "@marktiderman/genesis-core/row-actions";
|
|
10
|
+
import type { ChatInboxItem } from "../core/types";
|
|
11
|
+
|
|
12
|
+
/** The words on the inbox's row actions, shared by the native copy and the web inbox. */
|
|
13
|
+
export interface ChatInboxActionLabels {
|
|
14
|
+
markRead: string;
|
|
15
|
+
/** Mark as Unread (migration 0007): only you see it. */
|
|
16
|
+
markUnread: string;
|
|
17
|
+
pin: string;
|
|
18
|
+
unpin: string;
|
|
19
|
+
/** Mute from the inbox row, as Messages names it. */
|
|
20
|
+
hideAlerts: string;
|
|
21
|
+
showAlerts: string;
|
|
22
|
+
archive: string;
|
|
23
|
+
/** Delete for me (migration 0007), and its confirmation. */
|
|
24
|
+
deleteConversation: string;
|
|
25
|
+
deleteConversationTitle: string;
|
|
26
|
+
deleteConversationBody: string;
|
|
27
|
+
/** The confirmation's Cancel. */
|
|
28
|
+
cancel: string;
|
|
29
|
+
/** A muted row's bell-slash, for a screen reader. */
|
|
30
|
+
alertsOff: string;
|
|
31
|
+
/** A pinned row's pin, for a screen reader. */
|
|
32
|
+
pinnedMark: string;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/** The English words, which the native copy starts from too. */
|
|
36
|
+
export const defaultInboxActionLabels: ChatInboxActionLabels = Object.freeze({
|
|
37
|
+
markRead: "Mark read",
|
|
38
|
+
markUnread: "Mark as Unread",
|
|
39
|
+
pin: "Pin",
|
|
40
|
+
unpin: "Unpin",
|
|
41
|
+
hideAlerts: "Hide Alerts",
|
|
42
|
+
showAlerts: "Show Alerts",
|
|
43
|
+
archive: "Archive",
|
|
44
|
+
deleteConversation: "Delete",
|
|
45
|
+
deleteConversationTitle: "Delete this conversation?",
|
|
46
|
+
deleteConversationBody:
|
|
47
|
+
"Its messages are removed for you and it leaves your inbox. Everyone else still sees them. A new message brings it back, with only what comes after.",
|
|
48
|
+
cancel: "Cancel",
|
|
49
|
+
alertsOff: "Alerts off",
|
|
50
|
+
pinnedMark: "Pinned",
|
|
51
|
+
});
|
|
52
|
+
|
|
53
|
+
/** Asks before a destructive action: resolves `true` to go ahead. Native passes an Alert, web a dialog. */
|
|
54
|
+
export type ChatConfirm = (title: string, body: string, confirmLabel: string) => Promise<boolean>;
|
|
55
|
+
|
|
56
|
+
/** What `useInboxActions` returns: your own actions on one inbox row, each the call's promise. */
|
|
57
|
+
export interface ChatInboxActions {
|
|
58
|
+
/** Mark as Read when it has unread messages, else Mark as Unread. */
|
|
59
|
+
toggleUnread: (item: ChatInboxItem) => Promise<unknown>;
|
|
60
|
+
togglePinned: (item: ChatInboxItem) => Promise<unknown>;
|
|
61
|
+
/** Show Alerts when muted, else Hide Alerts until `until` (default: until turned back on). */
|
|
62
|
+
toggleMuted: (item: ChatInboxItem, until?: string) => Promise<unknown>;
|
|
63
|
+
setArchived: (item: ChatInboxItem, archived: boolean) => Promise<unknown>;
|
|
64
|
+
/** Delete for me, up to the last message the row showed (`item.lastSeq`). */
|
|
65
|
+
deleteForMe: (item: ChatInboxItem) => Promise<unknown>;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
export interface InboxRowActionsOptions {
|
|
69
|
+
/** Asks before Delete for me. */
|
|
70
|
+
confirm: ChatConfirm;
|
|
71
|
+
/** A failed action: say so (an alert, a toast). Default: nothing. */
|
|
72
|
+
onError?: (error: unknown) => void;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/** One inbox row's actions: Messages' set, in its order and colors. */
|
|
76
|
+
export function inboxRowActions(item: ChatInboxItem, act: ChatInboxActions, labels: ChatInboxActionLabels, options: InboxRowActionsOptions): RowSwipeAction[] {
|
|
77
|
+
const run = (call: Promise<unknown>) => {
|
|
78
|
+
call.catch((error: unknown) => options.onError?.(error));
|
|
79
|
+
};
|
|
80
|
+
const unread = item.unread > 0;
|
|
81
|
+
return [
|
|
82
|
+
{
|
|
83
|
+
id: unread ? "read" : "unread",
|
|
84
|
+
label: unread ? labels.markRead : labels.markUnread,
|
|
85
|
+
icon: unread ? "mail-open" : "message-unread",
|
|
86
|
+
tone: "info",
|
|
87
|
+
swipe: { side: "leading", full: true },
|
|
88
|
+
onPress: () => run(act.toggleUnread(item)),
|
|
89
|
+
},
|
|
90
|
+
{
|
|
91
|
+
id: "pin",
|
|
92
|
+
label: item.pinned ? labels.unpin : labels.pin,
|
|
93
|
+
icon: "pin",
|
|
94
|
+
accent: "orange",
|
|
95
|
+
swipe: { side: "leading" },
|
|
96
|
+
onPress: () => run(act.togglePinned(item)),
|
|
97
|
+
},
|
|
98
|
+
{
|
|
99
|
+
id: "alerts",
|
|
100
|
+
label: item.muted ? labels.showAlerts : labels.hideAlerts,
|
|
101
|
+
icon: item.muted ? "bell" : "bell-off",
|
|
102
|
+
accent: "purple",
|
|
103
|
+
swipe: { side: "trailing" },
|
|
104
|
+
onPress: () => run(act.toggleMuted(item)),
|
|
105
|
+
},
|
|
106
|
+
{
|
|
107
|
+
id: "delete",
|
|
108
|
+
label: labels.deleteConversation,
|
|
109
|
+
icon: "trash",
|
|
110
|
+
destructive: true,
|
|
111
|
+
swipe: { side: "trailing", full: true },
|
|
112
|
+
// It asks first, so a full swipe can't delete by mistake.
|
|
113
|
+
confirms: true,
|
|
114
|
+
onPress: () =>
|
|
115
|
+
run(
|
|
116
|
+
options.confirm(labels.deleteConversationTitle, labels.deleteConversationBody, labels.deleteConversation).then((ok) => (ok ? act.deleteForMe(item) : undefined)),
|
|
117
|
+
),
|
|
118
|
+
},
|
|
119
|
+
...(item.archived ? [] : [{ id: "archive", label: labels.archive, icon: "archive", swipe: false as const, onPress: () => run(act.setArchived(item, true)) }]),
|
|
120
|
+
];
|
|
121
|
+
}
|
package/src/react/index.tsx
CHANGED
|
@@ -5,7 +5,8 @@
|
|
|
5
5
|
* Realtime hints, sending through the outbox, and message actions. Server
|
|
6
6
|
* state is TanStack Query's; the renderers in /web and /native only draw.
|
|
7
7
|
*/
|
|
8
|
-
import { useQueries, useQuery, useQueryClient } from "@tanstack/react-query";
|
|
8
|
+
import { keepPreviousData, useQueries, useQuery, useQueryClient, type QueryClient } from "@tanstack/react-query";
|
|
9
|
+
import type { ChatInboxActions } from "./inbox-actions";
|
|
9
10
|
import { createContext, useCallback, useContext, useEffect, useMemo, useRef, useState, type ReactNode } from "react";
|
|
10
11
|
import type { ChatClient, ConversationChannel, MessagePage } from "../core/client";
|
|
11
12
|
import {
|
|
@@ -26,6 +27,7 @@ import type {
|
|
|
26
27
|
ChatAttachment,
|
|
27
28
|
ChatAvailability,
|
|
28
29
|
ChatLinkPreview,
|
|
30
|
+
ChatMember,
|
|
29
31
|
ChatMessage,
|
|
30
32
|
ChatSearchHit,
|
|
31
33
|
ChatSignal,
|
|
@@ -39,6 +41,8 @@ import type {
|
|
|
39
41
|
|
|
40
42
|
export const chatKeys = {
|
|
41
43
|
all: ["genesis-chat"] as const,
|
|
44
|
+
/** Every inbox list (each `inbox(opts)` is under it). */
|
|
45
|
+
inboxAll: () => ["genesis-chat", "inbox"] as const,
|
|
42
46
|
inbox: (opts?: object) => ["genesis-chat", "inbox", opts ?? {}] as const,
|
|
43
47
|
unread: () => ["genesis-chat", "unread"] as const,
|
|
44
48
|
conversation: (id: string) => ["genesis-chat", "conversation", id] as const,
|
|
@@ -51,12 +55,44 @@ export const chatKeys = {
|
|
|
51
55
|
scheduled: (conversationId?: string | null) => ["genesis-chat", "scheduled", conversationId ?? null] as const,
|
|
52
56
|
availability: (conversationId: string) => ["genesis-chat", "conversation", conversationId, "availability"] as const,
|
|
53
57
|
myAvailability: () => ["genesis-chat", "my-availability"] as const,
|
|
58
|
+
/** Every search's results (each `search(query, id)` is under it). */
|
|
59
|
+
searchAll: () => ["genesis-chat", "search"] as const,
|
|
54
60
|
search: (query: string, conversationId?: string | null) => ["genesis-chat", "search", conversationId ?? null, query] as const,
|
|
55
61
|
previews: (messageIds: string[]) => ["genesis-chat", "previews", [...messageIds].sort()] as const,
|
|
56
62
|
/** One message's link previews (useLinkPreviews keeps one query per message). */
|
|
57
63
|
preview: (messageId: string) => ["genesis-chat", "preview", messageId] as const,
|
|
58
64
|
};
|
|
59
65
|
|
|
66
|
+
/** Refreshes every inbox list and the unread badge: after anything that changes a row. */
|
|
67
|
+
function refreshInbox(queryClient: QueryClient): void {
|
|
68
|
+
void queryClient.invalidateQueries({ queryKey: chatKeys.inboxAll() });
|
|
69
|
+
void queryClient.invalidateQueries({ queryKey: chatKeys.unread() });
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/**
|
|
73
|
+
* How many times each conversation has been forgotten, per query cache. A load (a catch-up, a
|
|
74
|
+
* live message, an earlier page) captures it when it starts and writes nothing if it changed, so
|
|
75
|
+
* a fetch already under way when the conversation was deleted can't put its history back. Loads
|
|
76
|
+
* started afterwards write as usual.
|
|
77
|
+
*/
|
|
78
|
+
const forgotten = new WeakMap<QueryClient, Map<string, number>>();
|
|
79
|
+
function generationOf(queryClient: QueryClient, conversationId: string): number {
|
|
80
|
+
return forgotten.get(queryClient)?.get(conversationId) ?? 0;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/** Drops what this device holds of a conversation (its thread, pins and every search), so deleted history can't show again. */
|
|
84
|
+
function forgetConversation(queryClient: QueryClient, conversationId: string): void {
|
|
85
|
+
let byId = forgotten.get(queryClient);
|
|
86
|
+
if (!byId) forgotten.set(queryClient, (byId = new Map()));
|
|
87
|
+
byId.set(conversationId, generationOf(queryClient, conversationId) + 1);
|
|
88
|
+
queryClient.removeQueries({ queryKey: chatKeys.conversation(conversationId) });
|
|
89
|
+
queryClient.removeQueries({ queryKey: chatKeys.pins(conversationId) });
|
|
90
|
+
queryClient.removeQueries({ queryKey: chatKeys.searchAll() });
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/** Hide Alerts from the row: until it's turned back on (a date far enough away to read as always). */
|
|
94
|
+
const MUTED_FOREVER = "9999-12-31T00:00:00.000Z";
|
|
95
|
+
|
|
60
96
|
/** How many messages a catch-up asks for at a time, and how many pages before it gives up and jumps to the newest. */
|
|
61
97
|
export const CATCH_UP_PAGE = 200;
|
|
62
98
|
export const CATCH_UP_MAX_PAGES = 10;
|
|
@@ -252,7 +288,7 @@ export function ChatProvider({
|
|
|
252
288
|
(prev) => upsertInto(prev, [message]) ?? prev,
|
|
253
289
|
);
|
|
254
290
|
void queryClient.invalidateQueries({ queryKey: ["genesis-chat", "scheduled"] });
|
|
255
|
-
|
|
291
|
+
refreshInbox(queryClient);
|
|
256
292
|
},
|
|
257
293
|
}),
|
|
258
294
|
// A new person or client is a new outbox.
|
|
@@ -268,8 +304,7 @@ export function ChatProvider({
|
|
|
268
304
|
const target = typeof window !== "undefined" && typeof window.addEventListener === "function" ? window : null;
|
|
269
305
|
target?.addEventListener("online", online);
|
|
270
306
|
const sub = client.subscribeInbox(userId, (signal) => {
|
|
271
|
-
|
|
272
|
-
void queryClient.invalidateQueries({ queryKey: chatKeys.unread() });
|
|
307
|
+
refreshInbox(queryClient);
|
|
273
308
|
for (const l of listeners.current) l(signal);
|
|
274
309
|
});
|
|
275
310
|
return () => {
|
|
@@ -332,6 +367,9 @@ export interface UseConversationOptions {
|
|
|
332
367
|
}
|
|
333
368
|
|
|
334
369
|
/** One conversation: its messages (with what you are still sending), members, your role, and who is typing. */
|
|
370
|
+
/** How long a `read` hint waits for others before the members are read again. */
|
|
371
|
+
const READ_REFETCH_MS = 300;
|
|
372
|
+
|
|
335
373
|
export function useConversation(conversationId: string | null | undefined, opts: UseConversationOptions = {}) {
|
|
336
374
|
const { client, userId, outbox, queue } = useChat();
|
|
337
375
|
const queryClient = useQueryClient();
|
|
@@ -368,14 +406,35 @@ export function useConversation(conversationId: string | null | undefined, opts:
|
|
|
368
406
|
const hasEarlier = messages.data?.hasEarlier ?? false;
|
|
369
407
|
// Where "New" goes: what you had read when the conversation opened.
|
|
370
408
|
const [readWhenOpened, setReadWhenOpened] = useState<number | null>(null);
|
|
409
|
+
// Another conversation in the same screen (a split view, no remount) opens at its own read place:
|
|
410
|
+
// forget the last one's, and read this one's members afresh (a cached copy may be from an earlier visit).
|
|
411
|
+
const [openedFor, setOpenedFor] = useState(id);
|
|
412
|
+
if (openedFor !== id) {
|
|
413
|
+
setOpenedFor(id);
|
|
414
|
+
setReadWhenOpened(null);
|
|
415
|
+
}
|
|
416
|
+
const { refetch: refetchMembers } = members;
|
|
417
|
+
const firstId = useRef(id);
|
|
418
|
+
useEffect(() => {
|
|
419
|
+
if (firstId.current === id) return;
|
|
420
|
+
firstId.current = id;
|
|
421
|
+
if (enabled) void refetchMembers();
|
|
422
|
+
}, [id, enabled, refetchMembers]);
|
|
371
423
|
|
|
424
|
+
/**
|
|
425
|
+
* Merges messages into the list. `since` is the conversation's forget generation when the load
|
|
426
|
+
* began (see forgetConversation): when it has moved on, the load predates a Delete for me and
|
|
427
|
+
* writes nothing.
|
|
428
|
+
*/
|
|
372
429
|
const merge = useCallback(
|
|
373
|
-
(incoming: ChatMessage[], hasEarlierNow?: boolean) =>
|
|
430
|
+
(incoming: ChatMessage[], hasEarlierNow?: boolean, since = generationOf(queryClient, id)) => {
|
|
431
|
+
if (generationOf(queryClient, id) !== since) return;
|
|
374
432
|
queryClient.setQueryData<MessagesData>(messagesKey, (prev) => {
|
|
375
433
|
const base = prev ?? { messages: [], hasEarlier: false };
|
|
376
434
|
return { messages: upsertMessages(base.messages, incoming), hasEarlier: hasEarlierNow ?? base.hasEarlier };
|
|
377
|
-
})
|
|
378
|
-
|
|
435
|
+
});
|
|
436
|
+
},
|
|
437
|
+
[queryClient, messagesKey, id],
|
|
379
438
|
);
|
|
380
439
|
|
|
381
440
|
/**
|
|
@@ -386,39 +445,56 @@ export function useConversation(conversationId: string | null | undefined, opts:
|
|
|
386
445
|
* it shows the newest page instead, with the rest behind "load earlier".
|
|
387
446
|
*/
|
|
388
447
|
const catchUp = useCallback(async () => {
|
|
448
|
+
const since = generationOf(queryClient, id);
|
|
389
449
|
const current = queryClient.getQueryData<MessagesData>(messagesKey) ?? (await queryClient.ensureQueryData<MessagesData>({ queryKey: messagesKey, queryFn: fetchPage }));
|
|
390
450
|
const list = current.messages;
|
|
391
451
|
let after = list.length ? list[list.length - 1]!.seq : 0;
|
|
392
452
|
for (let pages = 0; ; ) {
|
|
393
453
|
const page = await client.messages(id, { afterSeq: after, limit: CATCH_UP_PAGE, threadRootId: opts.threadRootId, topic: opts.topic });
|
|
394
|
-
if (
|
|
454
|
+
if (generationOf(queryClient, id) !== since) return;
|
|
455
|
+
if (page.messages.length) merge(page.messages, undefined, since);
|
|
395
456
|
if (page.messages.length < CATCH_UP_PAGE) return;
|
|
396
457
|
after = Math.max(after, ...page.messages.map((m) => m.seq));
|
|
397
458
|
if (++pages >= CATCH_UP_MAX_PAGES) break;
|
|
398
459
|
}
|
|
399
460
|
const newest = await fetchPage();
|
|
461
|
+
if (generationOf(queryClient, id) !== since) return;
|
|
400
462
|
queryClient.setQueryData<MessagesData>(messagesKey, { messages: newest.messages, hasEarlier: true });
|
|
401
463
|
}, [client, fetchPage, id, merge, messagesKey, opts.threadRootId, opts.topic, queryClient]);
|
|
402
464
|
|
|
403
465
|
const [activity, setActivity] = useState<ChatActivity[]>([]);
|
|
404
466
|
const channel = useRef<ConversationChannel | null>(null);
|
|
467
|
+
// Whether the live channel is joined: null until the client first says, false when it dropped.
|
|
468
|
+
const [live, setLive] = useState<boolean | null>(null);
|
|
405
469
|
useEffect(() => {
|
|
406
470
|
if (!enabled) return;
|
|
471
|
+
setLive(null);
|
|
407
472
|
const fetchOne = async (messageId: string) => {
|
|
473
|
+
const since = generationOf(queryClient, id);
|
|
408
474
|
const m = await client.message(messageId);
|
|
409
475
|
if (!m) return;
|
|
410
476
|
const belongs = opts.threadRootId ? m.threadRootId === opts.threadRootId : m.threadRootId === null;
|
|
411
|
-
if (belongs && (!opts.topic || m.topic === opts.topic)) merge([m]);
|
|
477
|
+
if (belongs && (!opts.topic || m.topic === opts.topic)) merge([m], undefined, since);
|
|
412
478
|
if (m.threadRootId && !opts.threadRootId) {
|
|
413
479
|
const root = await client.message(m.threadRootId);
|
|
414
|
-
if (root) merge([root]);
|
|
480
|
+
if (root) merge([root], undefined, since);
|
|
415
481
|
}
|
|
416
482
|
};
|
|
483
|
+
let readRefetch: ReturnType<typeof setTimeout> | null = null;
|
|
417
484
|
channel.current = client.subscribeConversation(id, userId, {
|
|
418
485
|
onSignal: (s) => {
|
|
419
486
|
if (s.type === "message") void fetchOne(s.id);
|
|
420
487
|
else if (s.type === "reaction") void fetchOne(s.messageId);
|
|
421
|
-
else if (s.type === "
|
|
488
|
+
else if (s.type === "read") {
|
|
489
|
+
// Read receipts: a cue to read the members again, never the read place itself (a payload
|
|
490
|
+
// is only as good as whoever sent it). Coalesced, so a burst of reads is one fetch.
|
|
491
|
+
if (readRefetch === null) {
|
|
492
|
+
readRefetch = setTimeout(() => {
|
|
493
|
+
readRefetch = null;
|
|
494
|
+
void queryClient.invalidateQueries({ queryKey: chatKeys.members(id) });
|
|
495
|
+
}, READ_REFETCH_MS);
|
|
496
|
+
}
|
|
497
|
+
} else if (s.type === "members") {
|
|
422
498
|
void queryClient.invalidateQueries({ queryKey: chatKeys.members(id) });
|
|
423
499
|
void queryClient.invalidateQueries({ queryKey: chatKeys.role(id) });
|
|
424
500
|
} else if (s.type === "conversation") {
|
|
@@ -429,9 +505,15 @@ export function useConversation(conversationId: string | null | undefined, opts:
|
|
|
429
505
|
}
|
|
430
506
|
},
|
|
431
507
|
onActivity: (a) => setActivity((prev) => currentActivity([...prev, a])),
|
|
432
|
-
|
|
508
|
+
// Every join: what was missed while the channel was down, messages and read places both.
|
|
509
|
+
onJoin: () => {
|
|
510
|
+
void catchUp().catch(() => undefined);
|
|
511
|
+
void queryClient.invalidateQueries({ queryKey: chatKeys.members(id) });
|
|
512
|
+
},
|
|
513
|
+
onLive: setLive,
|
|
433
514
|
});
|
|
434
515
|
return () => {
|
|
516
|
+
if (readRefetch) clearTimeout(readRefetch);
|
|
435
517
|
channel.current?.unsubscribe();
|
|
436
518
|
channel.current = null;
|
|
437
519
|
};
|
|
@@ -456,8 +538,7 @@ export function useConversation(conversationId: string | null | undefined, opts:
|
|
|
456
538
|
const markRead = useCallback(async () => {
|
|
457
539
|
if (!enabled || latestSeq === 0) return;
|
|
458
540
|
await client.markRead(id, latestSeq);
|
|
459
|
-
|
|
460
|
-
void queryClient.invalidateQueries({ queryKey: chatKeys.unread() });
|
|
541
|
+
refreshInbox(queryClient);
|
|
461
542
|
}, [client, enabled, id, latestSeq, queryClient]);
|
|
462
543
|
|
|
463
544
|
// Your read place is one number for the whole conversation, so only the whole timeline moves
|
|
@@ -482,21 +563,30 @@ export function useConversation(conversationId: string | null | undefined, opts:
|
|
|
482
563
|
[queryClient, id],
|
|
483
564
|
);
|
|
484
565
|
|
|
566
|
+
const { refetch: refetchMessages } = messages;
|
|
567
|
+
const { refetch: refetchConversationRow } = conversation;
|
|
568
|
+
const reload = useCallback(
|
|
569
|
+
() => Promise.all([refetchConversationRow(), refetchMessages()]).then(() => undefined),
|
|
570
|
+
[refetchConversationRow, refetchMessages],
|
|
571
|
+
);
|
|
572
|
+
|
|
485
573
|
const loadEarlier = useCallback(async () => {
|
|
486
574
|
const first = list[0];
|
|
487
575
|
if (!first || loadingEarlier) return;
|
|
488
576
|
setLoadingEarlier(true);
|
|
577
|
+
const since = generationOf(queryClient, id);
|
|
489
578
|
try {
|
|
490
579
|
const page = await client.messages(id, { beforeSeq: first.seq, limit: pageSize, threadRootId: opts.threadRootId, topic: opts.topic });
|
|
491
|
-
merge(page.messages, page.hasEarlier);
|
|
580
|
+
merge(page.messages, page.hasEarlier, since);
|
|
492
581
|
} finally {
|
|
493
582
|
setLoadingEarlier(false);
|
|
494
583
|
}
|
|
495
|
-
}, [client, id, list, loadingEarlier, merge, opts.threadRootId, opts.topic, pageSize]);
|
|
584
|
+
}, [client, id, list, loadingEarlier, merge, opts.threadRootId, opts.topic, pageSize, queryClient]);
|
|
496
585
|
|
|
497
586
|
/** Loads earlier messages until the one with this seq is held (a search result, a pinned message). True when it is. */
|
|
498
587
|
const loadUntil = useCallback(
|
|
499
588
|
async (seq: number) => {
|
|
589
|
+
const since = generationOf(queryClient, id);
|
|
500
590
|
let current = queryClient.getQueryData<MessagesData>(messagesKey);
|
|
501
591
|
for (let guard = 0; guard < 20 && current; guard++) {
|
|
502
592
|
const first = current.messages[0];
|
|
@@ -507,7 +597,8 @@ export function useConversation(conversationId: string | null | undefined, opts:
|
|
|
507
597
|
threadRootId: opts.threadRootId,
|
|
508
598
|
topic: opts.topic,
|
|
509
599
|
});
|
|
510
|
-
|
|
600
|
+
if (generationOf(queryClient, id) !== since) return false;
|
|
601
|
+
merge(page.messages, page.hasEarlier, since);
|
|
511
602
|
current = queryClient.getQueryData<MessagesData>(messagesKey);
|
|
512
603
|
}
|
|
513
604
|
return Boolean(current?.messages.some((m) => m.seq === seq));
|
|
@@ -575,6 +666,8 @@ export function useConversation(conversationId: string | null | undefined, opts:
|
|
|
575
666
|
loadUntil,
|
|
576
667
|
/** Where to draw the "New" line, from what you had read when it opened. */
|
|
577
668
|
firstUnreadId: readWhenOpened === null ? null : firstUnreadId(list, readWhenOpened, userId),
|
|
669
|
+
/** Whether `firstUnreadId` is known yet (your read place as of this opening has been fetched). */
|
|
670
|
+
firstUnreadKnown: readWhenOpened !== null,
|
|
578
671
|
activity: currentActivity(activity),
|
|
579
672
|
signalTyping,
|
|
580
673
|
signalRecording,
|
|
@@ -585,6 +678,10 @@ export function useConversation(conversationId: string | null | undefined, opts:
|
|
|
585
678
|
retry: outbox.retry,
|
|
586
679
|
discard: outbox.discard,
|
|
587
680
|
refetch: catchUp,
|
|
681
|
+
/** The conversation and its first page again, after either failed (a Retry on the thread's error row). */
|
|
682
|
+
reload,
|
|
683
|
+
/** The live channel: true once joined, false when it dropped (errored, timed out, closed), null until the client says. */
|
|
684
|
+
live,
|
|
588
685
|
};
|
|
589
686
|
}
|
|
590
687
|
|
|
@@ -624,6 +721,48 @@ export function useMessageActions() {
|
|
|
624
721
|
}, [client, queryClient]);
|
|
625
722
|
}
|
|
626
723
|
|
|
724
|
+
/**
|
|
725
|
+
* Your own actions on one inbox row (Mark as Unread or Read, Pin, Hide Alerts, Archive, Delete for
|
|
726
|
+
* me), refreshing the inbox and badge afterwards. Each takes the row's item and returns the call's
|
|
727
|
+
* promise, so a failure reaches the caller to show. Delete for me reads the row's `lastSeq` (what
|
|
728
|
+
* you saw) and drops the conversation's cached thread, pins and search results, so its deleted
|
|
729
|
+
* history can't show again on this device when a new message brings it back.
|
|
730
|
+
* `inboxRowActions(item, actions, labels, { confirm })` turns them into the row's swipe and menu.
|
|
731
|
+
*/
|
|
732
|
+
export function useInboxActions(): ChatInboxActions {
|
|
733
|
+
const { client } = useChat();
|
|
734
|
+
const queryClient = useQueryClient();
|
|
735
|
+
return useMemo(() => {
|
|
736
|
+
const run = async <T,>(call: () => Promise<T>): Promise<T> => {
|
|
737
|
+
try {
|
|
738
|
+
return await call();
|
|
739
|
+
} finally {
|
|
740
|
+
refreshInbox(queryClient);
|
|
741
|
+
}
|
|
742
|
+
};
|
|
743
|
+
return {
|
|
744
|
+
toggleUnread: (item) =>
|
|
745
|
+
run<unknown>(() => (item.unread > 0 ? client.markRead(item.conversationId) : client.setMySettings(item.conversationId, { markedUnread: true }))),
|
|
746
|
+
togglePinned: (item) => run(() => client.setMySettings(item.conversationId, { pinned: !item.pinned })),
|
|
747
|
+
toggleMuted: (item, until = MUTED_FOREVER) => run(() => client.setMySettings(item.conversationId, { mutedUntil: item.muted ? null : until })),
|
|
748
|
+
setArchived: (item, archived) => run(() => client.setMySettings(item.conversationId, { archived })),
|
|
749
|
+
deleteForMe: (item) =>
|
|
750
|
+
run(async () => {
|
|
751
|
+
await client.deleteConversationForMe(item.conversationId, item.lastSeq);
|
|
752
|
+
forgetConversation(queryClient, item.conversationId);
|
|
753
|
+
}),
|
|
754
|
+
};
|
|
755
|
+
}, [client, queryClient]);
|
|
756
|
+
}
|
|
757
|
+
|
|
758
|
+
/**
|
|
759
|
+
* What the read hooks return while there is nothing yet: one frozen object (and array) for every
|
|
760
|
+
* caller, so a row's memo holds across renders instead of seeing a fresh `{}` each time.
|
|
761
|
+
*/
|
|
762
|
+
const NO_PEOPLE: Record<string, ChatPerson> = Object.freeze({}) as Record<string, ChatPerson>;
|
|
763
|
+
const NO_URLS: Record<string, string> = Object.freeze({}) as Record<string, string>;
|
|
764
|
+
const NO_PINS: string[] = Object.freeze([]) as unknown as string[];
|
|
765
|
+
|
|
627
766
|
/**
|
|
628
767
|
* Names and avatars for these people, from the provider's `loadPeople`, fetched as one
|
|
629
768
|
* batch per set of ids and cached. Unknown ids are left out.
|
|
@@ -637,7 +776,7 @@ export function usePeople(userIds: (string | null | undefined)[]): Record<string
|
|
|
637
776
|
queryFn: () => loadPeople!(ids),
|
|
638
777
|
enabled: Boolean(loadPeople) && ids.length > 0,
|
|
639
778
|
staleTime: 5 * 60_000,
|
|
640
|
-
}).data ??
|
|
779
|
+
}).data ?? NO_PEOPLE
|
|
641
780
|
);
|
|
642
781
|
}
|
|
643
782
|
|
|
@@ -651,16 +790,25 @@ export function usePerson(userId: string | null | undefined): ChatPerson | null
|
|
|
651
790
|
export function usePins(conversationId: string | null | undefined): string[] {
|
|
652
791
|
const { client } = useChat();
|
|
653
792
|
return (
|
|
654
|
-
useQuery({ queryKey: chatKeys.pins(conversationId ?? ""), queryFn: () => client.pins(conversationId!), enabled: Boolean(conversationId) }).data ??
|
|
793
|
+
useQuery({ queryKey: chatKeys.pins(conversationId ?? ""), queryFn: () => client.pins(conversationId!), enabled: Boolean(conversationId) }).data ?? NO_PINS
|
|
655
794
|
);
|
|
656
795
|
}
|
|
657
796
|
|
|
658
|
-
/**
|
|
797
|
+
/**
|
|
798
|
+
* Signed links for files (cached by the client until shortly before they expire). While a new set
|
|
799
|
+
* of paths loads (a photo arrives), the links already signed stay: the photos on screen don't blank.
|
|
800
|
+
*/
|
|
659
801
|
export function useFileUrls(paths: (string | null | undefined)[]): Record<string, string> {
|
|
660
802
|
const { client } = useChat();
|
|
661
803
|
const list = useMemo(() => [...new Set(paths.filter((p): p is string => Boolean(p)))], [paths]);
|
|
662
804
|
return (
|
|
663
|
-
useQuery({
|
|
805
|
+
useQuery({
|
|
806
|
+
queryKey: chatKeys.files(list),
|
|
807
|
+
queryFn: () => client.fileUrls(list),
|
|
808
|
+
enabled: list.length > 0,
|
|
809
|
+
staleTime: 50 * 60_000,
|
|
810
|
+
placeholderData: keepPreviousData,
|
|
811
|
+
}).data ?? NO_URLS
|
|
664
812
|
);
|
|
665
813
|
}
|
|
666
814
|
|
|
@@ -671,7 +819,7 @@ export function useStartConversation() {
|
|
|
671
819
|
return useCallback(
|
|
672
820
|
async (kind: string, memberIds: string[], opts?: StartConversationOptions) => {
|
|
673
821
|
const id = await client.startConversation(kind, memberIds, opts);
|
|
674
|
-
|
|
822
|
+
refreshInbox(queryClient);
|
|
675
823
|
return id;
|
|
676
824
|
},
|
|
677
825
|
[client, queryClient],
|
|
@@ -790,7 +938,7 @@ export function useBroadcast() {
|
|
|
790
938
|
setSending(true);
|
|
791
939
|
try {
|
|
792
940
|
const ids = await client.broadcast(conversationIds, opts.clientId ?? randomId(), body, { silent: opts.silent });
|
|
793
|
-
|
|
941
|
+
refreshInbox(queryClient);
|
|
794
942
|
return ids;
|
|
795
943
|
} finally {
|
|
796
944
|
setSending(false);
|
|
@@ -897,3 +1045,4 @@ export function useLinkPreviews(messageIds: (string | null | undefined)[]): Reco
|
|
|
897
1045
|
const EMPTY_PREVIEWS: Record<string, ChatLinkPreview[]> = {};
|
|
898
1046
|
|
|
899
1047
|
export type { ThreadItem, LocalFile, QueuedMessage };
|
|
1048
|
+
export { defaultInboxActionLabels, inboxRowActions, type ChatConfirm, type ChatInboxActionLabels, type ChatInboxActions, type InboxRowActionsOptions } from "./inbox-actions";
|