@planningcenter/chat-react-native 4.2.0-rc.0 → 4.2.0-rc.1

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 (66) hide show
  1. package/build/components/conversation/message.d.ts +3 -2
  2. package/build/components/conversation/message.d.ts.map +1 -1
  3. package/build/components/conversation/message.js +23 -22
  4. package/build/components/conversation/message.js.map +1 -1
  5. package/build/components/conversation/message_list.d.ts +21 -0
  6. package/build/components/conversation/message_list.d.ts.map +1 -0
  7. package/build/components/conversation/message_list.js +273 -0
  8. package/build/components/conversation/message_list.js.map +1 -0
  9. package/build/components/conversation/message_read_receipts.d.ts +2 -4
  10. package/build/components/conversation/message_read_receipts.d.ts.map +1 -1
  11. package/build/components/conversation/message_read_receipts.js +2 -3
  12. package/build/components/conversation/message_read_receipts.js.map +1 -1
  13. package/build/components/conversation/reply_shadow_message.d.ts +2 -1
  14. package/build/components/conversation/reply_shadow_message.d.ts.map +1 -1
  15. package/build/components/conversation/reply_shadow_message.js +47 -46
  16. package/build/components/conversation/reply_shadow_message.js.map +1 -1
  17. package/build/hooks/use_conversation_messages.d.ts.map +1 -1
  18. package/build/hooks/use_conversation_messages.js +40 -28
  19. package/build/hooks/use_conversation_messages.js.map +1 -1
  20. package/build/hooks/use_conversation_messages_jolt_events.d.ts.map +1 -1
  21. package/build/hooks/use_conversation_messages_jolt_events.js +6 -1
  22. package/build/hooks/use_conversation_messages_jolt_events.js.map +1 -1
  23. package/build/screens/conversation_screen.d.ts.map +1 -1
  24. package/build/screens/conversation_screen.js +184 -365
  25. package/build/screens/conversation_screen.js.map +1 -1
  26. package/build/types/resources/message.d.ts +1 -0
  27. package/build/types/resources/message.d.ts.map +1 -1
  28. package/build/types/resources/message.js.map +1 -1
  29. package/build/utils/cache/messages_cache.d.ts +1 -0
  30. package/build/utils/cache/messages_cache.d.ts.map +1 -1
  31. package/build/utils/cache/messages_cache.js +10 -1
  32. package/build/utils/cache/messages_cache.js.map +1 -1
  33. package/build/utils/client/transform_response.d.ts.map +1 -1
  34. package/build/utils/client/transform_response.js +9 -5
  35. package/build/utils/client/transform_response.js.map +1 -1
  36. package/build/utils/group_messages.d.ts +1 -0
  37. package/build/utils/group_messages.d.ts.map +1 -1
  38. package/build/utils/group_messages.js +10 -1
  39. package/build/utils/group_messages.js.map +1 -1
  40. package/build/utils/replace_equal_by_id.d.ts +6 -0
  41. package/build/utils/replace_equal_by_id.d.ts.map +1 -0
  42. package/build/utils/replace_equal_by_id.js +41 -0
  43. package/build/utils/replace_equal_by_id.js.map +1 -0
  44. package/build/utils/request/messages_data_options.d.ts.map +1 -1
  45. package/build/utils/request/messages_data_options.js +1 -1
  46. package/build/utils/request/messages_data_options.js.map +1 -1
  47. package/package.json +2 -2
  48. package/src/components/conversation/__tests__/message_list.test.tsx +277 -0
  49. package/src/components/conversation/__tests__/reply_shadow_message.test.tsx +119 -0
  50. package/src/components/conversation/message.tsx +15 -18
  51. package/src/components/conversation/message_list.tsx +157 -0
  52. package/src/components/conversation/message_read_receipts.tsx +3 -5
  53. package/src/components/conversation/reply_shadow_message.tsx +9 -7
  54. package/src/hooks/use_conversation_messages.ts +5 -1
  55. package/src/hooks/use_conversation_messages_jolt_events.ts +7 -0
  56. package/src/screens/conversation_screen.tsx +11 -104
  57. package/src/types/resources/message.ts +1 -0
  58. package/src/utils/__tests__/group_messages.test.ts +48 -0
  59. package/src/utils/__tests__/replace_equal_by_id.test.ts +73 -0
  60. package/src/utils/cache/__tests__/messages_cache_reply_roots.test.ts +70 -0
  61. package/src/utils/cache/messages_cache.ts +21 -1
  62. package/src/utils/client/__tests__/transform_response.test.ts +62 -0
  63. package/src/utils/client/transform_response.ts +7 -5
  64. package/src/utils/group_messages.ts +18 -1
  65. package/src/utils/replace_equal_by_id.ts +42 -0
  66. package/src/utils/request/messages_data_options.ts +1 -1
