@planningcenter/chat-react-native 4.8.0-rc.3 → 4.8.0-rc.5

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 (57) hide show
  1. package/build/components/conversations/conversation_actions.d.ts +2 -1
  2. package/build/components/conversations/conversation_actions.d.ts.map +1 -1
  3. package/build/components/conversations/conversation_actions.js +137 -99
  4. package/build/components/conversations/conversation_actions.js.map +1 -1
  5. package/build/components/conversations/conversation_preview.d.ts.map +1 -1
  6. package/build/components/conversations/conversation_preview.js +154 -110
  7. package/build/components/conversations/conversation_preview.js.map +1 -1
  8. package/build/components/conversations/conversations.d.ts.map +1 -1
  9. package/build/components/conversations/conversations.js +50 -48
  10. package/build/components/conversations/conversations.js.map +1 -1
  11. package/build/components/display/checkbox.d.ts +8 -0
  12. package/build/components/display/checkbox.d.ts.map +1 -0
  13. package/build/components/display/checkbox.js +87 -0
  14. package/build/components/display/checkbox.js.map +1 -0
  15. package/build/components/display/index.d.ts +1 -0
  16. package/build/components/display/index.d.ts.map +1 -1
  17. package/build/components/display/index.js +1 -0
  18. package/build/components/display/index.js.map +1 -1
  19. package/build/contexts/conversations_context.d.ts +5 -0
  20. package/build/contexts/conversations_context.d.ts.map +1 -1
  21. package/build/contexts/conversations_context.js +121 -32
  22. package/build/contexts/conversations_context.js.map +1 -1
  23. package/build/hooks/use_bulk_conversation_actions.d.ts +8 -0
  24. package/build/hooks/use_bulk_conversation_actions.d.ts.map +1 -0
  25. package/build/hooks/use_bulk_conversation_actions.js +309 -0
  26. package/build/hooks/use_bulk_conversation_actions.js.map +1 -0
  27. package/build/hooks/use_conversations_cache.d.ts +14 -2
  28. package/build/hooks/use_conversations_cache.d.ts.map +1 -1
  29. package/build/hooks/use_conversations_cache.js +149 -56
  30. package/build/hooks/use_conversations_cache.js.map +1 -1
  31. package/build/navigation/index.d.ts.map +1 -1
  32. package/build/navigation/index.js +5 -7
  33. package/build/navigation/index.js.map +1 -1
  34. package/build/screens/conversation_filter_recipients/components/checkbox_row.d.ts.map +1 -1
  35. package/build/screens/conversation_filter_recipients/components/checkbox_row.js +9 -64
  36. package/build/screens/conversation_filter_recipients/components/checkbox_row.js.map +1 -1
  37. package/build/screens/conversations/conversations_screen.d.ts +4 -0
  38. package/build/screens/conversations/conversations_screen.d.ts.map +1 -1
  39. package/build/screens/conversations/conversations_screen.js +102 -31
  40. package/build/screens/conversations/conversations_screen.js.map +1 -1
  41. package/package.json +2 -2
  42. package/src/components/conversations/__tests__/conversation_actions.test.tsx +30 -2
  43. package/src/components/conversations/__tests__/conversation_preview.test.tsx +69 -3
  44. package/src/components/conversations/conversation_actions.tsx +13 -6
  45. package/src/components/conversations/conversation_preview.tsx +12 -1
  46. package/src/components/conversations/conversations.tsx +2 -1
  47. package/src/components/display/checkbox.tsx +47 -0
  48. package/src/components/display/index.ts +1 -0
  49. package/src/contexts/__tests__/conversations_context.test.tsx +86 -0
  50. package/src/contexts/conversations_context.tsx +69 -2
  51. package/src/hooks/__tests__/use_bulk_conversation_actions.test.tsx +119 -0
  52. package/src/hooks/use_bulk_conversation_actions.ts +173 -0
  53. package/src/hooks/use_conversations_cache.ts +32 -3
  54. package/src/navigation/index.tsx +8 -8
  55. package/src/screens/conversation_filter_recipients/components/checkbox_row.tsx +3 -35
  56. package/src/screens/conversations/__tests__/conversations_screen.test.tsx +5 -0
  57. package/src/screens/conversations/conversations_screen.tsx +49 -3
