@planningcenter/chat-react-native 4.7.1-qa-staging.8 → 4.7.1-qa-1119.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 (175) hide show
  1. package/build/components/conversations/bulk_conversation_actions_bar.d.ts +2 -0
  2. package/build/components/conversations/bulk_conversation_actions_bar.d.ts.map +1 -0
  3. package/build/components/conversations/bulk_conversation_actions_bar.js +215 -0
  4. package/build/components/conversations/bulk_conversation_actions_bar.js.map +1 -0
  5. package/build/components/conversations/conversation_actions.d.ts +2 -1
  6. package/build/components/conversations/conversation_actions.d.ts.map +1 -1
  7. package/build/components/conversations/conversation_actions.js +173 -130
  8. package/build/components/conversations/conversation_actions.js.map +1 -1
  9. package/build/components/conversations/conversation_preview.d.ts.map +1 -1
  10. package/build/components/conversations/conversation_preview.js +168 -110
  11. package/build/components/conversations/conversation_preview.js.map +1 -1
  12. package/build/components/conversations/conversations.d.ts.map +1 -1
  13. package/build/components/conversations/conversations.js +50 -48
  14. package/build/components/conversations/conversations.js.map +1 -1
  15. package/build/components/display/checkbox.d.ts +8 -0
  16. package/build/components/display/checkbox.d.ts.map +1 -0
  17. package/build/components/display/checkbox.js +87 -0
  18. package/build/components/display/checkbox.js.map +1 -0
  19. package/build/components/display/icon.d.ts +3 -1
  20. package/build/components/display/icon.d.ts.map +1 -1
  21. package/build/components/display/icon.js +2 -0
  22. package/build/components/display/icon.js.map +1 -1
  23. package/build/components/display/index.d.ts +1 -0
  24. package/build/components/display/index.d.ts.map +1 -1
  25. package/build/components/display/index.js +1 -0
  26. package/build/components/display/index.js.map +1 -1
  27. package/build/contexts/api_provider.d.ts.map +1 -1
  28. package/build/contexts/api_provider.js +2 -0
  29. package/build/contexts/api_provider.js.map +1 -1
  30. package/build/contexts/conversations_context.d.ts +5 -0
  31. package/build/contexts/conversations_context.d.ts.map +1 -1
  32. package/build/contexts/conversations_context.js +121 -32
  33. package/build/contexts/conversations_context.js.map +1 -1
  34. package/build/contexts/session_context.d.ts +0 -1
  35. package/build/contexts/session_context.d.ts.map +1 -1
  36. package/build/contexts/session_context.js +3 -0
  37. package/build/contexts/session_context.js.map +1 -1
  38. package/build/hooks/use_bulk_conversation_actions.d.ts +8 -0
  39. package/build/hooks/use_bulk_conversation_actions.d.ts.map +1 -0
  40. package/build/hooks/use_bulk_conversation_actions.js +309 -0
  41. package/build/hooks/use_bulk_conversation_actions.js.map +1 -0
  42. package/build/hooks/use_conversation_jolt_events.d.ts.map +1 -1
  43. package/build/hooks/use_conversation_jolt_events.js +3 -2
  44. package/build/hooks/use_conversation_jolt_events.js.map +1 -1
  45. package/build/hooks/use_conversations_actions.d.ts +9 -9
  46. package/build/hooks/use_conversations_actions.d.ts.map +1 -1
  47. package/build/hooks/use_conversations_actions.js +12 -7
  48. package/build/hooks/use_conversations_actions.js.map +1 -1
  49. package/build/hooks/use_conversations_cache.d.ts +15 -5
  50. package/build/hooks/use_conversations_cache.d.ts.map +1 -1
  51. package/build/hooks/use_conversations_cache.js +170 -122
  52. package/build/hooks/use_conversations_cache.js.map +1 -1
  53. package/build/hooks/use_conversations_jolt_events.d.ts.map +1 -1
  54. package/build/hooks/use_conversations_jolt_events.js +47 -20
  55. package/build/hooks/use_conversations_jolt_events.js.map +1 -1
  56. package/build/hooks/use_mark_latest_message_read.d.ts.map +1 -1
  57. package/build/hooks/use_mark_latest_message_read.js +5 -4
  58. package/build/hooks/use_mark_latest_message_read.js.map +1 -1
  59. package/build/navigation/index.d.ts.map +1 -1
  60. package/build/navigation/index.js +5 -7
  61. package/build/navigation/index.js.map +1 -1
  62. package/build/screens/conversation_actions_screen.d.ts +2 -0
  63. package/build/screens/conversation_actions_screen.d.ts.map +1 -1
  64. package/build/screens/conversation_actions_screen.js +380 -46
  65. package/build/screens/conversation_actions_screen.js.map +1 -1
  66. package/build/screens/conversation_filter_recipients/components/checkbox_row.d.ts.map +1 -1
  67. package/build/screens/conversation_filter_recipients/components/checkbox_row.js +9 -64
  68. package/build/screens/conversation_filter_recipients/components/checkbox_row.js.map +1 -1
  69. package/build/screens/conversations/conversations_screen.d.ts +5 -0
  70. package/build/screens/conversations/conversations_screen.d.ts.map +1 -1
  71. package/build/screens/conversations/conversations_screen.js +156 -31
  72. package/build/screens/conversations/conversations_screen.js.map +1 -1
  73. package/build/types/jolt_events/index.d.ts +2 -0
  74. package/build/types/jolt_events/index.d.ts.map +1 -1
  75. package/build/types/jolt_events/index.js.map +1 -1
  76. package/build/types/jolt_events/person_events.d.ts +9 -0
  77. package/build/types/jolt_events/person_events.d.ts.map +1 -0
  78. package/build/types/jolt_events/person_events.js +2 -0
  79. package/build/types/jolt_events/person_events.js.map +1 -0
  80. package/build/utils/jolt/parse_stream_user_event_type.d.ts +3 -0
  81. package/build/utils/jolt/parse_stream_user_event_type.d.ts.map +1 -0
  82. package/build/utils/jolt/parse_stream_user_event_type.js +9 -0
  83. package/build/utils/jolt/parse_stream_user_event_type.js.map +1 -0
  84. package/build/utils/native_adapters/configuration.d.ts +3 -0
  85. package/build/utils/native_adapters/configuration.d.ts.map +1 -1
  86. package/build/utils/native_adapters/configuration.js +3 -0
  87. package/build/utils/native_adapters/configuration.js.map +1 -1
  88. package/build/utils/native_adapters/index.d.ts +1 -0
  89. package/build/utils/native_adapters/index.d.ts.map +1 -1
  90. package/build/utils/native_adapters/index.js +1 -0
  91. package/build/utils/native_adapters/index.js.map +1 -1
  92. package/build/utils/native_adapters/updates.d.ts +11 -0
  93. package/build/utils/native_adapters/updates.d.ts.map +1 -0
  94. package/build/utils/native_adapters/updates.js +8 -0
  95. package/build/utils/native_adapters/updates.js.map +1 -0
  96. package/build/utils/throttled_refresh.d.ts +7 -0
  97. package/build/utils/throttled_refresh.d.ts.map +1 -0
  98. package/build/utils/throttled_refresh.js +42 -0
  99. package/build/utils/throttled_refresh.js.map +1 -0
  100. package/package.json +3 -3
  101. package/src/__tests__/contexts/session_context.tsx +19 -39
  102. package/src/__tests__/hooks/useTheme.tsx +0 -7
  103. package/src/__tests__/hooks/use_async_storage.test.tsx +1 -87
  104. package/src/__tests__/hooks/use_attachment_uploader.test.tsx +0 -11
  105. package/src/__tests__/hooks/use_font_scale.test.ts +0 -25
  106. package/src/__tests__/utils/cache/page_mutations.ts +3 -68
  107. package/src/__tests__/utils/client.ts +6 -15
  108. package/src/__tests__/utils/native_adapters/configuration.ts +15 -50
  109. package/src/__tests__/utils/parse_simple_markdown.ts +0 -6
  110. package/src/__tests__/utils/session.ts +0 -11
  111. package/src/__tests__/utils/theme.ts +0 -17
  112. package/src/components/conversations/__tests__/bulk_conversation_actions_bar.test.tsx +95 -0
  113. package/src/components/conversations/__tests__/conversation_actions.test.tsx +35 -3
  114. package/src/components/conversations/__tests__/conversation_preview.test.tsx +69 -3
  115. package/src/components/conversations/__tests__/conversations.test.tsx +4 -1
  116. package/src/components/conversations/bulk_conversation_actions_bar.tsx +140 -0
  117. package/src/components/conversations/conversation_actions.tsx +17 -9
  118. package/src/components/conversations/conversation_preview.tsx +20 -2
  119. package/src/components/conversations/conversations.tsx +2 -1
  120. package/src/components/display/__tests__/filter_dropdown.test.tsx +1 -19
  121. package/src/components/display/__tests__/icon_tile.test.tsx +24 -7
  122. package/src/components/display/checkbox.tsx +47 -0
  123. package/src/components/display/icon.tsx +3 -0
  124. package/src/components/display/index.ts +1 -0
  125. package/src/components/page/__tests__/component_error_boundary.test.tsx +0 -12
  126. package/src/contexts/__tests__/conversations_context.test.tsx +86 -0
  127. package/src/contexts/api_provider.tsx +2 -0
  128. package/src/contexts/conversations_context.tsx +69 -2
  129. package/src/contexts/session_context.tsx +3 -1
  130. package/src/hooks/__tests__/jolt_refresh_throttling.test.tsx +194 -0
  131. package/src/hooks/__tests__/use_bulk_conversation_actions.test.tsx +119 -0
  132. package/src/hooks/__tests__/use_conversations_jolt_events.test.tsx +1 -0
  133. package/src/hooks/__tests__/use_conversations_mark_read.test.tsx +38 -12
  134. package/src/hooks/__tests__/use_hide_conversation.test.tsx +15 -3
  135. package/src/hooks/__tests__/use_mark_latest_message_read.test.tsx +23 -2
  136. package/src/hooks/use_bulk_conversation_actions.ts +173 -0
  137. package/src/hooks/use_conversation_jolt_events.ts +2 -1
  138. package/src/hooks/use_conversations_actions.ts +7 -4
  139. package/src/hooks/use_conversations_cache.ts +33 -26
  140. package/src/hooks/use_conversations_jolt_events.ts +24 -10
  141. package/src/hooks/use_mark_latest_message_read.ts +6 -5
  142. package/src/navigation/index.tsx +8 -8
  143. package/src/screens/__tests__/conversation_actions_screen.test.tsx +48 -6
  144. package/src/screens/__tests__/conversation_details_screen.test.tsx +0 -19
  145. package/src/screens/avatar_picker/__tests__/avatar_picker_state.test.ts +0 -14
  146. package/src/screens/conversation_actions_screen.tsx +145 -12
  147. package/src/screens/conversation_filter_recipients/components/checkbox_row.tsx +3 -35
  148. package/src/screens/conversations/__tests__/conversations_screen.test.tsx +35 -9
  149. package/src/screens/conversations/components/__tests__/filter_dropdown_list_header_component.test.tsx +0 -8
  150. package/src/screens/conversations/components/__tests__/search_list_header_component.test.tsx +0 -10
  151. package/src/screens/conversations/conversations_screen.tsx +67 -3
  152. package/src/screens/search/components/__tests__/search_results_list.test.tsx +1 -0
  153. package/src/types/jolt_events/index.ts +2 -0
  154. package/src/types/jolt_events/person_events.ts +16 -0
  155. package/src/utils/__tests__/attachment_kind.test.ts +0 -4
  156. package/src/utils/__tests__/convert_attachments_for_create.test.ts +0 -28
  157. package/src/utils/__tests__/is_input_editable.test.ts +1 -2
  158. package/src/utils/__tests__/message_text.test.ts +0 -5
  159. package/src/utils/__tests__/session_manager.test.ts +0 -83
  160. package/src/utils/__tests__/sha_256.test.ts +0 -34
  161. package/src/utils/__tests__/throttled_refresh.test.ts +101 -0
  162. package/src/utils/__tests__/uri.test.ts +51 -0
  163. package/src/utils/jolt/__tests__/parse_stream_user_event_type.test.ts +27 -0
  164. package/src/utils/jolt/parse_stream_user_event_type.ts +16 -0
  165. package/src/utils/native_adapters/configuration.ts +5 -0
  166. package/src/utils/native_adapters/index.ts +1 -0
  167. package/src/utils/native_adapters/updates.ts +16 -0
  168. package/src/utils/throttled_refresh.ts +62 -0
  169. package/src/__tests__/event-polyfill.test.ts +0 -313
  170. package/src/__tests__/index.tsx +0 -5
  171. package/src/__tests__/jest.ts +0 -11
  172. package/src/__tests__/utils/uri.ts +0 -65
  173. package/src/components/display/__tests__/version_footer.test.tsx +0 -48
  174. package/src/screens/search/components/__tests__/search_blank_states.test.tsx +0 -20
  175. package/src/utils/__tests__/membership_sync_info_text.test.ts +0 -15