@@ -1,17 +1,15 @@
1
1
  import React from 'react'
2
2
  import { StyleSheet, View } from 'react-native'
3
3
  import { useTheme } from '../../hooks'
4
- import { MessageResource } from '../../types'
5
4
  import { Icon, Text } from '../display'
6
5
 
7
6
  interface Props {
8
- message: MessageResource
9
- latestReadMessageSortKey?: string
7
+ read?: boolean
10
8
  }
11
9
 
12
- export function MessageReadReceipts({ message, latestReadMessageSortKey }: Props) {
10
+ export function MessageReadReceipts({ read }: Props) {
13
11
  const styles = useStyles()
14
- if (!latestReadMessageSortKey || message.id > latestReadMessageSortKey) {
12
+ if (!read) {
15
13
  return (
16
14
  <View style={styles.badgeContainer}>
17
15
  <Icon name="general.check" style={styles.icon} />
@@ -1,6 +1,6 @@
1
1
  import { useNavigation } from '@react-navigation/native'
2
2
  import { some } from 'lodash'
3
- import React from 'react'
3
+ import React, { memo } from 'react'
4
4
  import { Pressable, StyleSheet, useWindowDimensions, View } from 'react-native'
5
5
  import Animated from 'react-native-reanimated'
6
6
  import {
@@ -37,18 +37,20 @@ interface ReplyShadowMessageProps extends MessageResource {
37
37
  nextRendersAuthor: boolean
38
38
  }
39
39
 
40
- export function ReplyShadowMessage({
40
+ export const ReplyShadowMessage = memo(function ReplyShadowMessageRow({
41
41
  conversation_id,
42
42
  inReplyScreen,
43
43
  messageId,
44
+ replyRoot,
44
45
  isReplyShadowMessage,
45
46
  nextRendersAuthor,
46
47
  }: ReplyShadowMessageProps) {
47
- const { message, isError, isLoading } = useConversationMessage({ conversation_id, messageId })
48
+ const fetched = useConversationMessage({ conversation_id, messageId, enabled: !replyRoot })
49
+ const message = replyRoot ?? fetched.message
48
50
 
49
51
  if (inReplyScreen) return null
50
- if (isLoading) return <ShadowMessageFallback text="Loading..." />
51
- if (isError || !message) return <ShadowMessageFallback text="Message deleted" />
52
+ if (!message && fetched.isLoading) return <ShadowMessageFallback text="Loading..." />
53
+ if (!message) return <ShadowMessageFallback text="Message deleted" />
52
54
 
53
55
  const enrichedMessage = {
54
56
  ...message,
@@ -57,7 +59,7 @@ export function ReplyShadowMessage({
57
59
  }
58
60
 
59
61
  return <ShadowMessageContent conversation_id={conversation_id} {...enrichedMessage} />
60
- }
62
+ })
61
63
 
62
64
  interface ShadowMessageContentProps extends MessageResource {
63
65
  conversation_id: number
@@ -82,7 +84,7 @@ function ShadowMessageContent({ conversation_id, ...message }: ShadowMessageCont
82
84
  const handleNavigateToReplies = () => {
83
85
  navigation.navigate('ConversationReply', {
84
86
  conversation_id,
85
- reply_root_id: message.replyRootId,
87
+ reply_root_id: message.replyRootId ?? message.id,
86
88
  reply_root_author_name: message.author.name,
87
89
  })
88
90
  }
@@ -1,5 +1,6 @@
1
1
  import { useMemo } from 'react'
2
2
  import { MessageResource } from '../types'
3
+ import { replaceEqualById } from '../utils/replace_equal_by_id'
3
4
  import { getMessagesQueryKey, getMessagesRequestArgs } from '../utils/request/get_messages'
4
5
  import { SuspensePaginatorOptions, useSuspensePaginator } from './use_suspense_api'
5
6
 
@@ -10,7 +11,10 @@ export const useConversationMessages = (
10
11
  const { data, refetch, isRefetching, fetchNextPage, hasNextPage } =
11
12
  useSuspensePaginator<MessageResource>(
12
13
  getMessagesRequestArgs({ conversation_id, reply_root_id }),
13
- opts
14
+ {
15
+ structuralSharing: replaceEqualById,
16
+ ...opts,
17
+ }
14
18
  )
15
19
  const queryKey = getMessagesQueryKey({ conversation_id, reply_root_id })
16
20
  const messages = useMemo(
@@ -11,6 +11,7 @@ import {
11
11
  updateCacheWithMessage,
12
12
  updateCacheWithIndividualMessage,
13
13
  updateCacheWithReaction,
14
+ updateCacheReplyRoots,
14
15
  getThreadedMessagesQueryKey,
15
16
  } from '../utils/cache/messages_cache'
16
17
  import { transformMessageEventDataToMessageResource } from '../utils/jolt/transform_message_event_data_to_message_resource'
@@ -44,6 +45,7 @@ export function useConversationMessagesJoltEvents({ conversationId }: Props) {
44
45
  data,
45
46
  currentPersonId: currentPerson.id,
46
47
  })
48
+ const isReplyRootUpdate = e.event === 'message.updated' && data.reply_root_id === data.sort_key
47
49
 
48
50
  if (e.event === 'message.created' && data.author_id) {
49
51
  removeAllTypingEventsByAuthorId(data.author_id)
@@ -62,6 +64,11 @@ export function useConversationMessagesJoltEvents({ conversationId }: Props) {
62
64
  data.reply_root_id
63
65
  )
64
66
  updateCacheWithMessage(queryClient, threadedMessagesQueryKey, message, e.event)
67
+
68
+ if (isReplyRootUpdate) {
69
+ updateCacheReplyRoots(queryClient, messagesQueryKey, message)
70
+ updateCacheReplyRoots(queryClient, threadedMessagesQueryKey, message)
71
+ }
65
72
  }
66
73
 
67
74
  // Update individual message query cache so reply shadow messages update immediately
@@ -1,4 +1,3 @@
1
- import { date as formatDate } from '@planningcenter/datetime-fmt'
2
1
  import { HeaderTitle, HeaderTitleProps, PlatformPressable } from '@react-navigation/elements'
3
2
  import {
4
3
  CommonActions,
@@ -11,24 +10,21 @@ import {
11
10
  import React, { useCallback, useEffect, useRef, useState } from 'react'
12
11
  import { FlatList, Platform, StyleSheet, useWindowDimensions, View } from 'react-native'
13
12
  import { useSafeAreaInsets } from 'react-native-safe-area-context'
14
- import { Badge, Icon, Text } from '../components'
13
+ import { Badge, Icon } from '../components'
15
14
  import { ConversationStartBanner } from '../components/conversation/conversation_start_banner'
16
15
  import { JumpToBottomButton } from '../components/conversation/jump_to_bottom_button'
17
- import { Message } from '../components/conversation/message'
18
16
  import { MessageForm } from '../components/conversation/message_form'
17
+ import { MessageList } from '../components/conversation/message_list'
19
18
  import {
20
19
  ConversationDisabledBanner,
21
20
  LeaderMessagesDisabledBanner,
22
21
  MemberMessagesDisabledBanner,
23
22
  } from '../components/conversation/messages_disabled_banners'
24
- import { ReplyShadowMessage } from '../components/conversation/reply_shadow_message'
25
- import { SystemMessage } from '../components/conversation/system_message'
26
23
  import { TypingIndicator } from '../components/conversation/typing_indicator'
27
24
  import { KeyboardView } from '../components/display/keyboard_view'
28
25
  import { useHeaderSlotReserve } from '../components/display/platform_modal_header_buttons'
29
26
  import BlankState from '../components/primitive/blank_state_primitive'
30
27
  import { ConversationContextProvider } from '../contexts/conversation_context'
31
- import { useTheme } from '../hooks'
32
28
  import { useMessageAvailableMembersAction } from '../hooks/direct_messages/use_message_available_members_action'
33
29
  import { useConversation } from '../hooks/use_conversation'
34
30
  import { useConversationJoltEvents } from '../hooks/use_conversation_jolt_events'
@@ -45,10 +41,6 @@ import { useVideoModerationJoltEvents } from '../hooks/use_video_moderation_jolt
45
41
  import { ConversationResource } from '../types/resources/conversation'
46
42
  import { ConversationBadgeResource } from '../types/resources/conversation_badge'
47
43
  import { MessageResource } from '../types/resources/message'
48
- import { getRelativeDateStatus } from '../utils/date'
49
- import { groupMessages, type DateSeparator } from '../utils/group_messages'
50
- import { CONVERSATION_MESSAGE_LIST_PADDING_HORIZONTAL } from '../utils/styles'
51
- import { isSystemMessage } from '../utils/system_messages'
52
44
 
53
45
  export type ConversationRouteProps = {
54
46
  conversation_id: number
@@ -101,16 +93,11 @@ function ConversationScreenContent({ route }: ConversationScreenProps) {
101
93
  const { markHandledByMessageForm } = useVideoModerationJoltEvents()
102
94
  useEnsureConversationsRouteExists()
103
95
  useMarkLatestMessageRead({ conversation, messages })
104
- const messagesWithSeparators = groupMessages({
105
- ms: messages,
106
- inReplyScreen: !!reply_root_id,
107
- })
108
- const noMessages = messagesWithSeparators.length === 0
96
+ const noMessages = messages.length === 0
109
97
 
110
98
  const { repliesDisabled, memberAbility, badges, title } = conversation
111
99
  const canReply = memberAbility?.canReply
112
100
  const showLeaderDisabledReplyBanner = canReply && repliesDisabled
113
- const canDeleteNonAuthoredMessages = memberAbility?.canDeleteNonAuthoredMessages ?? false
114
101
  const currentlyEditingMessage = messages.find(m => String(m.id) === String(editing_message_id))
115
102
  const replyRootAuthorFirstName = reply_root_author_name?.split(' ')[0]
116
103
  const replyHeaderTitle = replyRootAuthorFirstName
@@ -181,54 +168,19 @@ function ConversationScreenContent({ route }: ConversationScreenProps) {
181
168
  <ConversationStartBanner conversation={conversation} hasMessages={false} />
182
169
  </View>
183
170
  ) : (
184
- <FlatList
185
- inverted
186
- ref={listRef}
187
- contentContainerStyle={styles.listContainer}
188
- data={messagesWithSeparators}
189
- keyExtractor={item => item.id}
171
+ <MessageList
172
+ listRef={listRef}
173
+ conversation={conversation}
174
+ conversationId={conversation_id}
175
+ messages={messages}
176
+ replyRootId={reply_root_id}
177
+ hasNextPage={hasNextPage}
178
+ onEndReached={() => fetchNextPage()}
190
179
  onScroll={trackScroll}
191
180
  onLayout={onLayout}
192
181
  onContentSizeChange={onContentSizeChange}
193
182
  onScrollEndDrag={onScrollEndDrag}
194
183
  onMomentumScrollEnd={onMomentumScrollEnd}
195
- scrollEventThrottle={10}
196
- ListFooterComponent={
197
- hasNextPage ? null : (
198
- <ConversationStartBanner conversation={conversation} hasMessages={true} />
199
- )
200
- }
201
- renderItem={({ item }) => {
202
- if (item.type === 'DateSeparator') {
203
- return <InlineDateSeparator {...item} />
204
- }
205
-
206
- if (item.type === 'ReplyShadowMessage') {
207
- return (
208
- <ReplyShadowMessage
209
- {...(item as any)}
210
- conversation_id={conversation_id}
211
- inReplyScreen={!!reply_root_id}
212
- />
213
- )
214
- }
215
-
216
- if (isSystemMessage(item)) {
217
- return <SystemMessage message={item} conversationId={conversation_id} />
218
- }
219
-
220
- return (
221
- <Message
222
- {...item}
223
- canDeleteNonAuthoredMessages={canDeleteNonAuthoredMessages}
224
- conversation_id={conversation_id}
225
- latestReadMessageSortKey={conversation?.latestReadMessageSortKey}
226
- inReplyScreen={!!reply_root_id}
227
- />
228
- )
229
- }}
230
- onEndReached={() => fetchNextPage()}
231
- ListHeaderComponent={<View style={styles.listHeader} />}
232
184
  />
233
185
  )}
234
186
  <JumpToBottomButton onPress={handleReturnToBottom} visible={showJumpToBottomButton} />
@@ -295,44 +247,6 @@ function ConversationBottomBar({
295
247
  )
296
248
  }
297
249
 
298
- function InlineDateSeparator({ date }: DateSeparator) {
299
- const styles = useDateSeparatorStyles()
300
- const { isThisYear } = getRelativeDateStatus(date)
301
- const showYear = !isThisYear
302
- const dateStamp = formatDate(date, { style: 'long', year: showYear })
303
-
304
- return (
305
- <View style={styles.container}>
306
- <View style={styles.separator} />
307
- <Text variant="footnote" style={styles.dateText}>
308
- {dateStamp}
309
- </Text>
310
- <View style={styles.separator} />
311
- </View>
312
- )
313
- }
314
-
315
- const useDateSeparatorStyles = () => {
316
- const theme = useTheme()
317
- return StyleSheet.create({
318
- container: {
319
- alignItems: 'center',
320
- flexDirection: 'row',
321
- paddingHorizontal: CONVERSATION_MESSAGE_LIST_PADDING_HORIZONTAL,
322
- paddingVertical: 16,
323
- },
324
- separator: {
325
- flex: 1,
326
- height: 1,
327
- borderTopWidth: 1,
328
- borderTopColor: theme.colors.borderColorDefaultBase,
329
- },
330
- dateText: {
331
- paddingHorizontal: 8,
332
- },
333
- })
334
- }
335
-
336
250
  interface ConversationScreenTitleProps extends HeaderTitleProps {
337
251
  conversation_id: number
338
252
  badge?: ConversationBadgeResource
@@ -429,13 +343,6 @@ const useStyles = () => {
429
343
  flex: 1,
430
344
  justifyContent: 'center',
431
345
  },
432
- listContainer: {
433
- paddingVertical: 12,
434
- },
435
- listHeader: {
436
- // Just whitespace to provide space where the typing indicator can be
437
- height: 16,
438
- },
439
346
  })
440
347
  }
441
348
 
@@ -17,6 +17,7 @@ export interface MessageResource {
17
17
  reactionCounts: ReactionCountResource[]
18
18
  replyCount: number
19
19
  replyRootId?: string | null
20
+ replyRoot?: MessageResource | null
20
21
  idempotentKey?: string | null
21
22
  messageType: string
22
23
  personIdsForSystemEvent?: number[] | null
@@ -124,6 +124,54 @@ describe('groupMessages — nextRendersAuthor mirrors the newer enriched neighbo
124
124
  })
125
125
  })
126
126
 
127
+ describe('groupMessages — reply roots', () => {
128
+ const findShadow = (items: ReturnType<typeof groupMessages>, id: string) =>
129
+ items.find(item => 'type' in item && item.type === 'ReplyShadowMessage' && item.id === id)
130
+
131
+ it('carries the root from the page onto the reply and its shadow', () => {
132
+ const messages = [
133
+ message('03', { replyRootId: 'rootA' }),
134
+ message('02'),
135
+ message('rootA', { replyRootId: 'rootA', text: 'fresh' }),
136
+ ]
137
+
138
+ const enriched = groupMessages({ ms: messages })
139
+
140
+ expect((findEnriched(enriched, '03') as MessageResource).replyRoot?.text).toBe('fresh')
141
+ expect(findShadow(enriched, '03-rootA')).toMatchObject({ replyRoot: { id: 'rootA' } })
142
+ })
143
+
144
+ it('prefers the page copy of the root over the reply’s included snapshot', () => {
145
+ const snapshot = message('rootA', { replyRootId: 'rootA', text: 'stale' })
146
+ const messages = [
147
+ message('03', { replyRootId: 'rootA', replyRoot: snapshot }),
148
+ message('02'),
149
+ message('rootA', { replyRootId: 'rootA', text: 'fresh' }),
150
+ ]
151
+
152
+ const enriched = groupMessages({ ms: messages })
153
+
154
+ expect(findShadow(enriched, '03-rootA')).toMatchObject({ replyRoot: { text: 'fresh' } })
155
+ })
156
+
157
+ it('falls back to the included snapshot when the root is not on the page', () => {
158
+ const snapshot = message('rootA', { replyRootId: 'rootA', text: 'included' })
159
+ const messages = [message('02', { replyRootId: 'rootA', replyRoot: snapshot })]
160
+
161
+ const enriched = groupMessages({ ms: messages })
162
+
163
+ expect(findShadow(enriched, '02-rootA')).toMatchObject({ replyRoot: { text: 'included' } })
164
+ })
165
+
166
+ it('leaves replyRoot null when the root is neither on the page nor included', () => {
167
+ const messages = [message('02', { replyRootId: 'rootA' })]
168
+
169
+ const enriched = groupMessages({ ms: messages })
170
+
171
+ expect(findShadow(enriched, '02-rootA')).toMatchObject({ replyRoot: null })
172
+ })
173
+ })
174
+
127
175
  describe('groupMessages — system messages', () => {
128
176
  it('flags lastInGroup true and renderAuthor false on system messages', () => {
129
177
  const messages = [
@@ -0,0 +1,73 @@
1
+ import { replaceEqualById } from '../replace_equal_by_id'
2
+
3
+ type Record = { type: 'Message'; id: string; text: string; attachments: string[] }
4
+ type Pages = { pages: { data: Record[]; links: {}; meta: {} }[]; pageParams: unknown[] }
5
+
6
+ const record = (id: string, text = id): Record => ({ type: 'Message', id, text, attachments: [] })
7
+ const pagesOf = (...pages: Record[][]): Pages => ({
8
+ pages: pages.map(data => ({ data, links: {}, meta: {} })),
9
+ pageParams: pages.map(() => ({})),
10
+ })
11
+
12
+ const share = (prev: Pages, next: Pages) => replaceEqualById(prev, next) as Pages
13
+
14
+ describe('replaceEqualById', () => {
15
+ it('returns the previous data when nothing changed', () => {
16
+ const prev = pagesOf([record('c'), record('b')], [record('a')])
17
+ const next = pagesOf([record('c'), record('b')], [record('a')])
18
+
19
+ expect(share(prev, next)).toBe(prev)
20
+ })
21
+
22
+ it('keeps every existing record when one is inserted at the head', () => {
23
+ const [c, b] = [record('c'), record('b')]
24
+ const prev = pagesOf([c, b])
25
+ const next = pagesOf([record('d'), record('c'), record('b')])
26
+
27
+ const result = share(prev, next)
28
+
29
+ expect(result.pages[0].data[1]).toBe(c)
30
+ expect(result.pages[0].data[2]).toBe(b)
31
+ expect(result.pages[0].data[0].id).toBe('d')
32
+ })
33
+
34
+ it('keeps the survivors when a record is removed', () => {
35
+ const [c, b, a] = [record('c'), record('b'), record('a')]
36
+ const prev = pagesOf([c, b, a])
37
+ const next = pagesOf([record('c'), record('a')])
38
+
39
+ const result = share(prev, next)
40
+
41
+ expect(result.pages[0].data).toEqual([c, a])
42
+ expect(result.pages[0].data[0]).toBe(c)
43
+ expect(result.pages[0].data[1]).toBe(a)
44
+ })
45
+
46
+ it('replaces only the changed record and keeps its untouched nested references', () => {
47
+ const b = record('b')
48
+ const prev = pagesOf([record('c'), b])
49
+ const next = pagesOf([record('c'), { ...record('b', 'edited'), attachments: [] }])
50
+
51
+ const result = share(prev, next)
52
+
53
+ expect(result.pages[0].data[0]).toBe(prev.pages[0].data[0])
54
+ expect(result.pages[0].data[1]).not.toBe(b)
55
+ expect(result.pages[0].data[1].text).toBe('edited')
56
+ expect(result.pages[0].data[1].attachments).toBe(b.attachments)
57
+ })
58
+
59
+ it('keeps untouched pages when only another page changed', () => {
60
+ const prev = pagesOf([record('c')], [record('a')])
61
+ const next = pagesOf([record('d'), record('c')], [record('a')])
62
+
63
+ const result = share(prev, next)
64
+
65
+ expect(result.pages[1]).toBe(prev.pages[1])
66
+ })
67
+
68
+ it('returns the new data when there is nothing to share with', () => {
69
+ const next = pagesOf([record('a')])
70
+
71
+ expect(replaceEqualById(undefined, next)).toBe(next)
72
+ })
73
+ })
@@ -0,0 +1,70 @@
1
+ import { InfiniteData, QueryClient } from '@tanstack/react-query'
2
+ import type { ApiCollection } from '../../../types'
3
+ import type { MessageResource } from '../../../types/resources/message'
4
+ import type { PersonResource } from '../../../types/resources/person'
5
+ import { updateCacheReplyRoots } from '../messages_cache'
6
+
7
+ const author = { id: 1, type: 'Person', name: 'A', avatar: null } as unknown as PersonResource
8
+
9
+ const message = (id: string, overrides: Partial<MessageResource> = {}): MessageResource =>
10
+ ({
11
+ type: 'Message',
12
+ id,
13
+ text: `msg ${id}`,
14
+ html: '',
15
+ createdAt: '2026-01-01T00:00:00Z',
16
+ deletedAt: null,
17
+ textEditedAt: null,
18
+ mine: false,
19
+ attachments: [],
20
+ author,
21
+ reactionCounts: [],
22
+ replyCount: 0,
23
+ replyRootId: null,
24
+ messageType: 'message',
25
+ ...overrides,
26
+ }) as MessageResource
27
+
28
+ const queryKey = ['messages']
29
+
30
+ const seedPages = (queryClient: QueryClient, messages: MessageResource[]) => {
31
+ queryClient.setQueryData<InfiniteData<ApiCollection<MessageResource>>>(queryKey, {
32
+ pageParams: [{}],
33
+ pages: [{ data: messages, links: {}, meta: { count: messages.length, totalCount: 1 } }],
34
+ })
35
+ }
36
+
37
+ const pageMessages = (queryClient: QueryClient) =>
38
+ queryClient.getQueryData<InfiniteData<ApiCollection<MessageResource>>>(queryKey)!.pages[0].data
39
+
40
+ describe('updateCacheReplyRoots', () => {
41
+ it('merges a root update into every reply carrying that root', () => {
42
+ const queryClient = new QueryClient()
43
+ const root = message('rootA', { replyRootId: 'rootA', text: 'before' })
44
+ seedPages(queryClient, [
45
+ message('03', { replyRootId: 'rootA', replyRoot: root }),
46
+ message('02', { replyRootId: 'rootB', replyRoot: message('rootB', { text: 'other' }) }),
47
+ message('01', { replyRootId: 'rootA', replyRoot: root }),
48
+ ])
49
+
50
+ updateCacheReplyRoots(
51
+ queryClient,
52
+ queryKey,
53
+ message('rootA', { replyRootId: 'rootA', text: 'after', deletedAt: '2026-01-02T00:00:00Z' })
54
+ )
55
+
56
+ const [newest, other, oldest] = pageMessages(queryClient)
57
+ expect(newest.replyRoot).toMatchObject({ text: 'after', deletedAt: '2026-01-02T00:00:00Z' })
58
+ expect(oldest.replyRoot).toMatchObject({ text: 'after' })
59
+ expect(other.replyRoot?.text).toBe('other')
60
+ })
61
+
62
+ it('ignores replies without an inline root', () => {
63
+ const queryClient = new QueryClient()
64
+ seedPages(queryClient, [message('01', { replyRootId: 'rootA' })])
65
+
66
+ updateCacheReplyRoots(queryClient, queryKey, message('rootA', { replyRootId: 'rootA' }))
67
+
68
+ expect(pageMessages(queryClient)[0].replyRoot).toBeUndefined()
69
+ })
70
+ })
@@ -4,7 +4,11 @@ import { ApiCollection, ApiResource, MessageResource } from '../../types'
4
4
  import { JoltReactionEvent } from '../../types/jolt_events'
5
5
  import { transformReactionEventDataToReactionCountResource } from '../jolt/transform_reaction_event_data_to_reaction_count_resource'
6
6
  import { getMessagesRequestArgs } from '../request/get_messages'
7
- import { updateOrCreateRecordInPagesData, updateRecordInPagesData } from './page_mutations'
7
+ import {
8
+ updateAllRecordsInPagesData,
9
+ updateOrCreateRecordInPagesData,
10
+ updateRecordInPagesData,
11
+ } from './page_mutations'
8
12
  import { deleteRecordInPagesData } from './page_mutations'
9
13
 
10
14
  export function updateCacheWithMessage(
@@ -66,6 +70,22 @@ export function updateCacheWithIndividualMessage(
66
70
  })
67
71
  }
68
72
 
73
+ export function updateCacheReplyRoots(
74
+ queryClient: QueryClient,
75
+ queryKey: unknown[],
76
+ root: MessageResource
77
+ ) {
78
+ queryClient.setQueryData<MessagesQueryData>(queryKey, prev =>
79
+ updateAllRecordsInPagesData({
80
+ data: prev,
81
+ processRecord: message =>
82
+ message.replyRoot?.id === root.id
83
+ ? { ...message, replyRoot: mergeMessageUpdate(root, message.replyRoot) }
84
+ : message,
85
+ })
86
+ )
87
+ }
88
+
69
89
  export function updateCacheWithReaction(
70
90
  queryClient: QueryClient,
71
91
  queryKey: unknown[],
@@ -0,0 +1,62 @@
1
+ import transformResponse from '../transform_response'
2
+
3
+ const person = (id: string, name: string) => ({
4
+ type: 'Person',
5
+ id,
6
+ attributes: { name, avatar: null },
7
+ })
8
+
9
+ const message = (
10
+ id: string,
11
+ { authorId, replyRootId }: { authorId: string; replyRootId: string | null }
12
+ ) => ({
13
+ type: 'Message',
14
+ id,
15
+ attributes: { text: `msg ${id}` },
16
+ relationships: {
17
+ author: { data: { type: 'Person', id: authorId } },
18
+ reply_root: { data: replyRootId ? { type: 'Message', id: replyRootId } : null },
19
+ reaction_counts: { data: [] },
20
+ },
21
+ })
22
+
23
+ const root = message('01ROOT', { authorId: '2', replyRootId: '01ROOT' })
24
+ const reply = message('01REPLY', { authorId: '1', replyRootId: '01ROOT' })
25
+
26
+ describe('transformResponse — reply_root include', () => {
27
+ it('attaches the included root and its author to a reply', () => {
28
+ const result = transformResponse({
29
+ data: [reply],
30
+ included: [root, person('1', 'Replier'), person('2', 'Root Author')],
31
+ })
32
+
33
+ const [transformedReply] = result.data
34
+ expect(transformedReply.replyRootId).toBe('01ROOT')
35
+ expect(transformedReply.replyRoot.id).toBe('01ROOT')
36
+ expect(transformedReply.replyRoot.text).toBe('msg 01ROOT')
37
+ expect(transformedReply.replyRoot.author.name).toBe('Root Author')
38
+ })
39
+
40
+ it('drops a record’s self reference so the result stays acyclic', () => {
41
+ const result = transformResponse({
42
+ data: [reply, root],
43
+ included: [root, person('1', 'Replier'), person('2', 'Root Author')],
44
+ })
45
+
46
+ const [transformedReply, transformedRoot] = result.data
47
+ expect(transformedReply.replyRoot.replyRoot).toBeNull()
48
+ expect(transformedRoot.replyRootId).toBe('01ROOT')
49
+ expect(transformedRoot.replyRoot).toBeNull()
50
+ expect(() => JSON.stringify(result)).not.toThrow()
51
+ })
52
+
53
+ it('leaves replyRoot null when the root is not included', () => {
54
+ const result = transformResponse({
55
+ data: [reply],
56
+ included: [person('1', 'Replier')],
57
+ })
58
+
59
+ expect(result.data[0].replyRootId).toBe('01ROOT')
60
+ expect(result.data[0].replyRoot).toBeNull()
61
+ })
62
+ })
@@ -32,7 +32,8 @@ const transformRelationships = relationships => {
32
32
  }, {})
33
33
  }
34
34
 
35
- const addIncludedRecords = (relationships, included, seen, parent) => {
35
+ const addIncludedRecords = (record, included, seen, parent) => {
36
+ const { relationships } = record
36
37
  return Object.keys(relationships || {}).reduce((acc, key) => {
37
38
  const relationship = relationships[key]
38
39
  if (_.isArray(relationship.data)) {
@@ -43,13 +44,14 @@ const addIncludedRecords = (relationships, included, seen, parent) => {
43
44
  return _.set(
44
45
  acc,
45
46
  _.pluralize(key),
46
- _.map(records, record => transformRecord(record, included, seen))
47
+ _.map(records, related => transformRecord(related, included, seen))
47
48
  )
48
49
  } else {
49
50
  const [id, type] = _.at(relationship, ['data.id', 'data.type'])
50
51
  if (id && type) {
51
- const record = _.find(included, { id, type })
52
- return _.set(acc, key, record ? transformRecord(record, included, seen) : null)
52
+ const isSelfReference = id === record.id && type === record.type
53
+ const related = isSelfReference ? undefined : _.find(included, { id, type })
54
+ return _.set(acc, key, related ? transformRecord(related, included, seen) : null)
53
55
  } else {
54
56
  return acc
55
57
  }
@@ -78,7 +80,7 @@ const transformRecord = (record, included, seen) => {
78
80
 
79
81
  seen.set(record, transformed)
80
82
 
81
- return addIncludedRecords(relationships, included, seen, transformed)
83
+ return addIncludedRecords(record, included, seen, transformed)
82
84
  }
83
85
  }
84
86