@@ -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
+ })
@@ -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
+ }
@@ -1,4 +1,4 @@
1
- import { InfiniteData, useQueryClient } from '@tanstack/react-query'
1
+ import { InfiniteData, QueryKey, useQueryClient } from '@tanstack/react-query'
2
2
  import { ApiCollection, ConversationResource } from '../types'
3
3
  import {
4
4
  deleteRecordInPagesData,
@@ -10,6 +10,7 @@ import { useApiClient } from './use_api_client'
10
10
  import { getRequestQueryKey } from './use_suspense_api'
11
11
 
12
12
  type QueryData = InfiniteData<ApiCollection<ConversationResource>>
13
+ export type ConversationListsSnapshot = Array<[QueryKey, QueryData | undefined]>
13
14
 
14
15
  export function useConversationsCache(args?: Partial<ConversationRequestArgs>) {
15
16
  const apiClient = useApiClient()
@@ -63,8 +64,32 @@ export function useConversationsCache(args?: Partial<ConversationRequestArgs>) {
63
64
  })
64
65
  }
65
66
 
66
- const invalidateAllLists = () =>
67
- queryClient.invalidateQueries({ queryKey: [conversationsRequestArgs.url] })
67
+ const listsQueryKey = (filter?: string) =>
68
+ filter ? [conversationsRequestArgs.url, { filter }] : [conversationsRequestArgs.url]
69
+
70
+ const invalidateAllLists = ({ filter }: { filter?: string } = {}) =>
71
+ queryClient.invalidateQueries({ queryKey: listsQueryKey(filter) })
72
+
73
+ const cancelAllLists = () => queryClient.cancelQueries({ queryKey: listsQueryKey() })
74
+
75
+ const snapshotAllLists = (): ConversationListsSnapshot =>
76
+ queryClient.getQueriesData<QueryData>({ queryKey: listsQueryKey() })
77
+
78
+ const restoreLists = (lists: ConversationListsSnapshot) =>
79
+ lists.forEach(([queryKey, data]) => queryClient.setQueryData<QueryData>(queryKey, data))
80
+
81
+ const removeFromAllLists = (ids: number[], { filter }: { filter?: string } = {}) =>
82
+ queryClient.setQueriesData<QueryData>({ queryKey: listsQueryKey(filter) }, prev => {
83
+ if (!prev?.pages) return prev
84
+
85
+ return {
86
+ ...prev,
87
+ pages: prev.pages.map(page => ({
88
+ ...page,
89
+ data: page.data.filter(({ id }) => !ids.includes(id)),
90
+ })),
91
+ }
92
+ })
68
93
 
