@openpeepshq/rn-components 0.24.0 → 0.28.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.
Files changed (26) hide show
  1. package/package.json +2 -2
  2. package/src/components/conversations/ConversationPreviewCard.test.tsx +345 -0
  3. package/src/components/conversations/ConversationPreviewCard.tsx +29 -24
  4. package/src/components/custom/navigation/side-menu.test.tsx +9 -0
  5. package/src/components/custom/navigation/side-menu.tsx +19 -3
  6. package/src/components/groups/GroupAvatar.test.tsx +20 -2
  7. package/src/components/groups/GroupAvatar.tsx +7 -1
  8. package/src/components/jams/JamCallParticipant.test.tsx +303 -0
  9. package/src/components/jams/JamCallParticipant.tsx +7 -1
  10. package/src/components/jams/useLateTrackMediaStream.test.ts +139 -25
  11. package/src/components/jams/useLateTrackMediaStream.ts +62 -19
  12. package/src/components/post/pieces/ShareMenu.test.tsx +105 -11
  13. package/src/components/post/pieces/ShareMenu.tsx +55 -10
  14. package/src/components/post/pieces/modals/SendToConversationModal.tsx +140 -0
  15. package/src/components/post/pieces/modals/ShareIntoGroupModal.tsx +121 -0
  16. package/src/components/post/pieces/modals/index.ts +2 -0
  17. package/src/components/post/pieces/sharePickers.test.tsx +819 -0
  18. package/src/components/profile/Avatar.test.tsx +19 -0
  19. package/src/components/profile/Avatar.tsx +9 -1
  20. package/src/lib/push-notifications.test.ts +244 -0
  21. package/src/lib/push-notifications.ts +65 -0
  22. package/src/pages/auth/Login.tsx +16 -2
  23. package/src/pages/conversations/Index.test.tsx +235 -0
  24. package/src/pages/conversations/Index.tsx +15 -16
  25. package/src/pages/settings/Account.test.tsx +4 -0
  26. package/src/pages/settings/Account.tsx +14 -0
@@ -229,4 +229,23 @@ describe('ProfileAvatar SVG path selection (issue #1666 round-2 plan step 2)', (
229
229
  : tile.props.children;
230
230
  expect(text.props.style.fontSize).toBe(15);
231
231
  });
232
+
233
+ it('centers the initials glyph deterministically: lineHeight = fontSize and no font padding (issue #1666 QA 2026-11-24)', () => {
234
+ // The QA report: initials/fallback avatars sit low in the selection chips
235
+ // while image avatars align. The image branch is a true square disc; the
236
+ // initials must be the same. Without an explicit lineHeight the text box
237
+ // is the platform font line-height (taller than the glyphs) plus font-
238
+ // metric padding, so items-center centers the *box* below the *glyph*.
239
+ // lineHeight = fontSize + includeFontPadding: false make the box exactly
240
+ // glyph height — pin both so a revert fails.
241
+ const tree = renderAvatar(baseProfile);
242
+ const tile = tree.root
243
+ .findAllByType(MockView)
244
+ .find((node) => typeof node.props.style?.backgroundColor === 'string');
245
+ const text = Array.isArray(tile.props.children)
246
+ ? tile.props.children[0]
247
+ : tile.props.children;
248
+ expect(text.props.style.lineHeight).toBe(text.props.style.fontSize);
249
+ expect(text.props.style.includeFontPadding).toBe(false);
250
+ });
232
251
  });
@@ -71,7 +71,15 @@ export const ProfileAvatar = ({
71
71
  )}
72
72
  style={{ backgroundColor: initialsBg }}
73
73
  >
74
- <Text className="text-foreground font-medium" style={{ fontSize }}>
74
+ {/* lineHeight = fontSize + no font padding make the text box exactly the
75
+ glyph height, so items-center centers the initials on the circle —
76
+ the default line-height/font-metric padding leaves the box taller than
77
+ the glyphs and pushes them down (issue #1666 QA: initials avatars sit
78
+ low while image avatars align). */}
79
+ <Text
80
+ className="text-foreground font-medium"
81
+ style={{ fontSize, lineHeight: fontSize, includeFontPadding: false }}
82
+ >
75
83
  {getInitials(profile?.displayName, profile?.handle)}
