@marktiderman/genesis-chat 0.12.0 → 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 +46 -1
- package/dist/{chunk-2HNQWDLF.js → chunk-3UNYTK62.js} +3 -3
- package/dist/{chunk-2HNQWDLF.js.map → chunk-3UNYTK62.js.map} +1 -1
- package/dist/{chunk-VBIYDXL2.js → chunk-GEEJMKQF.js} +22 -3
- package/dist/chunk-GEEJMKQF.js.map +1 -0
- package/dist/{chunk-K5GYNHNE.js → chunk-H4BRVJJ7.js} +136 -23
- package/dist/chunk-H4BRVJJ7.js.map +1 -0
- package/dist/{chunk-3HQN2FZ5.js → chunk-SEMN3S6Q.js} +3 -3
- package/dist/{chunk-3HQN2FZ5.js.map → chunk-SEMN3S6Q.js.map} +1 -1
- package/dist/{client-DJs3ltZc.d.ts → client-DXWyDJ2u.d.ts} +14 -0
- package/dist/index.d.ts +4 -4
- package/dist/index.js +3 -3
- package/dist/native.d.ts +20 -12
- package/dist/native.js +40 -32
- package/dist/native.js.map +1 -1
- package/dist/{outbox-YFTbGIAl.d.ts → outbox-Ctngv6Yz.d.ts} +1 -1
- package/dist/push.d.ts +2 -2
- package/dist/react.d.ts +73 -4
- package/dist/react.js +3 -3
- package/dist/server.d.ts +1 -1
- package/dist/server.js +1 -1
- package/dist/{thread-CgHP00Jw.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/0007_genesis_chat_unread_and_delete_for_me.sql +455 -0
- package/migrations/tests/0007_genesis_chat_unread_and_delete_for_me.test.sql +178 -0
- package/package.json +13 -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 +21 -1
- 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__/thread-layout.test.ts +2 -2
- package/src/native/copy.ts +7 -10
- package/src/native/inbox-screen.tsx +52 -27
- package/src/native/index.ts +1 -1
- package/src/react/inbox-actions.ts +121 -0
- package/src/react/index.tsx +99 -17
- 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-K5GYNHNE.js.map +0 -1
- package/dist/chunk-VBIYDXL2.js.map +0 -1
package/src/native/copy.ts
CHANGED
|
@@ -3,10 +3,14 @@
|
|
|
3
3
|
* Every word the native chat screens say, in one catalog an app can override
|
|
4
4
|
* (translate, rename "Message" to "Note"). `{name}` and `{count}` are filled in.
|
|
5
5
|
*/
|
|
6
|
+
import { defaultInboxActionLabels, type ChatInboxActionLabels } from "../react/inbox-actions";
|
|
6
7
|
import { chatOrganiseCopy, type ChatOrganiseCopy } from "./organise-copy";
|
|
7
8
|
|
|
8
|
-
/**
|
|
9
|
-
|
|
9
|
+
/**
|
|
10
|
+
* Topics, scheduled send, availability, broadcast, search and moderation are in `ChatOrganiseCopy`;
|
|
11
|
+
* the inbox row actions' words in `ChatInboxActionLabels`, shared with the web inbox.
|
|
12
|
+
*/
|
|
13
|
+
export interface ChatNativeCopy extends ChatOrganiseCopy, ChatInboxActionLabels {
|
|
10
14
|
inboxTitle: string;
|
|
11
15
|
inboxEmptyTitle: string;
|
|
12
16
|
inboxEmptyBody: string;
|
|
@@ -18,10 +22,6 @@ export interface ChatNativeCopy extends ChatOrganiseCopy {
|
|
|
18
22
|
someone: string;
|
|
19
23
|
youPrefix: string;
|
|
20
24
|
mentionedYou: string;
|
|
21
|
-
markRead: string;
|
|
22
|
-
pin: string;
|
|
23
|
-
unpin: string;
|
|
24
|
-
archive: string;
|
|
25
25
|
threadEmptyTitle: string;
|
|
26
26
|
threadEmptyBody: string;
|
|
27
27
|
/** The conversation or its first page couldn't be read, and there's nothing to show. */
|
|
@@ -197,10 +197,7 @@ export const chatNativeCopy: ChatNativeCopy = {
|
|
|
197
197
|
someone: "Someone",
|
|
198
198
|
youPrefix: "You: ",
|
|
199
199
|
mentionedYou: "Mentioned you",
|
|
200
|
-
|
|
201
|
-
pin: "Pin",
|
|
202
|
-
unpin: "Unpin",
|
|
203
|
-
archive: "Archive",
|
|
200
|
+
...defaultInboxActionLabels,
|
|
204
201
|
threadEmptyTitle: "No messages yet",
|
|
205
202
|
threadEmptyBody: "Say hello below.",
|
|
206
203
|
threadErrorTitle: "Couldn't load messages",
|
|
@@ -2,17 +2,19 @@
|
|
|
2
2
|
* @feat:chat
|
|
3
3
|
* Your conversations on genesis-ui-native's InboxPage: each with its avatar,
|
|
4
4
|
* unread count, last message and time; pull to refresh; an empty state that
|
|
5
|
-
* offers to start a conversation
|
|
6
|
-
*
|
|
7
|
-
*
|
|
5
|
+
* offers to start a conversation. Each row has Messages' actions: swipe right for Mark as
|
|
6
|
+
* Unread (or Read) and Pin, left for Hide Alerts and Delete (for you, after asking); Archive
|
|
7
|
+
* is in the long-press menu. Every action is also a screen reader action on the row. Under the
|
|
8
|
+
* navigator's large title (`getInboxPageStackOptions`).
|
|
8
9
|
*/
|
|
9
10
|
import { useCallback, useMemo, useState } from "react";
|
|
11
|
+
import { Alert } from "react-native";
|
|
12
|
+
import type { RowSwipeAction } from "@marktiderman/genesis-core/row-actions";
|
|
10
13
|
import { NativeAvatar } from "@marktiderman/genesis-ui-native/components";
|
|
11
14
|
import { InboxPage, type InboxItem, type InboxPageProps } from "@marktiderman/genesis-ui-native/layouts";
|
|
12
15
|
import type { ChatInboxItem } from "../core/types";
|
|
13
|
-
import {
|
|
16
|
+
import { inboxRowActions, useChat, useInbox, useInboxActions, usePeople, type ChatAttachmentKind, type ChatConfirm } from "../react/index";
|
|
14
17
|
import { attachmentPreview } from "./attachment-cards";
|
|
15
|
-
import { useQueryClient } from "@tanstack/react-query";
|
|
16
18
|
import type { ChatNativeCopy } from "./copy";
|
|
17
19
|
import { initials, useChatNative, type ChatPerson } from "./context";
|
|
18
20
|
import { displayBody } from "./message-bubble";
|
|
@@ -29,6 +31,12 @@ export interface ChatInboxScreenProps {
|
|
|
29
31
|
/** Every kind but these (`["support"]` keeps support tickets out of a messages inbox). */
|
|
30
32
|
excludeKinds?: string[];
|
|
31
33
|
archived?: boolean;
|
|
34
|
+
/**
|
|
35
|
+
* Each row's actions: receives the conversation and the default set (`inboxRowActions`:
|
|
36
|
+
* Messages' Unread, Pin, Hide Alerts, Delete for me and Archive) and returns the row's. Add,
|
|
37
|
+
* drop, reorder or relabel them; the default keeps them as they are.
|
|
38
|
+
*/
|
|
39
|
+
rowActions?: (item: ChatInboxItem, defaults: RowSwipeAction[]) => RowSwipeAction[];
|
|
32
40
|
/** Passed to InboxPage (a header, a section title, slots). */
|
|
33
41
|
pageProps?: Partial<Omit<InboxPageProps, "items">>;
|
|
34
42
|
testID?: string;
|
|
@@ -58,13 +66,26 @@ export function inboxRow(
|
|
|
58
66
|
unread: item.unread > 0,
|
|
59
67
|
unreadCount: item.unread,
|
|
60
68
|
meta: item.mentioned ? ctx.copy.mentionedYou : undefined,
|
|
69
|
+
muted: item.muted,
|
|
70
|
+
pinned: item.pinned,
|
|
61
71
|
avatar: <NativeAvatar size={40} src={other?.avatarUrl ?? null} fallback={initials(title)} alt={title} recyclingKey={item.conversationId} />,
|
|
62
72
|
};
|
|
63
73
|
}
|
|
64
74
|
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
75
|
+
/** Asks with the system alert: Cancel, then the destructive action. */
|
|
76
|
+
export function alertConfirm(cancelLabel: string): ChatConfirm {
|
|
77
|
+
return (title, body, confirmLabel) =>
|
|
78
|
+
new Promise((resolve) =>
|
|
79
|
+
Alert.alert(title, body, [
|
|
80
|
+
{ text: cancelLabel, style: "cancel", onPress: () => resolve(false) },
|
|
81
|
+
{ text: confirmLabel, style: "destructive", onPress: () => resolve(true) },
|
|
82
|
+
], { cancelable: true, onDismiss: () => resolve(false) }),
|
|
83
|
+
);
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
export function ChatInboxScreen({ onOpen, onStart, kind, kinds, excludeKinds, archived, rowActions, pageProps, testID = "chat-inbox" }: ChatInboxScreenProps) {
|
|
87
|
+
const { userId, attachmentKinds } = useChat();
|
|
88
|
+
const act = useInboxActions();
|
|
68
89
|
const { copy, person: known } = useChatNative();
|
|
69
90
|
const inbox = useInbox({ kind, kinds, excludeKinds, archived });
|
|
70
91
|
// The other person in each direct conversation, fetched in one batch (ChatProvider loadPeople).
|
|
@@ -82,26 +103,26 @@ export function ChatInboxScreen({ onOpen, onStart, kind, kinds, excludeKinds, ar
|
|
|
82
103
|
}
|
|
83
104
|
}, [inbox]);
|
|
84
105
|
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
106
|
+
// A row action that fails says so, rather than leaving the row as it was without a word.
|
|
107
|
+
const options = useMemo(
|
|
108
|
+
() => ({
|
|
109
|
+
confirm: alertConfirm(copy.cancel),
|
|
110
|
+
onError: (e: unknown) => Alert.alert(copy.actionFailed, e instanceof Error ? e.message : undefined),
|
|
111
|
+
}),
|
|
112
|
+
[copy],
|
|
113
|
+
);
|
|
89
114
|
|
|
90
|
-
const items: InboxItem[] = inbox.items.map((item) =>
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
? []
|
|
102
|
-
: [{ id: "archive", label: copy.archive, onPress: () => void client.setMySettings(item.conversationId, { archived: true }).then(settle, settle) }]),
|
|
103
|
-
],
|
|
104
|
-
}));
|
|
115
|
+
const items: InboxItem[] = inbox.items.map((item) => {
|
|
116
|
+
// Messages' row actions: Unread (or Read) and Pin to the right, Hide Alerts and Delete to the
|
|
117
|
+
// left, round buttons; Archive in the long-press menu only. Every one is also a screen reader
|
|
118
|
+
// action on the row.
|
|
119
|
+
const defaults = inboxRowActions(item, act, copy, options);
|
|
120
|
+
return {
|
|
121
|
+
...inboxRow(item, { me: userId, copy, person, kinds: attachmentKinds }),
|
|
122
|
+
onPress: () => onOpen(item.conversationId),
|
|
123
|
+
swipeActions: rowActions ? rowActions(item, defaults) : defaults,
|
|
124
|
+
};
|
|
125
|
+
});
|
|
105
126
|
|
|
106
127
|
return (
|
|
107
128
|
<InboxPage
|
|
@@ -114,6 +135,10 @@ export function ChatInboxScreen({ onOpen, onStart, kind, kinds, excludeKinds, ar
|
|
|
114
135
|
onRefresh={refresh}
|
|
115
136
|
emptyTitle={copy.inboxEmptyTitle}
|
|
116
137
|
emptyBody={copy.inboxEmptyBody}
|
|
138
|
+
// Messages' round buttons behind the swipe, the row a pill while open.
|
|
139
|
+
swipeAppearance="round"
|
|
140
|
+
mutedLabel={copy.alertsOff}
|
|
141
|
+
pinnedLabel={copy.pinnedMark}
|
|
117
142
|
emptyActionLabel={onStart ? copy.startConversation : undefined}
|
|
118
143
|
onEmptyAction={onStart}
|
|
119
144
|
{...pageProps}
|
package/src/native/index.ts
CHANGED
|
@@ -26,7 +26,7 @@
|
|
|
26
26
|
*
|
|
27
27
|
* @stability Beta
|
|
28
28
|
*/
|
|
29
|
-
export { ChatInboxScreen, inboxRow, type ChatInboxScreenProps } from "./inbox-screen";
|
|
29
|
+
export { ChatInboxScreen, alertConfirm, inboxRow, type ChatInboxScreenProps } from "./inbox-screen";
|
|
30
30
|
export { ChatThreadScreen, threadListMode, nearBottom, AT_BOTTOM_POINTS, connectionState, countUnseenBelow, useOnline, type ChatThreadScreenProps, type ChatThreadScreenSlots, type ChatThreadAccessoryContext, type ChatConnectionState } from "./thread-screen";
|
|
31
31
|
export { ChatThreadTitle, type ChatThreadTitleProps, type ChatThreadTitleAvatar } from "./thread-title";
|
|
32
32
|
export { bubbleCorners, bubblePosition, type BubblePosition } from "./message-bubble";
|
|
@@ -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 { keepPreviousData, 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 {
|
|
@@ -40,6 +41,8 @@ import type {
|
|
|
40
41
|
|
|
41
42
|
export const chatKeys = {
|
|
42
43
|
all: ["genesis-chat"] as const,
|
|
44
|
+
/** Every inbox list (each `inbox(opts)` is under it). */
|
|
45
|
+
inboxAll: () => ["genesis-chat", "inbox"] as const,
|
|
43
46
|
inbox: (opts?: object) => ["genesis-chat", "inbox", opts ?? {}] as const,
|
|
44
47
|
unread: () => ["genesis-chat", "unread"] as const,
|
|
45
48
|
conversation: (id: string) => ["genesis-chat", "conversation", id] as const,
|
|
@@ -52,12 +55,44 @@ export const chatKeys = {
|
|
|
52
55
|
scheduled: (conversationId?: string | null) => ["genesis-chat", "scheduled", conversationId ?? null] as const,
|
|
53
56
|
availability: (conversationId: string) => ["genesis-chat", "conversation", conversationId, "availability"] as const,
|
|
54
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,
|
|
55
60
|
search: (query: string, conversationId?: string | null) => ["genesis-chat", "search", conversationId ?? null, query] as const,
|
|
56
61
|
previews: (messageIds: string[]) => ["genesis-chat", "previews", [...messageIds].sort()] as const,
|
|
57
62
|
/** One message's link previews (useLinkPreviews keeps one query per message). */
|
|
58
63
|
preview: (messageId: string) => ["genesis-chat", "preview", messageId] as const,
|
|
59
64
|
};
|
|
60
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
|
+
|
|
61
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. */
|
|
62
97
|
export const CATCH_UP_PAGE = 200;
|
|
63
98
|
export const CATCH_UP_MAX_PAGES = 10;
|
|
@@ -253,7 +288,7 @@ export function ChatProvider({
|
|
|
253
288
|
(prev) => upsertInto(prev, [message]) ?? prev,
|
|
254
289
|
);
|
|
255
290
|
void queryClient.invalidateQueries({ queryKey: ["genesis-chat", "scheduled"] });
|
|
256
|
-
|
|
291
|
+
refreshInbox(queryClient);
|
|
257
292
|
},
|
|
258
293
|
}),
|
|
259
294
|
// A new person or client is a new outbox.
|
|
@@ -269,8 +304,7 @@ export function ChatProvider({
|
|
|
269
304
|
const target = typeof window !== "undefined" && typeof window.addEventListener === "function" ? window : null;
|
|
270
305
|
target?.addEventListener("online", online);
|
|
271
306
|
const sub = client.subscribeInbox(userId, (signal) => {
|
|
272
|
-
|
|
273
|
-
void queryClient.invalidateQueries({ queryKey: chatKeys.unread() });
|
|
307
|
+
refreshInbox(queryClient);
|
|
274
308
|
for (const l of listeners.current) l(signal);
|
|
275
309
|
});
|
|
276
310
|
return () => {
|
|
@@ -387,13 +421,20 @@ export function useConversation(conversationId: string | null | undefined, opts:
|
|
|
387
421
|
if (enabled) void refetchMembers();
|
|
388
422
|
}, [id, enabled, refetchMembers]);
|
|
389
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
|
+
*/
|
|
390
429
|
const merge = useCallback(
|
|
391
|
-
(incoming: ChatMessage[], hasEarlierNow?: boolean) =>
|
|
430
|
+
(incoming: ChatMessage[], hasEarlierNow?: boolean, since = generationOf(queryClient, id)) => {
|
|
431
|
+
if (generationOf(queryClient, id) !== since) return;
|
|
392
432
|
queryClient.setQueryData<MessagesData>(messagesKey, (prev) => {
|
|
393
433
|
const base = prev ?? { messages: [], hasEarlier: false };
|
|
394
434
|
return { messages: upsertMessages(base.messages, incoming), hasEarlier: hasEarlierNow ?? base.hasEarlier };
|
|
395
|
-
})
|
|
396
|
-
|
|
435
|
+
});
|
|
436
|
+
},
|
|
437
|
+
[queryClient, messagesKey, id],
|
|
397
438
|
);
|
|
398
439
|
|
|
399
440
|
/**
|
|
@@ -404,17 +445,20 @@ export function useConversation(conversationId: string | null | undefined, opts:
|
|
|
404
445
|
* it shows the newest page instead, with the rest behind "load earlier".
|
|
405
446
|
*/
|
|
406
447
|
const catchUp = useCallback(async () => {
|
|
448
|
+
const since = generationOf(queryClient, id);
|
|
407
449
|
const current = queryClient.getQueryData<MessagesData>(messagesKey) ?? (await queryClient.ensureQueryData<MessagesData>({ queryKey: messagesKey, queryFn: fetchPage }));
|
|
408
450
|
const list = current.messages;
|
|
409
451
|
let after = list.length ? list[list.length - 1]!.seq : 0;
|
|
410
452
|
for (let pages = 0; ; ) {
|
|
411
453
|
const page = await client.messages(id, { afterSeq: after, limit: CATCH_UP_PAGE, threadRootId: opts.threadRootId, topic: opts.topic });
|
|
412
|
-
if (
|
|
454
|
+
if (generationOf(queryClient, id) !== since) return;
|
|
455
|
+
if (page.messages.length) merge(page.messages, undefined, since);
|
|
413
456
|
if (page.messages.length < CATCH_UP_PAGE) return;
|
|
414
457
|
after = Math.max(after, ...page.messages.map((m) => m.seq));
|
|
415
458
|
if (++pages >= CATCH_UP_MAX_PAGES) break;
|
|
416
459
|
}
|
|
417
460
|
const newest = await fetchPage();
|
|
461
|
+
if (generationOf(queryClient, id) !== since) return;
|
|
418
462
|
queryClient.setQueryData<MessagesData>(messagesKey, { messages: newest.messages, hasEarlier: true });
|
|
419
463
|
}, [client, fetchPage, id, merge, messagesKey, opts.threadRootId, opts.topic, queryClient]);
|
|
420
464
|
|
|
@@ -426,13 +470,14 @@ export function useConversation(conversationId: string | null | undefined, opts:
|
|
|
426
470
|
if (!enabled) return;
|
|
427
471
|
setLive(null);
|
|
428
472
|
const fetchOne = async (messageId: string) => {
|
|
473
|
+
const since = generationOf(queryClient, id);
|
|
429
474
|
const m = await client.message(messageId);
|
|
430
475
|
if (!m) return;
|
|
431
476
|
const belongs = opts.threadRootId ? m.threadRootId === opts.threadRootId : m.threadRootId === null;
|
|
432
|
-
if (belongs && (!opts.topic || m.topic === opts.topic)) merge([m]);
|
|
477
|
+
if (belongs && (!opts.topic || m.topic === opts.topic)) merge([m], undefined, since);
|
|
433
478
|
if (m.threadRootId && !opts.threadRootId) {
|
|
434
479
|
const root = await client.message(m.threadRootId);
|
|
435
|
-
if (root) merge([root]);
|
|
480
|
+
if (root) merge([root], undefined, since);
|
|
436
481
|
}
|
|
437
482
|
};
|
|
438
483
|
let readRefetch: ReturnType<typeof setTimeout> | null = null;
|
|
@@ -493,8 +538,7 @@ export function useConversation(conversationId: string | null | undefined, opts:
|
|
|
493
538
|
const markRead = useCallback(async () => {
|
|
494
539
|
if (!enabled || latestSeq === 0) return;
|
|
495
540
|
await client.markRead(id, latestSeq);
|
|
496
|
-
|
|
497
|
-
void queryClient.invalidateQueries({ queryKey: chatKeys.unread() });
|
|
541
|
+
refreshInbox(queryClient);
|
|
498
542
|
}, [client, enabled, id, latestSeq, queryClient]);
|
|
499
543
|
|
|
500
544
|
// Your read place is one number for the whole conversation, so only the whole timeline moves
|
|
@@ -530,17 +574,19 @@ export function useConversation(conversationId: string | null | undefined, opts:
|
|
|
530
574
|
const first = list[0];
|
|
531
575
|
if (!first || loadingEarlier) return;
|
|
532
576
|
setLoadingEarlier(true);
|
|
577
|
+
const since = generationOf(queryClient, id);
|
|
533
578
|
try {
|
|
534
579
|
const page = await client.messages(id, { beforeSeq: first.seq, limit: pageSize, threadRootId: opts.threadRootId, topic: opts.topic });
|
|
535
|
-
merge(page.messages, page.hasEarlier);
|
|
580
|
+
merge(page.messages, page.hasEarlier, since);
|
|
536
581
|
} finally {
|
|
537
582
|
setLoadingEarlier(false);
|
|
538
583
|
}
|
|
539
|
-
}, [client, id, list, loadingEarlier, merge, opts.threadRootId, opts.topic, pageSize]);
|
|
584
|
+
}, [client, id, list, loadingEarlier, merge, opts.threadRootId, opts.topic, pageSize, queryClient]);
|
|
540
585
|
|
|
541
586
|
/** Loads earlier messages until the one with this seq is held (a search result, a pinned message). True when it is. */
|
|
542
587
|
const loadUntil = useCallback(
|
|
543
588
|
async (seq: number) => {
|
|
589
|
+
const since = generationOf(queryClient, id);
|
|
544
590
|
let current = queryClient.getQueryData<MessagesData>(messagesKey);
|
|
545
591
|
for (let guard = 0; guard < 20 && current; guard++) {
|
|
546
592
|
const first = current.messages[0];
|
|
@@ -551,7 +597,8 @@ export function useConversation(conversationId: string | null | undefined, opts:
|
|
|
551
597
|
threadRootId: opts.threadRootId,
|
|
552
598
|
topic: opts.topic,
|
|
553
599
|
});
|
|
554
|
-
|
|
600
|
+
if (generationOf(queryClient, id) !== since) return false;
|
|
601
|
+
merge(page.messages, page.hasEarlier, since);
|
|
555
602
|
current = queryClient.getQueryData<MessagesData>(messagesKey);
|
|
556
603
|
}
|
|
557
604
|
return Boolean(current?.messages.some((m) => m.seq === seq));
|
|
@@ -674,6 +721,40 @@ export function useMessageActions() {
|
|
|
674
721
|
}, [client, queryClient]);
|
|
675
722
|
}
|
|
676
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
|
+
|
|
677
758
|
/**
|
|
678
759
|
* What the read hooks return while there is nothing yet: one frozen object (and array) for every
|
|
679
760
|
* caller, so a row's memo holds across renders instead of seeing a fresh `{}` each time.
|
|
@@ -738,7 +819,7 @@ export function useStartConversation() {
|
|
|
738
819
|
return useCallback(
|
|
739
820
|
async (kind: string, memberIds: string[], opts?: StartConversationOptions) => {
|
|
740
821
|
const id = await client.startConversation(kind, memberIds, opts);
|
|
741
|
-
|
|
822
|
+
refreshInbox(queryClient);
|
|
742
823
|
return id;
|
|
743
824
|
},
|
|
744
825
|
[client, queryClient],
|
|
@@ -857,7 +938,7 @@ export function useBroadcast() {
|
|
|
857
938
|
setSending(true);
|
|
858
939
|
try {
|
|
859
940
|
const ids = await client.broadcast(conversationIds, opts.clientId ?? randomId(), body, { silent: opts.silent });
|
|
860
|
-
|
|
941
|
+
refreshInbox(queryClient);
|
|
861
942
|
return ids;
|
|
862
943
|
} finally {
|
|
863
944
|
setSending(false);
|
|
@@ -964,3 +1045,4 @@ export function useLinkPreviews(messageIds: (string | null | undefined)[]): Reco
|
|
|
964
1045
|
const EMPTY_PREVIEWS: Record<string, ChatLinkPreview[]> = {};
|
|
965
1046
|
|
|
966
1047
|
export type { ThreadItem, LocalFile, QueuedMessage };
|
|
1048
|
+
export { defaultInboxActionLabels, inboxRowActions, type ChatConfirm, type ChatInboxActionLabels, type ChatInboxActions, type InboxRowActionsOptions } from "./inbox-actions";
|