@planningcenter/chat-react-native 4.8.0-rc.0 → 4.8.0-rc.10

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 (250) 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/chat_context.d.ts +0 -2
  31. package/build/contexts/chat_context.d.ts.map +1 -1
  32. package/build/contexts/chat_context.js +16 -93
  33. package/build/contexts/chat_context.js.map +1 -1
  34. package/build/contexts/conversations_context.d.ts +5 -0
  35. package/build/contexts/conversations_context.d.ts.map +1 -1
  36. package/build/contexts/conversations_context.js +121 -32
  37. package/build/contexts/conversations_context.js.map +1 -1
  38. package/build/contexts/session_context.d.ts +0 -1
  39. package/build/contexts/session_context.d.ts.map +1 -1
  40. package/build/contexts/session_context.js +3 -0
  41. package/build/contexts/session_context.js.map +1 -1
  42. package/build/hooks/groups/use_group_chat_conversation_payload.d.ts +11 -1
  43. package/build/hooks/groups/use_group_chat_conversation_payload.d.ts.map +1 -1
  44. package/build/hooks/groups/use_group_chat_conversation_payload.js +92 -47
  45. package/build/hooks/groups/use_group_chat_conversation_payload.js.map +1 -1
  46. package/build/hooks/groups/use_group_members_for_new_conversation.d.ts +27 -25
  47. package/build/hooks/groups/use_group_members_for_new_conversation.d.ts.map +1 -1
  48. package/build/hooks/groups/use_group_members_for_new_conversation.js +125 -110
  49. package/build/hooks/groups/use_group_members_for_new_conversation.js.map +1 -1
  50. package/build/hooks/groups/use_groups_conversation_create.d.ts.map +1 -1
  51. package/build/hooks/groups/use_groups_conversation_create.js +39 -31
  52. package/build/hooks/groups/use_groups_conversation_create.js.map +1 -1
  53. package/build/hooks/groups/use_groups_proxy.d.ts +2 -0
  54. package/build/hooks/groups/use_groups_proxy.d.ts.map +1 -0
  55. package/build/hooks/groups/use_groups_proxy.js +18 -0
  56. package/build/hooks/groups/use_groups_proxy.js.map +1 -0
  57. package/build/hooks/use_bulk_conversation_actions.d.ts +8 -0
  58. package/build/hooks/use_bulk_conversation_actions.d.ts.map +1 -0
  59. package/build/hooks/use_bulk_conversation_actions.js +309 -0
  60. package/build/hooks/use_bulk_conversation_actions.js.map +1 -0
  61. package/build/hooks/use_conversation_jolt_events.d.ts.map +1 -1
  62. package/build/hooks/use_conversation_jolt_events.js +3 -2
  63. package/build/hooks/use_conversation_jolt_events.js.map +1 -1
  64. package/build/hooks/use_conversations_actions.d.ts +9 -9
  65. package/build/hooks/use_conversations_actions.d.ts.map +1 -1
  66. package/build/hooks/use_conversations_actions.js +12 -7
  67. package/build/hooks/use_conversations_actions.js.map +1 -1
  68. package/build/hooks/use_conversations_cache.d.ts +15 -5
  69. package/build/hooks/use_conversations_cache.d.ts.map +1 -1
  70. package/build/hooks/use_conversations_cache.js +170 -122
  71. package/build/hooks/use_conversations_cache.js.map +1 -1
  72. package/build/hooks/use_conversations_jolt_events.d.ts.map +1 -1
  73. package/build/hooks/use_conversations_jolt_events.js +47 -20
  74. package/build/hooks/use_conversations_jolt_events.js.map +1 -1
  75. package/build/hooks/use_features.d.ts +1 -0
  76. package/build/hooks/use_features.d.ts.map +1 -1
  77. package/build/hooks/use_features.js +1 -0
  78. package/build/hooks/use_features.js.map +1 -1
  79. package/build/hooks/use_groups_groups.d.ts.map +1 -1
  80. package/build/hooks/use_groups_groups.js +25 -9
  81. package/build/hooks/use_groups_groups.js.map +1 -1
  82. package/build/hooks/use_mark_latest_message_read.d.ts.map +1 -1
  83. package/build/hooks/use_mark_latest_message_read.js +5 -4
  84. package/build/hooks/use_mark_latest_message_read.js.map +1 -1
  85. package/build/hooks/use_new_conversation_from_filter.d.ts.map +1 -1
  86. package/build/hooks/use_new_conversation_from_filter.js +11 -1
  87. package/build/hooks/use_new_conversation_from_filter.js.map +1 -1
  88. package/build/hooks/use_product_analytics.d.ts.map +1 -1
  89. package/build/hooks/use_product_analytics.js +93 -75
  90. package/build/hooks/use_product_analytics.js.map +1 -1
  91. package/build/navigation/index.d.ts.map +1 -1
  92. package/build/navigation/index.js +5 -7
  93. package/build/navigation/index.js.map +1 -1
  94. package/build/screens/conversation_actions_screen.d.ts +2 -0
  95. package/build/screens/conversation_actions_screen.d.ts.map +1 -1
  96. package/build/screens/conversation_actions_screen.js +380 -46
  97. package/build/screens/conversation_actions_screen.js.map +1 -1
  98. package/build/screens/conversation_filter_recipients/components/checkbox_row.d.ts.map +1 -1
  99. package/build/screens/conversation_filter_recipients/components/checkbox_row.js +9 -64
  100. package/build/screens/conversation_filter_recipients/components/checkbox_row.js.map +1 -1
  101. package/build/screens/conversation_new/components/groups_form.d.ts.map +1 -1
  102. package/build/screens/conversation_new/components/groups_form.js +96 -93
  103. package/build/screens/conversation_new/components/groups_form.js.map +1 -1
  104. package/build/screens/conversations/conversations_screen.d.ts +5 -0
  105. package/build/screens/conversations/conversations_screen.d.ts.map +1 -1
  106. package/build/screens/conversations/conversations_screen.js +156 -31
  107. package/build/screens/conversations/conversations_screen.js.map +1 -1
  108. package/build/screens/get_help_screen.d.ts.map +1 -1
  109. package/build/screens/get_help_screen.js +4 -20
  110. package/build/screens/get_help_screen.js.map +1 -1
  111. package/build/types/jolt_events/index.d.ts +2 -0
  112. package/build/types/jolt_events/index.d.ts.map +1 -1
  113. package/build/types/jolt_events/index.js.map +1 -1
  114. package/build/types/jolt_events/person_events.d.ts +9 -0
  115. package/build/types/jolt_events/person_events.d.ts.map +1 -0
  116. package/build/types/jolt_events/person_events.js +2 -0
  117. package/build/types/jolt_events/person_events.js.map +1 -0
  118. package/build/types/resources/groups/groups_group_resource.d.ts +1 -1
  119. package/build/types/resources/groups/groups_group_resource.d.ts.map +1 -1
  120. package/build/types/resources/groups/groups_group_resource.js.map +1 -1
  121. package/build/types/resources/groups/groups_membership_resource.d.ts +11 -0
  122. package/build/types/resources/groups/groups_membership_resource.d.ts.map +1 -0
  123. package/build/types/resources/groups/groups_membership_resource.js +2 -0
  124. package/build/types/resources/groups/groups_membership_resource.js.map +1 -0
  125. package/build/types/resources/groups/index.d.ts +1 -0
  126. package/build/types/resources/groups/index.d.ts.map +1 -1
  127. package/build/types/resources/groups/index.js +1 -0
  128. package/build/types/resources/groups/index.js.map +1 -1
  129. package/build/utils/jolt/parse_stream_user_event_type.d.ts +3 -0
  130. package/build/utils/jolt/parse_stream_user_event_type.d.ts.map +1 -0
  131. package/build/utils/jolt/parse_stream_user_event_type.js +9 -0
  132. package/build/utils/jolt/parse_stream_user_event_type.js.map +1 -0
  133. package/build/utils/native_adapters/configuration.d.ts +3 -0
  134. package/build/utils/native_adapters/configuration.d.ts.map +1 -1
  135. package/build/utils/native_adapters/configuration.js +3 -0
  136. package/build/utils/native_adapters/configuration.js.map +1 -1
  137. package/build/utils/native_adapters/index.d.ts +1 -0
  138. package/build/utils/native_adapters/index.d.ts.map +1 -1
  139. package/build/utils/native_adapters/index.js +1 -0
  140. package/build/utils/native_adapters/index.js.map +1 -1
  141. package/build/utils/native_adapters/linking.d.ts.map +1 -1
  142. package/build/utils/native_adapters/linking.js +48 -2
  143. package/build/utils/native_adapters/linking.js.map +1 -1
  144. package/build/utils/native_adapters/updates.d.ts +11 -0
  145. package/build/utils/native_adapters/updates.d.ts.map +1 -0
  146. package/build/utils/native_adapters/updates.js +8 -0
  147. package/build/utils/native_adapters/updates.js.map +1 -0
  148. package/build/utils/product_analytics_token.d.ts +12 -0
  149. package/build/utils/product_analytics_token.d.ts.map +1 -0
  150. package/build/utils/product_analytics_token.js +84 -0
  151. package/build/utils/product_analytics_token.js.map +1 -0
  152. package/build/utils/throttled_refresh.d.ts +7 -0
  153. package/build/utils/throttled_refresh.d.ts.map +1 -0
  154. package/build/utils/throttled_refresh.js +42 -0
  155. package/build/utils/throttled_refresh.js.map +1 -0
  156. package/package.json +2 -2
  157. package/src/__tests__/contexts/session_context.tsx +19 -39
  158. package/src/__tests__/hooks/useTheme.tsx +0 -7
  159. package/src/__tests__/hooks/use_async_storage.test.tsx +1 -87
  160. package/src/__tests__/hooks/use_attachment_uploader.test.tsx +0 -11
  161. package/src/__tests__/hooks/use_font_scale.test.ts +0 -25
  162. package/src/__tests__/hooks/use_group_chat_conversation_payload.test.tsx +31 -0
  163. package/src/__tests__/utils/cache/page_mutations.ts +3 -68
  164. package/src/__tests__/utils/client.ts +6 -15
  165. package/src/__tests__/utils/native_adapters/configuration.ts +15 -50
  166. package/src/__tests__/utils/parse_simple_markdown.ts +0 -6
  167. package/src/__tests__/utils/session.ts +0 -11
  168. package/src/__tests__/utils/theme.ts +0 -17
  169. package/src/components/conversations/__tests__/bulk_conversation_actions_bar.test.tsx +95 -0
  170. package/src/components/conversations/__tests__/conversation_actions.test.tsx +35 -3
  171. package/src/components/conversations/__tests__/conversation_preview.test.tsx +69 -3
  172. package/src/components/conversations/__tests__/conversations.test.tsx +4 -1
  173. package/src/components/conversations/bulk_conversation_actions_bar.tsx +140 -0
  174. package/src/components/conversations/conversation_actions.tsx +17 -9
  175. package/src/components/conversations/conversation_preview.tsx +20 -2
  176. package/src/components/conversations/conversations.tsx +2 -1
  177. package/src/components/display/__tests__/filter_dropdown.test.tsx +1 -19
  178. package/src/components/display/__tests__/icon_tile.test.tsx +24 -7
  179. package/src/components/display/checkbox.tsx +47 -0
  180. package/src/components/display/icon.tsx +3 -0
  181. package/src/components/display/index.ts +1 -0
  182. package/src/components/page/__tests__/component_error_boundary.test.tsx +0 -12
  183. package/src/contexts/__tests__/conversations_context.test.tsx +86 -0
  184. package/src/contexts/api_provider.tsx +2 -0
  185. package/src/contexts/chat_context.tsx +2 -58
  186. package/src/contexts/conversations_context.tsx +69 -2
  187. package/src/contexts/session_context.tsx +3 -1
  188. package/src/hooks/__tests__/jolt_refresh_throttling.test.tsx +194 -0
  189. package/src/hooks/__tests__/use_bulk_conversation_actions.test.tsx +119 -0
  190. package/src/hooks/__tests__/use_conversations_jolt_events.test.tsx +1 -0
  191. package/src/hooks/__tests__/use_conversations_mark_read.test.tsx +38 -12
  192. package/src/hooks/__tests__/use_hide_conversation.test.tsx +15 -3
  193. package/src/hooks/__tests__/use_mark_latest_message_read.test.tsx +23 -2
  194. package/src/hooks/__tests__/use_product_analytics.test.tsx +304 -0
  195. package/src/hooks/groups/use_group_chat_conversation_payload.ts +30 -12
  196. package/src/hooks/groups/use_group_members_for_new_conversation.ts +49 -18
  197. package/src/hooks/groups/use_groups_conversation_create.ts +10 -14
  198. package/src/hooks/groups/use_groups_proxy.ts +6 -0
  199. package/src/hooks/use_bulk_conversation_actions.ts +173 -0
  200. package/src/hooks/use_conversation_jolt_events.ts +2 -1
  201. package/src/hooks/use_conversations_actions.ts +7 -4
  202. package/src/hooks/use_conversations_cache.ts +33 -26
  203. package/src/hooks/use_conversations_jolt_events.ts +24 -10
  204. package/src/hooks/use_features.ts +1 -0
  205. package/src/hooks/use_groups_groups.ts +21 -16
  206. package/src/hooks/use_mark_latest_message_read.ts +6 -5
  207. package/src/hooks/use_new_conversation_from_filter.ts +13 -5
  208. package/src/hooks/use_product_analytics.ts +74 -41
  209. package/src/navigation/index.tsx +8 -8
  210. package/src/screens/__tests__/conversation_actions_screen.test.tsx +48 -6
  211. package/src/screens/__tests__/conversation_details_screen.test.tsx +0 -19
  212. package/src/screens/avatar_picker/__tests__/avatar_picker_state.test.ts +0 -14
  213. package/src/screens/conversation_actions_screen.tsx +145 -12
  214. package/src/screens/conversation_filter_recipients/components/checkbox_row.tsx +3 -35
  215. package/src/screens/conversation_new/components/groups_form.tsx +11 -9
  216. package/src/screens/conversations/__tests__/conversations_screen.test.tsx +35 -9
  217. package/src/screens/conversations/components/__tests__/filter_dropdown_list_header_component.test.tsx +0 -8
  218. package/src/screens/conversations/components/__tests__/search_list_header_component.test.tsx +0 -10
  219. package/src/screens/conversations/conversations_screen.tsx +67 -3
  220. package/src/screens/get_help_screen.tsx +4 -18
  221. package/src/screens/search/components/__tests__/search_results_list.test.tsx +1 -0
  222. package/src/types/jolt_events/index.ts +2 -0
  223. package/src/types/jolt_events/person_events.ts +16 -0
  224. package/src/types/resources/groups/groups_group_resource.ts +1 -1
  225. package/src/types/resources/groups/groups_membership_resource.ts +10 -0
  226. package/src/types/resources/groups/index.ts +1 -0
  227. package/src/utils/__tests__/attachment_kind.test.ts +0 -4
  228. package/src/utils/__tests__/convert_attachments_for_create.test.ts +0 -28
  229. package/src/utils/__tests__/is_input_editable.test.ts +1 -2
  230. package/src/utils/__tests__/message_text.test.ts +0 -5
  231. package/src/utils/__tests__/session_manager.test.ts +0 -83
  232. package/src/utils/__tests__/sha_256.test.ts +0 -34
  233. package/src/utils/__tests__/throttled_refresh.test.ts +101 -0
  234. package/src/utils/__tests__/uri.test.ts +51 -0
  235. package/src/utils/jolt/__tests__/parse_stream_user_event_type.test.ts +27 -0
  236. package/src/utils/jolt/parse_stream_user_event_type.ts +16 -0
  237. package/src/utils/native_adapters/__tests__/linking.test.ts +60 -4
  238. package/src/utils/native_adapters/configuration.ts +5 -0
  239. package/src/utils/native_adapters/index.ts +1 -0
  240. package/src/utils/native_adapters/linking.ts +50 -2
  241. package/src/utils/native_adapters/updates.ts +16 -0
  242. package/src/utils/product_analytics_token.ts +120 -0
  243. package/src/utils/throttled_refresh.ts +62 -0
  244. package/src/__tests__/event-polyfill.test.ts +0 -313
  245. package/src/__tests__/index.tsx +0 -5
  246. package/src/__tests__/jest.ts +0 -11
  247. package/src/__tests__/utils/uri.ts +0 -65
  248. package/src/components/display/__tests__/version_footer.test.tsx +0 -48
  249. package/src/screens/search/components/__tests__/search_blank_states.test.tsx +0 -20
  250. package/src/utils/__tests__/membership_sync_info_text.test.ts +0 -15