76
84
  </Text>
77
85
  </View>
@@ -0,0 +1,244 @@
1
+ /**
2
+ * Unit tests for unregisterPushForLogout — the RN half of the #2147 logout
3
+ * cleanup. The helper must delete this device's FCM row on the server
4
+ * (tolerating an already-deleted row), then drop the local FCM token, and it
5
+ * must never throw so logout cannot be blocked by push cleanup.
6
+ *
7
+ * The Firebase modules are mocked (the built package ships ESM which Jest's
8
+ * node transform doesn't cover — same approach as the other tests in this
9
+ * package). @openpeepshq/react is mocked too, but its handleResult /
10
+ * isSubscriptionNotFound helpers are loaded from the real shared source so
11
+ * they stay in sync with platform/react/src/push/pushSubscriptionErrors.ts.
12
+ */
13
+
14
+ jest.mock('@react-native-firebase/app', () => {
15
+ const state = {
16
+ token: 'fcm-token-123' as string | undefined,
17
+ getTokenError: undefined as unknown,
18
+ deleteTokenError: undefined as unknown,
19
+ };
20
+ const getToken = jest.fn(async () => {
21
+ if (state.getTokenError) throw state.getTokenError;
22
+ return state.token;
23
+ });
24
+ const deleteToken = jest.fn(async () => {
25
+ if (state.deleteTokenError) throw state.deleteTokenError;
26
+ });
27
+ return {
28
+ __state: state,
29
+ __getToken: getToken,
30
+ __deleteToken: deleteToken,
31
+ getApp: () => ({
32
+ messaging: () => ({ getToken, deleteToken }),
33
+ }),
34
+ };
35
+ });
36
+
37
+ jest.mock('@react-native-firebase/messaging', () => ({
38
+ // Delegate to the messaging instance the code passes in (the app mock
39
+ // owns the token state), so getToken errors/absence mirror the device.
40
+ getToken: jest.fn(async (messaging: { getToken: () => Promise<string> }) =>
41
+ messaging.getToken()
42
+ ),
43
+ requestPermission: jest.fn(),
44
+ AuthorizationStatus: {
45
+ AUTHORIZED: 'authorized',
46
+ PROVISIONAL: 'provisional',
47
+ DENIED: 'denied',
48
+ },
49
+ onMessage: jest.fn(() => jest.fn()),
50
+ onNotificationOpenedApp: jest.fn(() => jest.fn()),
51
+ getInitialNotification: jest.fn(async () => null),
52
+ setBackgroundMessageHandler: jest.fn(),
53
+ }));
54
+
55
+ jest.mock('@notifee/react-native', () => ({
56
+ __esModule: true,
57
+ default: {
58
+ onBackgroundEvent: jest.fn(() => jest.fn()),
59
+ onForegroundEvent: jest.fn(() => jest.fn()),
60
+ requestPermission: jest.fn(),
61
+ createChannel: jest.fn(),
62
+ setNotificationCategories: jest.fn(),
63
+ displayNotification: jest.fn(),
64
+ setBadgeCount: jest.fn(),
65
+ },
66
+ EventType: { PRESS: 'press', SHOW: 'show', DELETE: 'delete' },
67
+ }));
68
+
69
+ jest.mock('./utils', () => ({
70
+ handleInternalURLNavigation: jest.fn(),
71
+ }));
72
+
73
+ jest.mock('./notification-helpers', () => ({
74
+ setAppBadgeCount: jest.fn(),
75
+ incrementAppBadgeCount: jest.fn(),
76
+ }));
77
+
78
+ // The built @openpeepshq/react ships ESM, which RN Jest's ts-jest transform
79
+ // can't load, so the package is mocked. But handleResult /
80
+ // isSubscriptionNotFound must stay the REAL implementation (a drift-prone
81
+ // inline copy was the point of the review), so load the dependency-free leaf
82
+ // source file the package exports them from. It has no imports, so ts-jest
83
+ // transforms it cleanly without pulling the rest of the package in, and it
84
+ // points at source (not dist) so it never depends on a react build.
85
+ const realPushErrors = jest.requireActual(
86
+ '../../../react/src/push/pushSubscriptionErrors'
87
+ );
88
+
89
+ jest.mock('@openpeepshq/react', () => ({
90
+ handleResult: realPushErrors.handleResult,
91
+ isSubscriptionNotFound: realPushErrors.isSubscriptionNotFound,
92
+ apiErrorMessage: jest.fn(),
93
+ }));
94
+
95
+ import { unregisterPushForLogout } from './push-notifications';
96
+
97
+ // jest.mock returns undefined; require the mocked module for its internals.
98
+ const firebaseApp = require('@react-native-firebase/app');
99
+
100
+ const makeClient = (rows: Array<Record<string, unknown>>) => {
101
+ const listPushSubscriptions = jest.fn(async () => ({ data: rows }));
102
+ const deletePushSubcription = jest.fn(async () => ({
103
+ data: { success: true },
104
+ }));
105
+ const client = {
106
+ accounts: {
107
+ current: { listPushSubscriptions, deletePushSubcription },
108
+ },
109
+ };
110
+ return { client, listPushSubscriptions, deletePushSubcription };
111
+ };
112
+
113
+ const httpError = (status: number) =>
114
+ ({ error: { __HTTP_ERROR__: true, status } }) as unknown;
115
+
116
+ describe('unregisterPushForLogout', () => {
117
+ let consoleInfo: jest.SpyInstance;
118
+
119
+ beforeEach(() => {
120
+ firebaseApp.__state.token = 'fcm-token-123';
121
+ firebaseApp.__state.getTokenError = undefined;
122
+ firebaseApp.__state.deleteTokenError = undefined;
123
+ firebaseApp.__getToken.mockClear();
124
+ firebaseApp.__deleteToken.mockClear();
125
+ consoleInfo = jest.spyOn(console, 'info').mockImplementation(() => {});
126
+ });
127
+
128
+ afterEach(() => {
129
+ consoleInfo.mockRestore();
130
+ });
131
+
132
+ it('deletes this device’s FCM row on the server and drops the local token', async () => {
133
+ const rows = [
134
+ { type: 'fcm', fcmToken: 'other-device', id: 'sub-other' },
135
+ { type: 'fcm', fcmToken: 'fcm-token-123', id: 'sub-own' },
136
+ { type: 'web', endpoint: 'https://push.example/1', id: 'sub-web' },
137
+ ];
138
+ const { client, listPushSubscriptions, deletePushSubcription } =
139
+ makeClient(rows);
140
+
141
+ await expect(unregisterPushForLogout(client as never)).resolves.toBe('ok');
142
+
143
+ expect(listPushSubscriptions).toHaveBeenCalledTimes(1);
144
+ expect(deletePushSubcription).toHaveBeenCalledTimes(1);
145
+ expect(deletePushSubcription).toHaveBeenCalledWith({
146
+ pathParameters: { pushSubscriptionId: 'sub-own' },
147
+ });
148
+ expect(firebaseApp.__deleteToken).toHaveBeenCalledTimes(1);
149
+ });
150
+
151
+ it.each([404, 410])(
152
+ 'treats a %i from the delete as success (row already gone)',
153
+ async (status) => {
154
+ const rows = [{ type: 'fcm', fcmToken: 'fcm-token-123', id: 'sub-own' }];
155
+ const { client, deletePushSubcription } = makeClient(rows);
156
+ deletePushSubcription.mockRejectedValue(httpError(status));
157
+
158
+ await expect(unregisterPushForLogout(client as never)).resolves.toBe(
159
+ 'ok'
160
+ );
161
+
162
+ // The token is still dropped locally even though the server row is gone.
163
+ expect(firebaseApp.__deleteToken).toHaveBeenCalledTimes(1);
164
+ expect(consoleInfo).not.toHaveBeenCalled();
165
+ }
166
+ );
167
+
168
+ it('keeps the subscription as a fallback when the server delete fails hard, and still drops the token', async () => {
169
+ const rows = [{ type: 'fcm', fcmToken: 'fcm-token-123', id: 'sub-own' }];
170
+ const { client, deletePushSubcription } = makeClient(rows);
171
+ deletePushSubcription.mockRejectedValue(httpError(500));
172
+
173
+ // A hard server failure is reported so the caller can toast, while the
174
+ // local token is still dropped.
175
+ await expect(unregisterPushForLogout(client as never)).resolves.toBe(
176
+ 'failed'
177
+ );
178
+
179
+ expect(consoleInfo).toHaveBeenCalledWith(
180
+ 'Error removing push subscription on logout',
181
+ expect.anything()
182
+ );
183
+ expect(firebaseApp.__deleteToken).toHaveBeenCalledTimes(1);
184
+ });
185
+
186
+ it('logs the list failure as a fallback path when listPushSubscriptions throws', async () => {
187
+ const { client, listPushSubscriptions, deletePushSubcription } = makeClient(
188
+ []
189
+ );
190
+ listPushSubscriptions.mockRejectedValue(httpError(503));
191
+
192
+ // A hard server failure (even the list) is reported so the caller can toast.
193
+ await expect(unregisterPushForLogout(client as never)).resolves.toBe(
194
+ 'failed'
195
+ );
196
+
197
+ expect(deletePushSubcription).not.toHaveBeenCalled();
198
+ expect(consoleInfo).toHaveBeenCalledWith(
199
+ 'Error removing push subscription on logout',
200
+ expect.anything()
201
+ );
202
+ expect(firebaseApp.__deleteToken).toHaveBeenCalledTimes(1);
203
+ });
204
+
205
+ it('deletes nothing when no FCM row matches this device’s token', async () => {
206
+ const rows = [
207
+ { type: 'fcm', fcmToken: 'other-device', id: 'sub-other' },
208
+ { type: 'web', endpoint: 'https://push.example/1', id: 'sub-web' },
209
+ ];
210
+ const { client, deletePushSubcription } = makeClient(rows);
211
+
212
+ await expect(unregisterPushForLogout(client as never)).resolves.toBe('ok');
213
+
214
+ expect(deletePushSubcription).not.toHaveBeenCalled();
215
+ expect(firebaseApp.__deleteToken).toHaveBeenCalledTimes(1);
216
+ });
217
+
218
+ it('is a no-op (no client calls, no token delete) when Firebase messaging is unavailable', async () => {
219
+ firebaseApp.__state.getTokenError = new Error('no messaging');
220
+ const { client, listPushSubscriptions } = makeClient([]);
221
+
222
+ await expect(unregisterPushForLogout(client as never)).resolves.toBe('ok');
223
+
224
+ expect(listPushSubscriptions).not.toHaveBeenCalled();
225
+ expect(firebaseApp.__deleteToken).not.toHaveBeenCalled();
226
+ });
227
+
228
+ it('is a no-op when there is no token', async () => {
229
+ firebaseApp.__state.token = undefined;
230
+ const { client, listPushSubscriptions } = makeClient([]);
231
+
232
+ await expect(unregisterPushForLogout(client as never)).resolves.toBe('ok');
233
+
234
+ expect(listPushSubscriptions).not.toHaveBeenCalled();
235
+ expect(firebaseApp.__deleteToken).not.toHaveBeenCalled();
236
+ });
237
+
238
+ it('never throws when the local token delete fails', async () => {
239
+ firebaseApp.__state.deleteTokenError = new Error('token already gone');
240
+ const { client } = makeClient([]);
241
+
242
+ await expect(unregisterPushForLogout(client as never)).resolves.toBe('ok');
243
+ });
244
+ });
@@ -22,8 +22,12 @@ import {
22
22
  consumePendingPushAction,
23
23
  setPendingPushAction,
24
24
  } from './push-notification-navigation';