69
94
  const handleConversationDestroy = ({ id }: { id: number }) => {
70
95
  if (!id) return
@@ -93,12 +118,16 @@ export function useConversationsCache(args?: Partial<ConversationRequestArgs>) {
93
118
  }
94
119
 
95
120
  return {
121
+ cancelAllLists,
96
122
  queryKey: conversationQueryKey,
97
123
  create: updateOrCreate,
98
124
  destroy: handleConversationDestroy,
99
125
  fetchSync: fetchAndSync,
100
126
  invalidate: () => queryClient.invalidateQueries({ queryKey: conversationQueryKey }),
101
127
  invalidateAllLists,
128
+ removeFromAllLists,
129
+ restoreLists,
130
+ snapshotAllLists,
102
131
  update: updateOrCreate,
103
132
  updateAll,
104
133
  updateInAllLists,
@@ -60,7 +60,10 @@ import {
60
60
  ConversationSelectTypeScreen,
61
61
  ConversationSelectTypeScreenOptions,
62
62
  } from '../screens/conversation_select_type_screen'
63
- import { ConversationsScreen } from '../screens/conversations/conversations_screen'
63
+ import {
64
+ ConversationsScreen,
65
+ conversationsScreenOptions,
66
+ } from '../screens/conversations/conversations_screen'
64
67
  import { GetHelpScreen } from '../screens/get_help_screen'
65
68
  import {
66
69
  GroupNotificationLevelSelectScreen,
@@ -181,13 +184,10 @@ export const ChatStack = createNativeStackNavigator({
181
184
  Conversations: {
182
185
  screen: ConversationsScreen,
183
186
  options: ({ route, navigation }) =>
184
- composeOptions(
185
- {
186
- headerTitle: (route.params as { title?: string })?.title ?? 'Chat',
187
- headerBackVisible: false,
188
- },
189
- withRightClose({ onPress: navigation.goBack })
190
- ),
187
+ conversationsScreenOptions({
188
+ title: (route.params as { title?: string })?.title,
189
+ onClose: navigation.goBack,
190
+ }),
191
191
  },
192
192
  ConversationFilters: {
193
193
  screen: ConversationFiltersScreen,
@@ -1,8 +1,7 @@
1
1
  import { type RouteProp, useRoute } from '@react-navigation/native'
2
- import { Pressable, View, StyleSheet, type ViewStyle } from 'react-native'
3
- import { Icon, Text } from '../../../components'
2
+ import { Pressable, StyleSheet, type ViewStyle } from 'react-native'
3
+ import { Checkbox, Text } from '../../../components'
4
4
  import { useTheme } from '../../../hooks'
5
- import { tokens } from '../../../vendor/tapestry/tokens'
6
5
  import { ConversationFilterRecipientsScreenProps, SetTeamFilters, TeamProps } from '../types'
7
6
 
8
7
  interface TeamRowProps {
@@ -43,7 +42,7 @@ export const CheckboxRow = ({
43
42
  accessibilityLabelledBy={accessibilityLabelledBy}
44
43
  accessibilityLabel={`${teamName} team`}
45
44
  >
46
- <CheckboxIcon checked={checked} />
45
+ <Checkbox checked={checked} />
47
46
  <Text style={styles.label} numberOfLines={2}>
48
47
  {teamName}
49
48
  </Text>
@@ -51,28 +50,9 @@ export const CheckboxRow = ({
51
50
  )
52
51
  }
53
52
 
54
- function CheckboxIcon({ checked }: { checked: boolean }) {
55
- const styles = useStyles()
56
- const checkedStyle = checked ? styles.checkedContainer : styles.uncheckedContainer
57
-
58
- return (
59
- <View style={checkedStyle}>
60
- {checked && <Icon name="general.thickCheckmark" style={styles.checkedIcon} />}
61
- </View>
62
- )
63
- }
64
-
65
53
  const useStyles = () => {
66
54
  const { colors } = useTheme()
67
55
 
68
- const baseCheckboxStyles: ViewStyle = {
69
- width: 20,
70
- height: 20,
71
- borderRadius: 40,
72
- alignItems: 'center',
73
- justifyContent: 'center',
74
- }
75
-
76
56
  return StyleSheet.create({
77
57
  checkboxRow: {
78
58
  flexDirection: 'row',
@@ -89,17 +69,5 @@ const useStyles = () => {
89
69
  label: {
90
70
  flex: 1,
91
71
  },
92
- checkedContainer: {
93
- ...baseCheckboxStyles,
94
- backgroundColor: colors.statusSuccessIcon,
95
- },
96
- uncheckedContainer: {
97
- ...baseCheckboxStyles,
98
- borderWidth: 2,
99
- borderColor: colors.borderColorDefaultDarker,
100
- },
101
- checkedIcon: {
102
- color: tokens.colorNeutral100White,
103
- },
104
72
  })
105
73
  }
@@ -12,6 +12,10 @@ import {
12
12
  import { ConversationsScreen } from '../conversations_screen'
13
13
 
14
14
  const mockGet = jest.fn()
15
+ jest.mock('@react-navigation/native', () => ({
16
+ ...jest.requireActual('@react-navigation/native'),
17
+ useNavigation: () => ({ setOptions: jest.fn(), goBack: jest.fn() }),
18
+ }))
15
19
  jest.mock('../../../hooks/use_api_client', () => ({
16
20
  useApiClient: () => ({ chat: { get: mockGet } }),
17
21
  }))
@@ -21,6 +25,7 @@ jest.mock('../../../hooks/use_product_analytics', () => ({
21
25
  }))
22
26
  jest.mock('../../../contexts/conversations_context', () => ({
23
27
  ConversationsContextProvider: ({ children }: { children: React.ReactNode }) => children,
28
+ useConversationsContext: () => ({ selectMode: false, selectedIds: [] }),
24
29
  }))
25
30
  jest.mock('../../../components', () => ({
26
31
  Conversations: ({ ListHeaderComponent }: { ListHeaderComponent: React.ComponentType }) => (
@@ -1,9 +1,17 @@
1
- import { StaticScreenProps } from '@react-navigation/native'
2
- import React from 'react'
1
+ import { StaticScreenProps, useNavigation } from '@react-navigation/native'
2
+ import React, { useLayoutEffect, useRef } from 'react'
3
3
  import { StyleSheet, View } from 'react-native'
4
4
  import { Conversations } from '../../components'
5
+ import {
6
+ composeOptions,
7
+ withRightClose,
8
+ withRightText,
9
+ } from '../../components/display/platform_modal_header_buttons'
5
10
  import { Toast } from '../../components/display/toast'
6
- import { ConversationsContextProvider } from '../../contexts/conversations_context'
11
+ import {
12
+ ConversationsContextProvider,
13
+ useConversationsContext,
14
+ } from '../../contexts/conversations_context'
7
15
  import { useFilterDropdownEnabled } from '../../hooks/use_filter_dropdown_enabled'
8
16
  import { analyticsEvents, usePublishProductAnalyticsEvent } from '../../hooks/use_product_analytics'
9
17
  import { useSearchEnabled } from '../../hooks/use_search_enabled'
@@ -23,6 +31,18 @@ export type ConversationsScreenProps = StaticScreenProps<{
23
31
  show_unread?: boolean
24
32
  }>
25
33
 
34
+ export const conversationsScreenOptions = ({
35
+ title,
36
+ onClose,
37
+ }: {
38
+ title?: string
39
+ onClose: () => void
40
+ }) =>
41
+ composeOptions(
42
+ { headerTitle: title ?? 'Chat', headerBackVisible: false },
43
+ withRightClose({ onPress: onClose })
44
+ )
45
+
26
46
  export function ConversationsScreen({ route }: ConversationsScreenProps) {
27
47
  const styles = useStyles()
28
48
  const Header = useListHeaderComponent()
@@ -32,6 +52,7 @@ export function ConversationsScreen({ route }: ConversationsScreenProps) {
32
52
  return (
33
53
  <View style={styles.container}>
34
54
  <ConversationsContextProvider args={route.params} opts={{ throwOnError: true }}>
55
+ <SelectModeHeader title={route.params?.title} />
35
56
  <Conversations ListHeaderComponent={Header} />
36
57
  </ConversationsContextProvider>
37
58
  <Toast />
@@ -39,6 +60,31 @@ export function ConversationsScreen({ route }: ConversationsScreenProps) {
39
60
  )
40
61
  }
41
62
 
63
+ function SelectModeHeader({ title }: { title?: string }) {
64
+ const navigation = useNavigation()
65
+ const { selectMode, selectedIds, clearSelection } = useConversationsContext()
66
+ const hasEnteredSelectMode = useRef(false)
67
+ const selectedCount = selectedIds.length
68
+
69
+ useLayoutEffect(() => {
70
+ if (selectMode) hasEnteredSelectMode.current = true
71
+ if (!hasEnteredSelectMode.current) return
72
+
73
+ navigation.setOptions(
74
+ selectMode
75
+ ? composeOptions(
76
+ {
77
+ headerTitle: selectedCount > 0 ? `${selectedCount} selected` : 'Select conversations',
78
+ },
79
+ withRightText({ text: 'Cancel', onPress: clearSelection })
80
+ )
81
+ : conversationsScreenOptions({ title, onClose: navigation.goBack })
82
+ )
83
+ }, [navigation, selectMode, selectedCount, clearSelection, title])
84
+
85
+ return null
86
+ }
87
+
42
88
  const useListHeaderComponent = () => {
43
89
  const filterDropdownEnabled = useFilterDropdownEnabled()
44
90
  const searchEnabled = useSearchEnabled()