@@ -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,304 @@
1
+ import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
2
+ import { act, render, renderHook, waitFor } from '@testing-library/react-native'
3
+ import React from 'react'
4
+ import { Text } from 'react-native'
5
+ import { buildTestQueryClient } from '../../__utils__/query_client'
6
+ import { ChatProvider } from '../../contexts/chat_context'
7
+ import { Log } from '../../utils/native_adapters/configuration'
8
+ import {
9
+ productAnalyticsStorageKey,
10
+ StoredProductAnalyticsConfig,
11
+ TOKEN_EXPIRY_TIME,
12
+ } from '../../utils/product_analytics_token'
13
+ import { Session } from '../../utils/session'
14
+ import { ONE_HOUR } from '../../utils/time'
15
+ import { currentPersonQueryKey } from '../use_current_person'
16
+ import { analyticsEvents, useProductAnalytics } from '../use_product_analytics'
17
+
18
+ const mockStoredItems = new Map<string, string>()
19
+ jest.mock('../../utils/native_adapters', () => ({
20
+ ...jest.requireActual('../../utils/native_adapters'),
21
+ Storage: {
22
+ getItem: async (key: string) => mockStoredItems.get(key) ?? null,
23
+ setItem: async (key: string, value: string) => {
24
+ mockStoredItems.set(key, value)
25
+ },
26
+ removeItem: async (key: string) => {
27
+ mockStoredItems.delete(key)
28
+ },
29
+ },
30
+ }))
31
+
32
+ const AUTHORIZE_PATH = '/me/product_analytics_authorize'
33
+ const ANALYTICS_ENDPOINT = 'https://analytics.pco.test/events'
34
+ const accessToken = 'access-token-12345678'
35
+ const otherAccessToken = 'access-token-87654321'
36
+ const session = new Session({ token: { access_token: accessToken } })
37
+
38
+ const jsonResponse = (body: unknown, status = 200) => {
39
+ const response = {
40
+ ok: status >= 200 && status < 300,
41
+ status,
42
+ statusText: '',
43
+ url: '',
44
+ headers: {},
45
+ text: async () => JSON.stringify(body),
46
+ json: async () => body,
47
+ arrayBuffer: async () => new ArrayBuffer(0),
48
+ clone: () => response,
49
+ }
50
+ return response as unknown as Response
51
+ }
52
+
53
+ const authorizeResponse = (token: string) =>
54
+ jsonResponse({
55
+ data: {
56
+ type: 'ProductAnalyticsToken',
57
+ id: token,
58
+ attributes: { url: ANALYTICS_ENDPOINT, metadata: { person_id: '42' } },
59
+ },
60
+ })
61
+
62
+ const fetchMock = jest.fn<Promise<Response>, [string, RequestInit]>()
63
+ const authorizeCalls = () => fetchMock.mock.calls.filter(([url]) => url.includes(AUTHORIZE_PATH))
64
+ const analyticsCalls = () => fetchMock.mock.calls.filter(([url]) => url === ANALYTICS_ENDPOINT)
65
+ const sentEvents = () =>
66
+ analyticsCalls().flatMap(([, init]) => JSON.parse(init.body as string).events)
67
+
68
+ const respondWithToken = (token: string, status = 200, eventsStatus = 200) => {
69
+ fetchMock.mockImplementation(async url => {
70
+ if (url.includes(AUTHORIZE_PATH)) {
71
+ return status === 200 ? authorizeResponse(token) : jsonResponse({ errors: [] }, status)
72
+ }
73
+ return jsonResponse({}, eventsStatus)
74
+ })
75
+ }
76
+
77
+ const PERSON_ID = '42'
78
+
79
+ const storeConfig = (overrides: Partial<StoredProductAnalyticsConfig> = {}) => {
80
+ const config: StoredProductAnalyticsConfig = {
81
+ token: 'stored-token',
82
+ endpoint: ANALYTICS_ENDPOINT,
83
+ metadata: { person_id: PERSON_ID },
84
+ expiresAt: Date.now() + TOKEN_EXPIRY_TIME,
85
+ personId: PERSON_ID,
86
+ ...overrides,
87
+ }
88
+ mockStoredItems.set(productAnalyticsStorageKey(session), JSON.stringify(config))
89
+ }
90
+
91
+ let queryClient: QueryClient
92
+ let reportError: jest.SpyInstance
93
+
94
+ const buildWrapper =
95
+ (accessTokenForSession: string) =>
96
+ ({ children }: { children: React.ReactNode }) => (
97
+ <QueryClientProvider client={queryClient}>
98
+ <ChatProvider
99
+ value={{
100
+ token: { access_token: accessTokenForSession },
101
+ onUnauthorizedResponse: () => {},
102
+ theme: { theme: { colors: {} }, colorScheme: 'light' },
103
+ }}
104
+ >
105
+ {children}
106
+ </ChatProvider>
107
+ </QueryClientProvider>
108
+ )
109
+
110
+ const renderAnalytics = (accessTokenForSession = accessToken) =>
111
+ renderHook(() => useProductAnalytics(), { wrapper: buildWrapper(accessTokenForSession) })
112
+
113
+ beforeEach(() => {
114
+ queryClient = buildTestQueryClient()
115
+ queryClient.setQueryData(currentPersonQueryKey, { data: { type: 'Person', id: PERSON_ID } })
116
+ mockStoredItems.clear()
117
+ fetchMock.mockReset()
118
+ reportError = jest.spyOn(Log, 'reportError').mockImplementation(() => {})
119
+ global.fetch = fetchMock as unknown as typeof fetch
120
+ })
121
+
122
+ afterEach(() => {
123
+ queryClient.clear()
124
+ jest.restoreAllMocks()
125
+ })
126
+
127
+ describe('ChatProvider', () => {
128
+ const originalNodeEnv = process.env.NODE_ENV
129
+
130
+ beforeAll(() => {
131
+ process.env.NODE_ENV = 'development'
132
+ })
133
+
134
+ afterAll(() => {
135
+ process.env.NODE_ENV = originalNodeEnv
136
+ })
137
+
138
+ it('does not request a product analytics token when nothing publishes an event', async () => {
139
+ respondWithToken('unused-token')
140
+ const Wrapper = buildWrapper(accessToken)
141
+
142
+ render(<Text>A screen without analytics</Text>, { wrapper: Wrapper })
143
+ await act(async () => {})
144
+
145
+ expect(authorizeCalls()).toHaveLength(0)
146
+ })
147
+ })
148
+
149
+ describe('useProductAnalytics', () => {
150
+ it('requests the token once for concurrent events and sends both with it', async () => {
151
+ respondWithToken('fresh-token')
152
+ const { result } = renderAnalytics()
153
+
154
+ await act(() =>
155
+ Promise.all([
156
+ result.current.publishEvent(analyticsEvents.conversation_index_opened),
157
+ result.current.publishEvent(analyticsEvents.search_performed, { term_length: 3 }),
158
+ ])
159
+ )
160
+
161
+ expect(authorizeCalls()).toHaveLength(1)
162
+ expect(analyticsCalls()).toHaveLength(2)
163
+ analyticsCalls().forEach(([, init]) => {
164
+ expect(init.headers).toMatchObject({ 'X-Authorization': 'Bearer fresh-token' })
165
+ })
166
+ expect(sentEvents()).toEqual([
167
+ { name: analyticsEvents.conversation_index_opened, meta: { person_id: '42' } },
168
+ { name: analyticsEvents.search_performed, meta: { person_id: '42', term_length: 3 } },
169
+ ])
170
+ })
171
+
172
+ it('stores a fetched token with its expiry for this person', async () => {
173
+ respondWithToken('fresh-token')
174
+ const { result } = renderAnalytics()
175
+ const before = Date.now()
176
+
177
+ await act(() => result.current.publishEvent(analyticsEvents.conversation_show_opened))
178
+
179
+ const stored = JSON.parse(mockStoredItems.get(productAnalyticsStorageKey(session)) ?? 'null')
180
+ expect(stored).toMatchObject({
181
+ token: 'fresh-token',
182
+ endpoint: ANALYTICS_ENDPOINT,
183
+ personId: PERSON_ID,
184
+ })
185
+ expect(stored.expiresAt).toBeGreaterThanOrEqual(before + TOKEN_EXPIRY_TIME)
186
+ })
187
+
188
+ it('reuses a stored unexpired token for the same person without an authorize request', async () => {
189
+ respondWithToken('fresh-token')
190
+ storeConfig()
191
+ const { result } = renderAnalytics()
192
+
193
+ await act(() => result.current.publishEvent(analyticsEvents.conversation_index_opened))
194
+
195
+ expect(authorizeCalls()).toHaveLength(0)
196
+ expect(analyticsCalls()).toHaveLength(1)
197
+ expect(analyticsCalls()[0][1].headers).toMatchObject({
198
+ 'X-Authorization': 'Bearer stored-token',
199
+ })
200
+ })
201
+
202
+ it('replaces a stored token that is within an hour of expiring', async () => {
203
+ respondWithToken('fresh-token')
204
+ storeConfig({ expiresAt: Date.now() + ONE_HOUR / 2 })
205
+ const { result } = renderAnalytics()
206
+
207
+ await act(() => result.current.publishEvent(analyticsEvents.conversation_index_opened))
208
+
209
+ expect(authorizeCalls()).toHaveLength(1)
210
+ expect(analyticsCalls()[0][1].headers).toMatchObject({
211
+ 'X-Authorization': 'Bearer fresh-token',
212
+ })
213
+ expect(mockStoredItems.get(productAnalyticsStorageKey(session))).toContain('fresh-token')
214
+ })
215
+
216
+ it('reuses the stored token after the access token is refreshed', async () => {
217
+ respondWithToken('fresh-token')
218
+ storeConfig()
219
+ const { result } = renderAnalytics(otherAccessToken)
220
+
221
+ await act(() => result.current.publishEvent(analyticsEvents.conversation_index_opened))
222
+
223
+ expect(authorizeCalls()).toHaveLength(0)
224
+ expect(analyticsCalls()[0][1].headers).toMatchObject({
225
+ 'X-Authorization': 'Bearer stored-token',
226
+ })
227
+ })
228
+
229
+ it('replaces a token stored for another person', async () => {
230
+ respondWithToken('fresh-token')
231
+ storeConfig({ personId: '99' })
232
+ const { result } = renderAnalytics()
233
+
234
+ await act(() => result.current.publishEvent(analyticsEvents.conversation_index_opened))
235
+
236
+ expect(authorizeCalls()).toHaveLength(1)
237
+ expect(analyticsCalls()[0][1].headers).toMatchObject({
238
+ 'X-Authorization': 'Bearer fresh-token',
239
+ })
240
+ expect(mockStoredItems.get(productAnalyticsStorageKey(session))).toContain('fresh-token')
241
+ })
242
+
243
+ it('drops the event without retrying when the authorize request is rejected', async () => {
244
+ jest.spyOn(console, 'warn').mockImplementation(() => {})
245
+ jest.spyOn(console, 'error').mockImplementation(() => {})
246
+ respondWithToken('fresh-token', 429)
247
+ const { result } = renderAnalytics()
248
+
249
+ const responses = await act(() =>
250
+ result.current.publishEvent(analyticsEvents.conversation_index_opened)
251
+ )
252
+
253
+ expect(responses).toEqual([])
254
+ expect(authorizeCalls()).toHaveLength(1)
255
+ expect(analyticsCalls()).toHaveLength(0)
256
+ await waitFor(() => expect(mockStoredItems.size).toBe(0))
257
+ // Reported once, by the API client's HTTP instrumentation, not again here
258
+ expect(reportError).toHaveBeenCalledTimes(1)
259
+ expect(reportError.mock.calls[0][1]).toMatchObject({ scope: 'http' })
260
+ })
261
+
262
+ it('reports an unexpected token failure to Sentry and drops the event', async () => {
263
+ jest.spyOn(console, 'warn').mockImplementation(() => {})
264
+ // An authorize response without the expected body
265
+ fetchMock.mockImplementation(async () => jsonResponse({}))
266
+ const { result } = renderAnalytics()
267
+
268
+ await act(() => result.current.publishEvent(analyticsEvents.conversation_index_opened))
269
+
270
+ expect(analyticsCalls()).toHaveLength(0)
271
+ expect(reportError).toHaveBeenCalledTimes(1)
272
+ expect(reportError.mock.calls[0][1]).toMatchObject({
273
+ tags: { feature: 'product-analytics', 'analytics.stage': 'prepare' },
274
+ })
275
+ })
276
+
277
+ it('reports events the analytics endpoint rejects', async () => {
278
+ respondWithToken('fresh-token', 200, 401)
279
+ const { result } = renderAnalytics()
280
+
281
+ await act(() => result.current.publishEvent(analyticsEvents.conversation_index_opened))
282
+
283
+ expect(reportError).toHaveBeenCalledTimes(1)
284
+ const [error, context] = reportError.mock.calls[0]
285
+ expect(error.name).toBe('HTTPError401')
286
+ expect(context).toMatchObject({ tags: { 'analytics.stage': 'send', 'http.status': '401' } })
287
+ })
288
+
289
+ it('does not report a network failure while sending events', async () => {
290
+ jest.spyOn(console, 'warn').mockImplementation(() => {})
291
+ fetchMock.mockImplementation(async url => {
292
+ if (url.includes(AUTHORIZE_PATH)) return authorizeResponse('fresh-token')
293
+ throw new TypeError('Network request failed')
294
+ })
295
+ const { result } = renderAnalytics()
296
+
297
+ const responses = await act(() =>
298
+ result.current.publishEvent(analyticsEvents.conversation_index_opened)
299
+ )
300
+
301
+ expect(responses).toEqual([])
302
+ expect(reportError).not.toHaveBeenCalled()
303
+ })
304
+ })
@@ -1,7 +1,8 @@
1
1
  import { useQuery } from '@tanstack/react-query'