25
+ import type { useOpenpeeps } from '@openpeepshq/react';
26
+ import { isSubscriptionNotFound, handleResult } from '@openpeepshq/react';
25
27
  import './push-notifications-background';
26
28
 
29
+ type OpenpeepsClient = ReturnType<typeof useOpenpeeps>['client'];
30
+
27
31
  const messageToPushNotification = (
28
32
  message: FirebaseMessagingTypes.RemoteMessage
29
33
  ): PushMessage | undefined =>
@@ -245,3 +249,64 @@ export const initializePushNotifications = async (
245
249
  }
246
250
  return fcmRegistration;
247
251
  };
252
+
253
+ /**
254
+ * Logout cleanup: remove this device's FCM subscription from the server and
255
+ * drop the local FCM registration, so the logged-out device stops receiving
256
+ * pushes for this account and the next login registers fresh. Must run before
257
+ * credentials are cleared — the API calls need the auth token. Best-effort:
258
+ * never throws, so logout cannot be blocked by push cleanup.
259
+ *
260
+ * Returns `'failed'` when the server row could not be removed (the user would
261
+ * keep receiving pushes for this account, so the caller toasts); `'ok'`
262
+ * otherwise, including when there was no local registration at all or only
263
+ * the local token drop failed (the server-side delete is what stops delivery).
264
+ */
265
+ export const unregisterPushForLogout = async (
266
+ client: OpenpeepsClient
267
+ ): Promise<'ok' | 'failed'> => {
268
+ let token: string | undefined;
269
+ try {
270
+ token = await getToken(getApp().messaging());
271
+ } catch {
272
+ // No Firebase messaging available; nothing to unregister.
273
+ return 'ok';
274
+ }
275
+ if (!token) return 'ok';
276
+
277
+ let serverCleanupFailed = false;
278
+ try {
279
+ const subscriptions = await client.accounts.current
280
+ .listPushSubscriptions()
281
+ .then(handleResult);
282
+ const own = subscriptions.find(
283
+ (subscription) =>
284
+ subscription.type === 'fcm' && subscription.fcmToken === token
285
+ );
286
+ if (own) {
287
+ await client.accounts.current
288
+ .deletePushSubcription({
289
+ pathParameters: { pushSubscriptionId: own.id },
290
+ })
291
+ .then(handleResult)
292
+ .catch((err) => {
293
+ // The row may already be gone (e.g. logged out elsewhere);
294
+ // deleting a missing subscription is not a failure.
295
+ if (isSubscriptionNotFound(err)) return;
296
+ throw err;
297
+ });
298
+ }
299
+ } catch (err) {
300
+ // Keep the subscription as a fallback: the delivery-time cleanup still
301
+ // removes it once the token gets rejected as unregistered.
302
+ serverCleanupFailed = true;
303
+ console.info('Error removing push subscription on logout', err);
304
+ }
305
+
306
+ try {
307
+ await getApp().messaging().deleteToken();
308
+ } catch {
309
+ // Token may already be gone; nothing to do.
310
+ }
311
+ return serverCleanupFailed ? 'failed' : 'ok';
312
+ };
@@ -22,6 +22,7 @@ import {
22
22
  } from '@openpeepshq/react';