@@ -0,0 +1,194 @@
1
+ import { QueryClient, QueryClientProvider, useQuery } from '@tanstack/react-query'
2
+ import { act, render } from '@testing-library/react-native'
3
+ import React, { Suspense } from 'react'
4
+ import { buildTestQueryClient } from '../../__utils__/query_client'
5
+ import type { ApiResource, ConversationResource, CurrentPersonResource } from '../../types'
6
+ import { getConversationsRequestArgs } from '../../utils/request/conversation'
7
+ import { cancelThrottledRefreshes, REFRESH_THROTTLE_MS } from '../../utils/throttled_refresh'
8
+ import { getConversationRequestArgs } from '../use_conversation'
9
+ import { useConversationJoltEvents } from '../use_conversation_jolt_events'
10
+ import { useConversationsJoltEvents } from '../use_conversations_jolt_events'
11
+ import { currentPersonQueryKey } from '../use_current_person'
12
+ import { getRequestQueryKey } from '../use_suspense_api'
13
+
14
+ type Handler = (event: unknown) => void
15
+ const mockHandlers = new Map<string, Set<Handler>>()
16
+
17
+ jest.mock('../use_jolt', () => {
18
+ const { useEffect } = jest.requireActual<typeof import('react')>('react')
19
+ return {
20
+ useJoltChannel: (channelName: string) => channelName,
21
+ useJoltEvent: (channel: string, eventName: string, handler: Handler) => {
22
+ useEffect(() => {
23
+ const key = `${channel}:${eventName}`
24
+ const bound = mockHandlers.get(key) ?? new Set<Handler>()
25
+ mockHandlers.set(key, bound)
26
+ bound.add(handler)
27
+ return () => {
28
+ bound.delete(handler)
29
+ }
30
+ }, [channel, eventName, handler])
31
+ },
32
+ }
33
+ })
34
+ jest.mock('../use_api', () => ({ useApiGet: () => ({ data: { id: 1 } }) }))
35
+ jest.mock('../../contexts/conversations_context', () => ({
36
+ useConversationsContext: () => ({ args: {} }),
37
+ }))
38
+
39
+ const mockGet = jest.fn()
40
+ jest.mock('../use_api_client', () => ({ useApiClient: () => ({ chat: { get: mockGet } }) }))
41
+
42
+ const personId = 1
43
+ const conversationId = 7
44
+ const peopleChannel = `chat.people.${personId}`
45
+ const conversationChannel = `chat.conversations.${conversationId}`
46
+ const listQueryKey = getRequestQueryKey(getConversationsRequestArgs({}))
47
+ const conversationQueryKey = getRequestQueryKey(
48
+ getConversationRequestArgs({ conversation_id: conversationId })
49
+ )
50
+ const listUrl = listQueryKey[0]
51
+ const conversationUrl = conversationQueryKey[0]
52
+ const meUrl = currentPersonQueryKey[0]
53
+
54
+ let queryClient: QueryClient
55
+
56
+ const ConversationsList = () => {
57
+ useConversationsJoltEvents()
58
+ return null
59
+ }
60
+
61
+ const ConversationScreen = () => {
62
+ useConversationJoltEvents({ conversationId })
63
+ useQuery({
64
+ queryKey: conversationQueryKey,
65
+ queryFn: () => mockGet({ url: conversationUrl }),
66
+ staleTime: Infinity,
67
+ })
68
+ return null
69
+ }
70
+
71
+ const fire = (channel: string, eventName: string, payload: Record<string, unknown>) => {
72
+ const message = { event: eventName, channel, ...payload }
73
+ mockHandlers.get(`${channel}:${eventName}`)?.forEach(handler => handler(message))
74
+ }
75
+
76
+ const conversationUpdated = () => {
77
+ const data = { data: { id: conversationId, last_message_author_id: 2 } }
78
+ fire(peopleChannel, 'conversation.updated', { data })
79
+ fire(conversationChannel, 'conversation.updated', { data })
80
+ }
81
+
82
+ const conversationRead = () => {
83
+ const data = { data: { id: conversationId, latest_read_message_sort_key: 'z' } }
84
+ fire(peopleChannel, 'conversation.read', { data })
85
+ fire(conversationChannel, 'conversation.read', { data })
86
+ }
87
+
88
+ const streamUserUpdated = (payload: Record<string, unknown>) =>
89
+ fire(peopleChannel, 'STREAM_USER_UPDATED', { data: { data: JSON.stringify(payload) } })
90
+
91
+ const requestsFor = (url: string) =>
92
+ mockGet.mock.calls.filter(([request]) => request.url === url).length
93
+
94
+ const advance = (ms: number) => act(async () => jest.advanceTimersByTime(ms))
95
+
96
+ const seed = () => {
97
+ queryClient.setQueryData<ApiResource<CurrentPersonResource>>(currentPersonQueryKey, {
98
+ data: { type: 'Person', id: personId },
99
+ } as ApiResource<CurrentPersonResource>)
100
+ queryClient.setQueryData<ApiResource<ConversationResource>>(conversationQueryKey, {
101
+ data: { type: 'Conversation', id: conversationId },
102
+ } as ApiResource<ConversationResource>)
103
+ queryClient.setQueryData(listQueryKey, {
104
+ pages: [{ data: [{ type: 'Conversation', id: conversationId }], links: {}, meta: {} }],
105
+ pageParams: [undefined],
106
+ })
107
+ }
108
+
109
+ const mountTwoListsAndTwoScreens = async () => {
110
+ seed()
111
+ render(
112
+ <QueryClientProvider client={queryClient}>
113
+ <Suspense fallback={null}>
114
+ <ConversationsList />
115
+ <ConversationsList />
116
+ <ConversationScreen />
117
+ <ConversationScreen />
118
+ </Suspense>
119
+ </QueryClientProvider>
120
+ )
121
+ await advance(1)
122
+ mockGet.mockClear()
123
+ }
124
+
125
+ beforeEach(async () => {
126
+ jest.useFakeTimers()
127
+ mockHandlers.clear()
128
+ mockGet.mockReset()
129
+ mockGet.mockImplementation(({ url }: { url: string }) => {
130
+ if (url === meUrl) return Promise.resolve({ data: { type: 'Person', id: personId } })
131
+ if (url === conversationUrl) {
132
+ return Promise.resolve({ data: { type: 'Conversation', id: conversationId } })
133
+ }
134
+ return Promise.resolve({ data: [{ type: 'Conversation', id: conversationId }] })
135
+ })
136
+ queryClient = buildTestQueryClient({ defaultOptions: { queries: { gcTime: Infinity } } })
137
+ await mountTwoListsAndTwoScreens()
138
+ })
139
+
140
+ afterEach(() => {
141
+ cancelThrottledRefreshes(queryClient)
142
+ jest.useRealTimers()
143
+ })
144
+
145
+ describe('conversation.updated across two lists and two screens', () => {
146
+ it('collapses 50 events into one request now and one when the window ends', async () => {
147
+ for (let i = 0; i < 50; i++) conversationUpdated()
148
+ await advance(1)
149
+
150
+ expect(requestsFor(listUrl)).toBe(1)
151
+ expect(requestsFor(conversationUrl)).toBe(1)
152
+
153
+ await advance(REFRESH_THROTTLE_MS)
154
+
155
+ expect(requestsFor(listUrl)).toBe(2)
156
+ expect(requestsFor(conversationUrl)).toBe(2)
157
+ })
158
+ })
159
+
160
+ describe('/me refreshes', () => {
161
+ it('makes no /me request for message.created stream events or conversation.read events', async () => {
162
+ for (let i = 0; i < 50; i++) {
163
+ streamUserUpdated({ event_type: 'message.created' })
164
+ conversationRead()
165
+ }
166
+ await advance(REFRESH_THROTTLE_MS * 2)
167
+
168
+ expect(requestsFor(meUrl)).toBe(0)
169
+ })
170
+
171
+ it('ignores the other read-state event types', async () => {
172
+ streamUserUpdated({ event_type: 'conversation.mark_read' })
173
+ streamUserUpdated({ event_type: 'conversation.mark_unread' })
174
+ streamUserUpdated({ event_type: 'person.mark_all_read' })
175
+ streamUserUpdated({ event_type: 'conversation.destroy' })
176
+ await advance(REFRESH_THROTTLE_MS * 2)
177
+
178
+ expect(requestsFor(meUrl)).toBe(0)
179
+ })
180
+
181
+ it('refetches /me once for app_grant.synced', async () => {
182
+ streamUserUpdated({ event_type: 'app_grant.synced' })
183
+ await advance(REFRESH_THROTTLE_MS * 2)
184
+
185
+ expect(requestsFor(meUrl)).toBe(1)
186
+ })
187
+
188
+ it('refetches /me once for an event with no event_type', async () => {
189
+ streamUserUpdated({})
190
+ await advance(REFRESH_THROTTLE_MS * 2)
191
+
192
+ expect(requestsFor(meUrl)).toBe(1)
193
+ })
194
+ })
@@ -0,0 +1,119 @@
1
+ import { QueryClientProvider } from '@tanstack/react-query'
2
+ import { act, renderHook } from '@testing-library/react-native'
3
+ import React from 'react'
4
+ import { Alert } from 'react-native'
5
+ import { buildTestQueryClient } from '../../__utils__/query_client'
6
+ import type { ConversationResource } from '../../types'
7
+ import { getConversationsRequestArgs } from '../../utils/request/conversation'
8
+ import { dismissToast, toastStore } from '../../utils/toast_store'
9
+ import { useBulkConversationActions } from '../use_bulk_conversation_actions'
10
+ import { currentPersonQueryKey } from '../use_current_person'
11
+ import { getRequestQueryKey } from '../use_suspense_api'
12
+
13
+ const mockPatch = jest.fn()
14
+ const mockPost = jest.fn()
15
+ jest.mock('../use_api_client', () => ({
16
+ useApiClient: () => ({ chat: { patch: mockPatch, post: mockPost } }),
17
+ }))
18
+
19
+ const conversations = [
20
+ { id: 7, muted: false, unreadCount: 2, unreadReaction: false },
21
+ { id: 8, muted: false, unreadCount: 3, unreadReaction: true },
22
+ { id: 9, muted: false, unreadCount: 0, unreadReaction: false },
23
+ ] as ConversationResource[]
24
+ const allKey = getRequestQueryKey(getConversationsRequestArgs({ gids: 'all' }))
25
+ const hiddenKey = getRequestQueryKey(getConversationsRequestArgs({ show_hidden: true }))
26
+
27
+ const listData = (records: ConversationResource[]) => ({
28
+ pages: [{ data: records, links: {}, meta: { count: records.length } }],
29
+ pageParams: [{}],
30
+ })
31
+
32
+ const listRecords = () =>
33
+ (queryClient.getQueryData(allKey) as ReturnType<typeof listData>).pages[0].data
34
+
35
+ const listIds = () => listRecords().map(({ id }) => id)
36
+
37
+ let queryClient = buildTestQueryClient()
38
+
39
+ const wrapper = ({ children }: { children: React.ReactNode }) => (
40
+ <QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
41
+ )
42
+
43
+ const renderBulk = () => renderHook(() => useBulkConversationActions(), { wrapper })
44
+
45
+ describe('useBulkConversationActions', () => {
46
+ beforeEach(() => {
47
+ queryClient = buildTestQueryClient({ defaultOptions: { queries: { gcTime: Infinity } } })
48
+ queryClient.setQueryData(allKey, listData(conversations))
49
+ queryClient.setQueryData(currentPersonQueryKey, { data: { unreadCount: 10 } })
50
+ mockPatch.mockReset().mockResolvedValue({ data: {} })
51
+ mockPost.mockReset().mockResolvedValue({ data: {} })
52
+ dismissToast()
53
+ jest.spyOn(Alert, 'alert').mockImplementation(() => {})
54
+ })
55
+
56
+ afterEach(() => {
57
+ jest.restoreAllMocks()
58
+ })
59
+
60
+ it.each([
61
+ ['hide', mockPatch, '/me/conversations/7/conversation_membership', { hidden: true }],
62
+ ['unhide', mockPatch, '/me/conversations/7/conversation_membership', { hidden: false }],
63
+ ['silence', mockPatch, '/me/conversations/7/conversation_membership', { muted: true }],
64
+ ['markRead', mockPost, '/me/conversations/7/mark_read', {}],
65
+ ] as const)(
66
+ '%s sends one request per conversation',
67
+ async (action, request, firstUrl, attributes) => {
68
+ const { result } = renderBulk()
69
+
70
+ await act(() => result.current[action](conversations))
71
+
72
+ expect(request.mock.calls.map(([{ url, data }]) => [url, data.data.attributes])).toEqual([
73
+ [firstUrl, attributes],
74
+ [firstUrl.replace('/7/', '/8/'), attributes],
75
+ [firstUrl.replace('/7/', '/9/'), attributes],
76
+ ])
77
+ }
78
+ )
79
+
80
+ it('rolls back only the failed rows and alerts once', async () => {
81
+ mockPost.mockImplementation(({ url }) =>
82
+ url.includes('/8/') ? Promise.reject(new Error('nope')) : Promise.resolve({ data: {} })
83
+ )
84
+ const { result } = renderBulk()
85
+
86
+ await act(() => result.current.markRead(conversations))
87
+
88
+ expect(listRecords().map(({ unreadCount }) => unreadCount)).toEqual([0, 3, 0])
89
+ expect(queryClient.getQueryData(currentPersonQueryKey)).toEqual({ data: { unreadCount: 8 } })
90
+ expect(Alert.alert).toHaveBeenCalledTimes(1)
91
+ expect(Alert.alert).toHaveBeenCalledWith(
92
+ 'Oops',
93
+ "Couldn't mark read 1 conversation. Please try again."
94
+ )
95
+ })
96
+
97
+ it('restores every hidden row on undo and unhides the ones that succeeded', async () => {
98
+ mockPatch.mockImplementation(({ url }) =>
99
+ url.includes('/9/') ? Promise.reject(new Error('nope')) : Promise.resolve({ data: {} })
100
+ )
101
+ queryClient.setQueryData(hiddenKey, listData([]))
102
+ const { result } = renderBulk()
103
+
104
+ await act(() => result.current.hide(conversations))
105
+
106
+ expect(listIds()).toEqual([9])
107
+ expect(queryClient.getQueryState(hiddenKey)?.isInvalidated).toBe(true)
108
+ expect(toastStore.getSnapshot()).toMatchObject({ title: '2 conversations hidden' })
109
+
110
+ mockPatch.mockClear()
111
+ await act(async () => toastStore.getSnapshot()?.action?.onPress())
112
+
113
+ expect(listIds()).toEqual([7, 8, 9])
114
+ expect(mockPatch.mock.calls.map(([{ url, data }]) => [url, data.data.attributes])).toEqual([
115
+ ['/me/conversations/7/conversation_membership', { hidden: false }],
116
+ ['/me/conversations/8/conversation_membership', { hidden: false }],
117
+ ])
118
+ })
119
+ })
@@ -18,6 +18,7 @@ jest.mock('../use_jolt', () => ({
18
18
  jest.mock('../use_api', () => ({ useApiGet: () => ({ data: { id: 1 } }) }))
19
19
  jest.mock('../use_current_person', () => ({
20
20
  currentPersonRequestArgs: {},
21
+ currentPersonQueryKey: ['/me'],
21
22
  useCurrentPersonCache: () => ({ invalidate: jest.fn() }),
22
23
  }))
23
24
 
@@ -1,4 +1,4 @@
1
- import { QueryClientProvider } from '@tanstack/react-query'
1
+ import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
2
2
  import { act, renderHook } from '@testing-library/react-native'
3
3
  import React from 'react'
4
4
  import { buildTestQueryClient } from '../../__utils__/query_client'
@@ -7,27 +7,53 @@ import { getConversationsRequestArgs } from '../../utils/request/conversation'
7
7
  import { useConversationsMarkRead } from '../use_conversations_actions'
8
8
  import { getRequestQueryKey } from '../use_suspense_api'
9
9
 
10
+ const mockPost = jest.fn()
11
+ const mockGet = jest.fn()
10
12
  jest.mock('../use_api_client', () => ({
11
- useApiClient: () => ({
12
- chat: { post: jest.fn().mockResolvedValue({}), get: jest.fn().mockResolvedValue({ data: [] }) },
13
- }),
13
+ useApiClient: () => ({ chat: { post: mockPost, get: mockGet } }),
14
14
  }))
15
15
 
16
+ const conversation = { id: 7, unreadCount: 8 } as ConversationResource
17
+ const listKey = getRequestQueryKey(getConversationsRequestArgs())
18
+ const archivedListKey = getRequestQueryKey(getConversationsRequestArgs({ show_archived: true }))
19
+ let queryClient: QueryClient
20
+
21
+ const wrapper = ({ children }: { children: React.ReactNode }) => (
22
+ <QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
23
+ )
24
+
25
+ const listShows = (key: typeof listKey) => queryClient.getQueryData(key)
26
+
27
+ beforeEach(() => {
28
+ mockPost.mockReset()
29
+ mockGet.mockReset()
30
+ queryClient = buildTestQueryClient({ defaultOptions: { queries: { gcTime: Infinity } } })
31
+ queryClient.setQueryData(listKey, { pages: [{ data: [conversation] }], pageParams: [] })
32
+ queryClient.setQueryData(archivedListKey, { pages: [{ data: [conversation] }], pageParams: [] })
33
+ })
34
+
16
35
  describe('useConversationsMarkRead', () => {
17
36
  it('marks the conversation read in a list outside the current conversations context', async () => {
18
- const conversation = { id: 7, unreadCount: 8 } as ConversationResource
19
- const archivedListKey = getRequestQueryKey(getConversationsRequestArgs({ show_archived: true }))
20
- const queryClient = buildTestQueryClient({ defaultOptions: { queries: { gcTime: Infinity } } })
21
- queryClient.setQueryData(archivedListKey, { pages: [{ data: [conversation] }], pageParams: [] })
22
- const wrapper = ({ children }: { children: React.ReactNode }) => (
23
- <QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
24
- )
37
+ mockPost.mockResolvedValue({ data: { type: 'Conversation', id: 7, unreadCount: 0 } })
25
38
  const { result } = renderHook(() => useConversationsMarkRead({ conversation }), { wrapper })
26
39
 
27
40
  await act(async () => result.current.markRead(true))
28
41
 
29
- expect(queryClient.getQueryData(archivedListKey)).toMatchObject({
42
+ expect(listShows(archivedListKey)).toMatchObject({
30
43
  pages: [{ data: [{ id: 7, unreadCount: 0 }] }],
31
44
  })
32
45
  })
46
+
47
+ it('shows the unread count from the response without refetching the conversation', async () => {
48
+ mockPost.mockResolvedValue({ data: { type: 'Conversation', id: 7, unreadCount: 3 } })
49
+ const { result } = renderHook(() => useConversationsMarkRead({ conversation }), { wrapper })
50
+
51
+ await act(async () => result.current.markRead(false))
52
+
53
+ expect(mockGet).not.toHaveBeenCalled()
54
+ expect(listShows(listKey)).toMatchObject({ pages: [{ data: [{ id: 7, unreadCount: 3 }] }] })
55
+ expect(listShows(archivedListKey)).toMatchObject({
56
+ pages: [{ data: [{ id: 7, unreadCount: 3 }] }],
57
+ })
58
+ })
33
59
  })
@@ -47,6 +47,16 @@ const wrapper = ({ children }: { children: React.ReactNode }) => (
47
47
  <QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
48
48
  )
49
49
 
50
+ // A mutation left pending keeps Jest alive: with no observers, TanStack Query
51
+ // re-arms its gc timer until the mutation settles.
52
+ let settlePatch: (() => void) | undefined
53
+ const mockPendingPatch = () =>
54
+ mockPatch.mockReturnValue(
55
+ new Promise(resolve => {
56
+ settlePatch = () => resolve({ data: {} })
57
+ })
58
+ )
59
+
50
60
  const renderHide = (target: ConversationResource = conversation, hidden?: boolean) =>
51
61
  renderHook(() => useHideConversation({ conversation: target, hidden }), { wrapper })
52
62
 
@@ -63,12 +73,14 @@ describe('useHideConversation', () => {
63
73
  jest.spyOn(Alert, 'alert').mockImplementation(() => {})
64
74
  })
65
75
 
66
- afterEach(() => {
76
+ afterEach(async () => {
77
+ await act(async () => settlePatch?.())
78
+ settlePatch = undefined
67
79
  jest.restoreAllMocks()
68
80
  })
69
81
 
70
82
  it('removes the conversation from every list before the request resolves', async () => {
71
- mockPatch.mockReturnValue(new Promise(() => {}))
83
+ mockPendingPatch()
72
84
  const { result } = renderHide()
73
85
 
74
86
  await act(async () => result.current.setHidden(true))
@@ -152,7 +164,7 @@ describe('useHideConversation', () => {
152
164
  })
153
165
 
154
166
  it('removes the conversation from the hidden list before the request resolves', async () => {
155
- mockPatch.mockReturnValue(new Promise(() => {}))
167
+ mockPendingPatch()
156
168
  const { result } = renderHide(conversation, true)
157
169
 
158
170
  expect(result.current.hidden).toBe(true)
@@ -34,12 +34,33 @@ describe('useMarkLatestMessageRead', () => {
34
34
  expect(mockMarkRead).toHaveBeenCalledTimes(1)
35
35
 
36
36
  rerender({ conversation: { ...conversation, unreadCount: 2 }, enabled: false })
37
- act(() => jest.advanceTimersByTime(1000))
37
+ act(() => jest.advanceTimersByTime(3000))
38
38
 
39
39
  expect(mockMarkRead).toHaveBeenCalledTimes(1)
40
40
 
41
41
  rerender({ conversation: { ...conversation, unreadCount: 2 }, enabled: true })
42
- act(() => jest.advanceTimersByTime(1000))
42
+ act(() => jest.advanceTimersByTime(3000))
43
+
44
+ expect(mockMarkRead).toHaveBeenCalledTimes(2)
45
+ jest.useRealTimers()
46
+ })
47
+
48
+ it('collapses unread bumps inside three seconds into one trailing mark-read', () => {
49
+ jest.useFakeTimers()
50
+ const { rerender } = renderHook<void, { conversation: ConversationResource }>(
51
+ props => useMarkLatestMessageRead({ ...props, messages: [] }),
52
+ { initialProps: { conversation } }
53
+ )
54
+ expect(mockMarkRead).toHaveBeenCalledTimes(1)
55
+
56
+ for (let i = 0; i < 3; i++) {
57
+ rerender({ conversation: { ...conversation, unreadCount: 0 } })
58
+ act(() => jest.advanceTimersByTime(500))
59
+ rerender({ conversation: { ...conversation, unreadCount: 1 } })
60
+ }
61
+ expect(mockMarkRead).toHaveBeenCalledTimes(1)
62
+
63
+ act(() => jest.advanceTimersByTime(3000))
43
64
 
44
65
  expect(mockMarkRead).toHaveBeenCalledTimes(2)
45
66
  jest.useRealTimers()
@@ -0,0 +1,173 @@
1
+ import { useQueryClient } from '@tanstack/react-query'
2
+ import { Alert } from 'react-native'
3
+ import { useConversationsContext } from '../contexts/conversations_context'
4
+ import { ApiResource, ConversationResource } from '../types'
5
+ import { pluralize } from '../utils/pluralize'
6
+ import { HIDDEN_CONVERSATIONS_FILTER } from '../utils/request/conversation'
7
+ import { showToast } from '../utils/toast_store'
8
+ import { useApiClient } from './use_api_client'
9
+ import { getConversationRequestArgs } from './use_conversation'
10
+ import { useConversationsCache } from './use_conversations_cache'
11
+ import { useCurrentPersonCache } from './use_current_person'
12
+ import { getRequestQueryKey } from './use_suspense_api'
13
+
14
+ const settle = async (
15
+ conversations: ConversationResource[],
16
+ request: (conversation: ConversationResource) => Promise<unknown>
17
+ ) => {
18
+ const results = await Promise.allSettled(conversations.map(request))
19
+ const succeeded = conversations.filter((_, i) => results[i].status === 'fulfilled')
20
+ const failed = conversations.filter((_, i) => results[i].status === 'rejected')
21
+
22
+ return { succeeded, failed }
23
+ }
24
+
25
+ const alertFailures = (verb: string, failed: ConversationResource[]) => {
26
+ if (failed.length === 0) return
27
+
28
+ Alert.alert(
29
+ 'Oops',
30
+ `Couldn't ${verb} ${pluralize(failed.length, 'conversation')}. Please try again.`
31
+ )
32
+ }
33
+
34
+ const sumUnread = (conversations: ConversationResource[]) =>
35
+ conversations.reduce((sum, { unreadCount }) => sum + (unreadCount || 0), 0)
36
+
37
+ export const useBulkConversationActions = () => {
38
+ const apiClient = useApiClient()
39
+ const queryClient = useQueryClient()
40
+ const { args } = useConversationsContext()
41
+ const currentPersonCache = useCurrentPersonCache()
42
+ const {
43
+ cancelAllLists,
44
+ invalidateAllLists,
45
+ removeFromAllLists,
46
+ restoreLists,
47
+ snapshotAllLists,
48
+ updateInAllLists,
49
+ } = useConversationsCache(args)
50
+
51
+ const setMembershipHidden = (conversations: ConversationResource[], hidden: boolean) =>
52
+ conversations.forEach(({ id }) =>
53
+ queryClient.setQueryData<ApiResource<ConversationResource>>(
54
+ getRequestQueryKey(getConversationRequestArgs({ conversation_id: id })),
55
+ prev => {
56
+ if (!prev?.data) return prev
57
+
58
+ return {
59
+ ...prev,
60
+ data: {
61
+ ...prev.data,
62
+ conversationMembership: { ...prev.data.conversationMembership, hidden },
63
+ },
64
+ }
65
+ }
66
+ )
67
+ )
68
+
69
+ const patchMembership =
70
+ (attributes: { hidden?: boolean; muted?: boolean }) =>
71
+ ({ id }: ConversationResource) =>
72
+ apiClient.chat.patch({
73
+ url: `/me/conversations/${id}/conversation_membership`,
74
+ data: {
75
+ data: { type: 'ConversationMembership', attributes },
76
+ fields: { ConversationMembership: Object.keys(attributes).join(',') },
77
+ },
78
+ })
79
+
80
+ const applyHidden = async (conversations: ConversationResource[], hidden: boolean) => {
81
+ const filter = hidden ? undefined : HIDDEN_CONVERSATIONS_FILTER
82
+ await cancelAllLists()
83
+ const previousLists = snapshotAllLists()
84
+
85
+ removeFromAllLists(
86
+ conversations.map(({ id }) => id),
87
+ { filter }
88
+ )
89
+ setMembershipHidden(conversations, hidden)
90
+
91
+ const result = await settle(conversations, patchMembership({ hidden }))
92
+
93
+ if (result.failed.length > 0) {
94
+ restoreLists(previousLists)
95
+ removeFromAllLists(
96
+ result.succeeded.map(({ id }) => id),
97
+ { filter }
98
+ )
99
+ setMembershipHidden(result.failed, !hidden)
100
+ }
101
+
102
+ return { ...result, previousLists }
103
+ }
104
+
105
+ const unhide = async (conversations: ConversationResource[]) => {
106
+ const { failed } = await applyHidden(conversations, false)
107
+
108
+ invalidateAllLists()
109
+ alertFailures('unhide', failed)
110
+ }
111
+
112
+ const hide = async (conversations: ConversationResource[]) => {
113
+ const { succeeded, failed, previousLists } = await applyHidden(conversations, true)
114
+
115
+ alertFailures('hide', failed)
116
+ if (succeeded.length === 0) return
117
+
118
+ invalidateAllLists({ filter: HIDDEN_CONVERSATIONS_FILTER })
119
+ showToast({
120
+ title: `${pluralize(succeeded.length, 'conversation')} hidden`,
121
+ action: {
122
+ label: 'Undo',
123
+ onPress: () => {
124
+ restoreLists(previousLists)
125
+ unhide(succeeded)
126
+ },
127
+ },
128
+ })
129
+ }
130
+
131
+ const silence = async (conversations: ConversationResource[]) => {
132
+ const setMuted = (conversation: ConversationResource, muted: boolean) =>
133
+ updateInAllLists(conversation.id, {
134
+ muted,
135
+ conversationMembership: { ...conversation.conversationMembership, muted },
136
+ })
137
+
138
+ conversations.forEach(conversation => setMuted(conversation, true))
139
+
140
+ const { failed } = await settle(conversations, patchMembership({ muted: true }))
141
+
142
+ failed.forEach(conversation => setMuted(conversation, conversation.muted))
143
+ alertFailures('silence', failed)
144
+ }
145
+
146
+ const adjustPersonUnread = (delta: number) =>
147
+ currentPersonCache.update({}, person => ({
148
+ ...person,
149
+ unreadCount: Math.max(person.unreadCount + delta, 0),
150
+ }))
151
+
152
+ const markRead = async (conversations: ConversationResource[]) => {
153
+ conversations.forEach(({ id }) =>
154
+ updateInAllLists(id, { unreadCount: 0, unreadReaction: false })
155
+ )
156
+ adjustPersonUnread(-sumUnread(conversations))
157
+
158
+ const { failed } = await settle(conversations, ({ id }) =>
159
+ apiClient.chat.post({
160
+ url: `/me/conversations/${id}/mark_read`,
161
+ data: { data: { type: '', attributes: {} }, fields: { Conversation: 'unread_count,id' } },
162
+ })
163
+ )
164
+
165
+ failed.forEach(({ id, unreadCount, unreadReaction }) =>
166
+ updateInAllLists(id, { unreadCount, unreadReaction })
167
+ )
168
+ adjustPersonUnread(sumUnread(failed))
169
+ alertFailures('mark read', failed)
170
+ }
171
+
172
+ return { hide, unhide, silence, markRead }
173
+ }
@@ -3,6 +3,7 @@ import { useCallback, useMemo } from 'react'
3
3
  import { ApiResource, ConversationResource } from '../types'
4
4
  import { JoltConversationEvent, JoltReactionEvent } from '../types/jolt_events'
5
5
  import { completeMessageCreationConversationTracking } from '../utils/performance_tracking'
6
+ import { throttledRefresh } from '../utils/throttled_refresh'
6
7
  import { useApiClient } from './use_api_client'
7
8
  import { getConversationRequestArgs } from './use_conversation'
8
9
  import { useCurrentPerson } from './use_current_person'
@@ -54,7 +55,7 @@ export function useConversationJoltEvents({ conversationId }: Props) {
54
55
  }
55
56
  })
56
57
 
57
- queryClient.invalidateQueries({ queryKey })
58
+ throttledRefresh(queryClient, queryKey, e, () => queryClient.invalidateQueries({ queryKey }))
58
59
  },
59
60
  [queryClient, queryKey, currentPersonId, apiClient]
60
61
  )