2
2
  import { ApiResource, ResourceObject } from '../../types'
3
3
  import { toMs } from '../../utils/time'
4
- import { useApiClient } from '../use_api_client'
4
+ import { App, useApiClient } from '../use_api_client'
5
+ import { useGroupsProxy } from './use_groups_proxy'
5
6
 
6
7
  const STALE_TIME_MS = toMs(25, 'minutes') // under Groups' 30-min server-side expiry
7
8
 
@@ -12,20 +13,13 @@ interface Props {
12
13
 
13
14
  export function useGroupChatConversationPayload({ groupId, enabled = true }: Props) {
14
15
  const apiClient = useApiClient()
15
- const url = `/me/groups/${groupId}/chat_conversation_payload`
16
+ const proxied = useGroupsProxy()
17
+ const { app, url, data: body } = groupChatConversationPayloadRequest({ groupId, proxied })
16
18
 
17
19
  const { data, ...rest } = useQuery({
18
20
  queryKey: ['groups', url],
19
21
  queryFn: () =>
20
- apiClient.groups.post<ApiResource<GroupChatConversationPayload>>({
21
- url,
22
- data: {
23
- data: {
24
- type: 'GroupChatConversationPayload',
25
- attributes: { title: '' },
26
- },
27
- },
28
- }),
22
+ apiClient[app].post<ApiResource<GroupChatConversationPayload>>({ url, data: body }),
29
23
  staleTime: STALE_TIME_MS,
30
24
  refetchOnMount: 'always',
31
25
  enabled,
@@ -34,7 +28,31 @@ export function useGroupChatConversationPayload({ groupId, enabled = true }: Pro
34
28
  return { payload: data?.data.value, ...rest }
35
29
  }
36
30
 
31
+ export function groupChatConversationPayloadRequest({
32
+ groupId,
33
+ title = '',
34
+ proxied,
35
+ }: {
36
+ groupId: number
37
+ title?: string
38
+ proxied: boolean
39
+ }): { app: App; url: string; data: object } {
40
+ if (proxied) {
41
+ return {
42
+ app: 'chat',
43
+ url: `/me/groups_groups/${groupId}/chat_conversation_payload`,
44
+ data: { data: { type: 'GroupsChatConversationPayload', attributes: { title } } },
45
+ }
46
+ }
47
+
48
+ return {
49
+ app: 'groups',
50
+ url: `/me/groups/${groupId}/chat_conversation_payload`,
51
+ data: { data: { type: 'GroupChatConversationPayload', attributes: { title } } },
52
+ }
53
+ }
54
+
37
55
  interface GroupChatConversationPayload extends ResourceObject {
38
- type: 'GroupChatConversationPayload'
56
+ type: 'GroupChatConversationPayload' | 'GroupsChatConversationPayload'
39
57
  value: string
40
58
  }