23
23
  import Toast from 'react-native-toast-message';
24
24
  import { useTranslation } from 'react-i18next';
25
+ import { unregisterPushForLogout } from '../../lib/push-notifications';
25
26
  import { LOGIN_EMAIL, LOGIN_PASSWORD } from '../../lib/constants';
26
27
 
27
28
  export const Login = ({
@@ -30,7 +31,7 @@ export const Login = ({
30
31
  const { t } = useTranslation();
31
32
  const [isPasswordVisible, setIsPasswordVisible] = React.useState(false);
32
33
  const { login, submitting } = usePasswordLogin();
33
- const { openpeepsApi } = useOpenpeeps();
34
+ const { openpeepsApi, client } = useOpenpeeps();
34
35
  const logout = openpeepsApi.logoutAction();
35
36
  const isRegistrationOpen =
36
37
  !!useServerInfo().communityConfig?.settings?.openRegistrations;
@@ -45,8 +46,21 @@ export const Login = ({
45
46
 
46
47
  const onSubmit = async (values: LoginRequest) => {
47
48
  try {
48
- // Drop any stale session cache before switching accounts.
49
+ // Best-effort cleanup (never throws); clears stale subscriptions from
50
+ // any previous session before switching accounts. The RN side owns FCM
51
+ // cleanup, so this outcome — not the web pushCleanup flag — is what the
52
+ // logout toast reflects on native.
53
+ const pushResult = await unregisterPushForLogout(client);
49
54
  await logout();
55
+ if (pushResult === 'failed') {
56
+ Toast.show({
57
+ type: 'error',
58
+ text1: t('settings.notifications.pushCleanupFailed', {
59
+ defaultValue:
60
+ 'Could not remove push notifications for this device.',
61
+ }),
62
+ });
63
+ }
50
64
  await login(values);
51
65
  } catch (err) {
52
66
  Toast.show({
@@ -0,0 +1,235 @@
1
+ /**
2
+ * Regression tests for the conversation-row list keys (issue #2107 review
3
+ * S1), the per-row unread-badge indexing, and the `conversation[0]`
4
+ * first-post contract (review S1–S3, round 8).
5
+ *
6
+ * The DM list swapped `key={idx}` for `key={first.id}` — the first (oldest
7
+ * root) post identifies the thread, matching the web list — but nothing
8
+ * pinned that: a regression back to index keys would pass CI. The sibling
9
+ * `New.test.tsx` ("row keying (issue #1666 review S3)") reads keys off
10
+ * `_currentFiber()` because React strips them from `toJSON()`; the tests
11
+ * here do the same for the conversation rows.
12
+ */
13
+
14
+ const React = require('react');
15
+ const ReactTestRenderer = require('react-test-renderer');
16
+
17
+ // Merged 1:1 threads: `conversation[0]` is the oldest root post and
18
+ // identifies the thread. Both threads carry two posts, interleaved
19
+ // (a1, b1, a2): with a single multi-post thread, keying by the *last*
20
+ // post id happens to yield the same key list as first-post keying, so the
21
+ // keying test is not mutation-tight — the interleaved shape makes
22
+ // leaf-keying produce `['post-a2','post-b2']` and fail. The empty third
23
+ // group exercises the `!first → null` guard: an empty conversation group
24
+ // is skipped, not crashed on.
25
+ const ada = { id: 'p-ada', handle: 'ada', displayName: 'Ada' };
26
+ const beth = { id: 'p-beth', handle: 'beth', displayName: 'Beth' };
27
+ const CONVERSATIONS: { id: string; profile: { id: string } }[][] = [
28
+ [
29
+ { id: 'post-a1', profile: ada },
30
+ { id: 'post-b1', profile: beth },
31
+ { id: 'post-a2', profile: ada },
32
+ ],
33
+ [{ id: 'post-b2', profile: beth }],
34
+ [],
35
+ ];
36
+
37
+ jest.mock('react-native', () => ({
38
+ View: (props: { testID?: string; className?: string; children?: unknown }) =>
39
+ React.createElement(
40
+ 'View',
41
+ { testID: props.testID, className: props.className },
42
+ props.children
43
+ ),
44
+ TouchableOpacity: (props: {
45
+ testID?: string;
46
+ className?: string;
47
+ children?: unknown;
48
+ }) =>
49
+ React.createElement(
50
+ 'TouchableOpacity',
51
+ { testID: props.testID, className: props.className },
52
+ props.children
53
+ ),
54
+ ActivityIndicator: () => null,
55
+ RefreshControl: () => null,
56
+ }));
57
+
58
+ jest.mock('react-i18next', () => ({
59
+ useTranslation: () => ({ t: (key: string) => key }),
60
+ }));
61
+
62
+ jest.mock('react-native-keyboard-aware-scroll-view', () => ({
63
+ KeyboardAwareScrollView: (props: { children?: unknown }) =>
64
+ React.createElement('KeyboardAwareScrollView', null, props.children),
65
+ }));
66
+
67
+ // The badge contract tests need a per-test unread map; `useUnseenPostCounts`
68
+ // reads whatever this points at, so the tests set `UNSEEN_BY_CONVERSATION`
69
+ // before each render.
70
+ const UNSEEN_BY_CONVERSATION: { direct: Record<string, number> } = {
71
+ direct: {},
72
+ };
73
+
74
+ // Each test overwrites `UNSEEN_BY_CONVERSATION.direct` before rendering;
75
+ // reset it afterwards so a test that forgets to set it cannot inherit a
76
+ // previous test's counts (review S2, round 9).
77
+ afterEach(() => {
78
+ UNSEEN_BY_CONVERSATION.direct = {};
79
+ });
80
+
81
+ jest.mock('@openpeepshq/react', () => ({
82
+ useAuthData: () => ({}),
83
+ useOpenpeeps: () => ({
84
+ currentProfile: { id: 'me' },
85
+ openpeepsApi: {
86
+ useConversations: () => ({
87
+ data: CONVERSATIONS,
88
+ isLoading: false,
89
+ isError: false,
90
+ refetch: jest.fn(),
91
+ }),
92
+ useArchivedConversations: () => ({
93
+ data: [],
94
+ isLoading: false,
95
+ isError: false,
96
+ refetch: jest.fn(),
97
+ }),
98
+ useUnseenPostCounts: () => ({ data: UNSEEN_BY_CONVERSATION }),
99
+ },
100
+ }),
101
+ }));
102
+
103
+ jest.mock('@openpeepshq/common', () => ({
104
+ canCreatePost: () => false,
105
+ }));
106
+
107
+ jest.mock('@gorhom/bottom-sheet', () => ({
108
+ BottomSheetModal: React.forwardRef(() => null),
109
+ }));
110
+
111
+ jest.mock('../../components/icons/index', () => ({
112
+ MessageCircleOffIcon: () => null,
113
+ MessageSquarePlusIcon: () => null,
114
+ }));
115
+
116
+ jest.mock('../../components/ui/themed-text', () => ({
117
+ ThemedText: (props: Record<string, unknown> & { children?: unknown }) =>
118
+ React.createElement('ThemedText', props, props.children),
119
+ TextClassContext: {
120
+ Provider: ({ children }: { children?: unknown }) => children,
121
+ },
122
+ }));
123
+
124
+ jest.mock('../../components/layout', () => ({
125
+ useSetPageHeader: jest.fn(),
126
+ useSetPlusButtonActions: jest.fn(),
127
+ }));
128
+
129
+ jest.mock('../../components/conversations/index', () => {
130
+ const ConversationSettingsSheet = React.forwardRef(() => null);
131
+ return {
132
+ // Named so the test can locate the rows (the object-literal shorthand
133
+ // sets the function's `name`); the key under test lives on the element
134
+ // Index.tsx renders.
135
+ ConversationPreviewCard: (props: Record<string, unknown>) =>
136
+ React.createElement('ConversationPreviewCard', props),
137
+ DirectMessageSearch: () => null,
138
+ useCreateNewConversation: () => ({ openCreateConversation: jest.fn() }),
139
+ ConversationSettingsSheet,
140
+ };
141
+ });
142
+
143
+ import { ConversationsIndex } from './Index';
144
+
145
+ const renderIndex = () => {
146
+ let tree: ReturnType<typeof ReactTestRenderer.create>;
147
+ ReactTestRenderer.act(() => {
148
+ tree = ReactTestRenderer.create(
149
+ React.createElement(ConversationsIndex, {
150
+ navigation: { navigate: jest.fn() },
151
+ } as never)
152
+ );
153
+ });
154
+ return tree;
155
+ };
156
+
157
+ const rowNodes = (tree: ReturnType<typeof ReactTestRenderer.create>) =>
158
+ tree.root.findAll(
159
+ (node: { type?: { name?: string } }) =>
160
+ typeof node.type === 'function' &&
161
+ node.type.name === 'ConversationPreviewCard'
162
+ );
163
+
164
+ describe('ConversationsIndex row keying (issue #2107 review S1)', () => {
165
+ it('keys the conversation rows by the first post id, not array index or leaf', () => {
166
+ const tree = renderIndex();
167
+ // React strips keys from the public TestInstance / toJSON output; the
168
+ // key only lives on the fiber, so read it from there (same pattern as
169
+ // New.test.tsx). With the fixed `key={first.id}` these are the first
170
+ // (oldest root) post ids of each thread; a regression to `key={idx}`
171
+ // would yield "0"/"1" and a regression to the leaf (last) post id
172
+ // would yield "post-a2"/"post-b2" (the mock is interleaved so a
173
+ // single-multi-post-thread layout cannot hide the leaf-keying
174
+ // regression — review S3).
175
+ const rowKeys = rowNodes(tree).map(
176
+ (node: { _currentFiber: () => { key: string } }) =>
177
+ node._currentFiber().key
178
+ );
179
+ // Exactly two rows: the empty group was skipped by the `!first → null`
180
+ // guard (rendered above without throwing), and the keys are still the
181
+ // first post ids of the non-empty threads.
182
+ expect(rowKeys).toEqual(['post-a1', 'post-b2']);
183
+ });
184
+ });
185
+
186
+ describe('ConversationsIndex unread-badge wiring (issue #2107 review S1–S2)', () => {
187
+ it('indexes each row by its own first post and falls back to 0, never other rows', () => {
188
+ // `post-a1` is the first post of the first row; `post-a2` is that
189
+ // thread's leaf (never used for indexing); `archived-root-id` is a
190
+ // thread root absent from the active preview list (an archived thread
191
+ // the user left). A regression that pools the counts instead of
192
+ // indexing per row would hand the first row 2 + 3 + 5 = 10.
193
+ UNSEEN_BY_CONVERSATION.direct = {
194
+ 'post-a1': 2,
195
+ 'post-a2': 3,
196
+ 'archived-root-id': 5,
197
+ };
198
+ const tree = renderIndex();
199
+ const rows = rowNodes(tree);
200
+ expect(rows).toHaveLength(2);
201
+ // The mocked card does not render the badge itself — it carries the
202
+ // exact `unreadCount` the page passed; that prop is what the
203
+ // `unreadCount > 0` branch inside the real card consumes.
204
+ expect(rows[0].props.unreadCount).toBe(2);
205
+ // The second row's first post (`post-b2`) is absent from the map: the
206
+ // `?? 0` fallback suppresses its badge entirely.
207
+ expect(rows[1].props.unreadCount).toBe(0);
208
+ });
209
+
210
+ it('pins the page↔core contract: rows and badges index conversation[0] (the oldest root)', () => {
211
+ // `mergeOneToOnePreviews` orders each 1:1 group `[oldest root, …,
212
+ // newest leaf]`; the page assumes the row identity and the badge
213
+ // index both come from `conversation[0]`. If core ever returned a
214
+ // group with the newest post first, the badge would index the leaf
215
+ // and silently drop counts — this mock mirrors the shape the contract
216
+ // depends on: row one carries the unseen count on its OLDEST root
217
+ // (`post-a1`), not its leaf (`post-a2`).
218
+ UNSEEN_BY_CONVERSATION.direct = {
219
+ 'post-a1': 4,
220
+ };
221
+ const tree = renderIndex();
222
+ const rows = rowNodes(tree);
223
+ expect(rows).toHaveLength(2);
224
+ // Row identity follows the same contract: the keys are the oldest
225
+ // roots, in the order the page renders them.
226
+ const rowKeys = rows.map(
227
+ (node: { _currentFiber: () => { key: string } }) =>
228
+ node._currentFiber().key
229
+ );
230
+ expect(rowKeys).toEqual(['post-a1', 'post-b2']);
231
+ // The unseen count lands on the row whose first post owns it.
232
+ expect(rows[0].props.unreadCount).toBe(4);
233
+ expect(rows[1].props.unreadCount).toBe(0);
234
+ });
235
+ });
@@ -156,22 +156,21 @@ export const ConversationsIndex: React.FC<MessagesProps> = ({ navigation }) => {
156
156
  </View>
157
157
  )}
158
158
  {!isLoading &&
159
- conversations?.map((conversation, idx) => (
160
- <ConversationPreviewCard
161
- key={idx}
162
- conversation={conversation}
163
- unreadCount={
164
- conversation[0]?.id
165
- ? (unseenByConversation[conversation[0].id] ?? 0)
166
- : 0
167
- }
168
- onPress={() =>
169
- navigation.navigate('Conversation', {
170
- id: conversation[0]?.id,
171
- })
172
- }
173
- />
174
- ))}
159
+ conversations?.map((conversation) => {
160
+ // The first post identifies the thread (matches the web list).
161
+ const first = conversation[0];
162
+ if (!first) return null;
163
+ return (
164
+ <ConversationPreviewCard
165
+ key={first.id}
166
+ conversation={conversation}
167
+ unreadCount={unseenByConversation[first.id] ?? 0}
168
+ onPress={() =>
169
+ navigation.navigate('Conversation', { id: first.id })
170
+ }
171
+ />
172
+ );
173
+ })}
175
174
  </>
176
175
  )}
177
176
  </KeyboardAwareScrollView>