@planningcenter/chat-react-native 4.8.0-qa-staging.1 → 4.8.0-qa-staging.3

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 (64) 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 +120 -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 +143 -107
  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 +154 -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/index.d.ts +1 -0
  20. package/build/components/display/index.d.ts.map +1 -1
  21. package/build/components/display/index.js +1 -0
  22. package/build/components/display/index.js.map +1 -1
  23. package/build/contexts/conversations_context.d.ts +5 -0
  24. package/build/contexts/conversations_context.d.ts.map +1 -1
  25. package/build/contexts/conversations_context.js +121 -32
  26. package/build/contexts/conversations_context.js.map +1 -1
  27. package/build/hooks/use_bulk_conversation_actions.d.ts +8 -0
  28. package/build/hooks/use_bulk_conversation_actions.d.ts.map +1 -0
  29. package/build/hooks/use_bulk_conversation_actions.js +309 -0
  30. package/build/hooks/use_bulk_conversation_actions.js.map +1 -0
  31. package/build/hooks/use_conversations_cache.d.ts +14 -2
  32. package/build/hooks/use_conversations_cache.d.ts.map +1 -1
  33. package/build/hooks/use_conversations_cache.js +149 -56
  34. package/build/hooks/use_conversations_cache.js.map +1 -1
  35. package/build/navigation/index.d.ts.map +1 -1
  36. package/build/navigation/index.js +5 -7
  37. package/build/navigation/index.js.map +1 -1
  38. package/build/screens/conversation_filter_recipients/components/checkbox_row.d.ts.map +1 -1
  39. package/build/screens/conversation_filter_recipients/components/checkbox_row.js +9 -64
  40. package/build/screens/conversation_filter_recipients/components/checkbox_row.js.map +1 -1
  41. package/build/screens/conversations/conversations_screen.d.ts +4 -0
  42. package/build/screens/conversations/conversations_screen.d.ts.map +1 -1
  43. package/build/screens/conversations/conversations_screen.js +122 -43
  44. package/build/screens/conversations/conversations_screen.js.map +1 -1
  45. package/package.json +3 -3
  46. package/src/components/conversations/__tests__/bulk_conversation_actions_bar.test.tsx +95 -0
  47. package/src/components/conversations/__tests__/conversation_actions.test.tsx +36 -11
  48. package/src/components/conversations/__tests__/conversation_preview.test.tsx +69 -3
  49. package/src/components/conversations/bulk_conversation_actions_bar.tsx +108 -0
  50. package/src/components/conversations/conversation_actions.tsx +18 -12
  51. package/src/components/conversations/conversation_preview.tsx +12 -1
  52. package/src/components/conversations/conversations.tsx +2 -1
  53. package/src/components/display/checkbox.tsx +47 -0
  54. package/src/components/display/index.ts +1 -0
  55. package/src/contexts/__tests__/conversations_context.test.tsx +86 -0
  56. package/src/contexts/conversations_context.tsx +69 -2
  57. package/src/hooks/__tests__/use_bulk_conversation_actions.test.tsx +119 -0
  58. package/src/hooks/__tests__/use_hide_conversation.test.tsx +15 -3
  59. package/src/hooks/use_bulk_conversation_actions.ts +173 -0
  60. package/src/hooks/use_conversations_cache.ts +32 -3
  61. package/src/navigation/index.tsx +8 -8
  62. package/src/screens/conversation_filter_recipients/components/checkbox_row.tsx +3 -35
  63. package/src/screens/conversations/__tests__/conversations_screen.test.tsx +8 -0
  64. package/src/screens/conversations/conversations_screen.tsx +51 -3
@@ -0,0 +1,108 @@
1
+ import React, { useEffect, useState } from 'react'
2
+ import { StyleSheet } from 'react-native'
3
+ import Animated, { FadeIn, LayoutAnimationConfig, ReduceMotion } from 'react-native-reanimated'
4
+ import { useSafeAreaInsets } from 'react-native-safe-area-context'
5
+ import { useConversationsContext } from '../../contexts/conversations_context'
6
+ import { useReduceMotion, useTheme } from '../../hooks'
7
+ import { useBulkConversationActions } from '../../hooks/use_bulk_conversation_actions'
8
+ import { ConversationResource } from '../../types'
9
+ import { MAX_FONT_SIZE_MULTIPLIER_LANDMARK, isArchivedConversation } from '../../utils'
10
+ import { dismissToast } from '../../utils/toast_store'
11
+ import { Button } from '../display'
12
+
13
+ export function BulkConversationActionsBar() {
14
+ const styles = useStyles()
15
+ const reduceMotion = useReduceMotion() ? ReduceMotion.Always : ReduceMotion.Never
16
+ const {
17
+ selectMode,
18
+ selectedIds,
19
+ conversations,
20
+ hideable,
21
+ clearSelection,
22
+ args: { show_hidden: hiddenView = false },
23
+ } = useConversationsContext()
24
+ const { hide, unhide, silence, markRead } = useBulkConversationActions()
25
+ const [pending, setPending] = useState(false)
26
+
27
+ const selected = conversations.filter(({ id }) => selectedIds.includes(id))
28
+ const disabled = pending || selected.length === 0
29
+ const canSilence = !disabled && !selected.some(isArchivedConversation)
30
+ const canHide = canSilence && hideable
31
+
32
+ const run = (action: (_conversations: ConversationResource[]) => Promise<void>) => async () => {
33
+ setPending(true)
34
+ try {
35
+ await action(selected)
36
+ } finally {
37
+ setPending(false)
38
+ clearSelection()
39
+ }
40
+ }
41
+
42
+ useEffect(() => {
43
+ if (selectMode) dismissToast()
44
+ }, [selectMode])
45
+
46
+ return (
47
+ <LayoutAnimationConfig skipEntering>
48
+ {selectMode && (
49
+ <Animated.View
50
+ entering={FadeIn.duration(300).reduceMotion(reduceMotion)}
51
+ style={styles.container}
52
+ testID="bulk-conversation-actions-bar"
53
+ >
54
+ <Button
55
+ variant="outline"
56
+ title={hiddenView ? 'Unhide' : 'Hide'}
57
+ iconNameLeft={hiddenView ? 'general.showEye' : 'general.hideEye'}
58
+ disabled={!canHide}
59
+ onPress={run(hiddenView ? unhide : hide)}
60
+ style={styles.button}
61
+ maxFontSizeMultiplier={MAX_FONT_SIZE_MULTIPLIER_LANDMARK}
62
+ />
63
+ <Button
64
+ variant="outline"
65
+ title="Silence"
66
+ iconNameLeft="general.bellMuted"
67
+ disabled={!canSilence}
68
+ onPress={run(silence)}
69
+ style={styles.button}
70
+ maxFontSizeMultiplier={MAX_FONT_SIZE_MULTIPLIER_LANDMARK}
71
+ />
72
+ <Button
73
+ variant="outline"
74
+ title="Mark read"
75
+ iconNameLeft="general.outlinedTextMessage"
76
+ disabled={disabled}
77
+ onPress={run(markRead)}
78
+ style={styles.button}
79
+ maxFontSizeMultiplier={MAX_FONT_SIZE_MULTIPLIER_LANDMARK}
80
+ />
81
+ </Animated.View>
82
+ )}
83
+ </LayoutAnimationConfig>
84
+ )
85
+ }
86
+
87
+ const useStyles = () => {
88
+ const { bottom } = useSafeAreaInsets()
89
+ const { colors } = useTheme()
90
+ const containerVerticalPadding = 16
91
+
92
+ return StyleSheet.create({
93
+ container: {
94
+ flexDirection: 'row',
95
+ flexWrap: 'wrap',
96
+ gap: 8,
97
+ backgroundColor: colors.surfaceColor090,
98
+ paddingHorizontal: 16,
99
+ paddingTop: containerVerticalPadding,
100
+ paddingBottom: bottom + containerVerticalPadding,
101
+ borderTopWidth: 1,
102
+ borderTopColor: colors.borderColorDefaultDim,
103
+ },
104
+ button: {
105
+ flexGrow: 1,
106
+ },
107
+ })
108
+ }
@@ -1,4 +1,3 @@
1
- import { useNavigation } from '@react-navigation/native'
2
1
  import React, { ReactNode, useCallback, useEffect, useRef, useState } from 'react'
3
2
  import {
4
3
  AccessibilityActionEvent,
@@ -32,17 +31,18 @@ export function ConversationActions({
32
31
  style,
33
32
  onPress,
34
33
  accessibilityLabel,
34
+ selected,
35
35
  }: {
36
36
  children: ReactNode
37
37
  conversation: ConversationResource
38
38
  onPress: () => void
39
39
  style?: StyleProp<ViewStyle>
40
40
  accessibilityLabel?: string
41
+ selected?: boolean
41
42
  }) {
42
43
  const swipeableRef = useRef<SwipeableMethods>(null)
43
- const navigation = useNavigation()
44
44
  const styles = useStyles()
45
- const { activeConversationId, setActiveConversationId, hideable, args } =
45
+ const { activeConversationId, setActiveConversationId, hideable, args, enterSelectMode } =
46
46
  useConversationsContext()
47
47
  const [disabled, setDisabled] = useState(false)
48
48
  const overshootLeft = Platform.OS === 'ios'
@@ -67,6 +67,8 @@ export function ConversationActions({
67
67
  const isConversationEmpty = conversation.lastMessageCreatedAt === null
68
68
  const canMute = !isArchivedConversation(conversation)
69
69
  const canHide = hideable && hideConversationsEnabled && !isArchivedConversation(conversation)
70
+ const selectMode = selected !== undefined
71
+ const canEnterSelectMode = hideable && hideConversationsEnabled && !selectMode
70
72
 
71
73
  const handleSwipeableClose = useCallback(() => {
72
74
  setDisabled(false)
@@ -97,8 +99,8 @@ export function ConversationActions({
97
99
  if (disabled) return
98
100
 
99
101
  Haptic.impactLight()
100
- navigation.navigate('ConversationActions', { conversation_id: conversation.id })
101
- }, [disabled, navigation, conversation.id])
102
+ enterSelectMode(conversation.id)
103
+ }, [disabled, enterSelectMode, conversation.id])
102
104
 
103
105
  const handleLatestMessageUnread = useCallback(() => {
104
106
  markRead(!read)
@@ -132,11 +134,9 @@ export function ConversationActions({
132
134
  ]
133
135
  : []
134
136
 
135
- const accessibilityActions = [
136
- ...muteAccessibilityAction,
137
- ...hideAccessibilityAction,
138
- ...readAccessibilityAction,
139
- ]
137
+ const accessibilityActions = selectMode
138
+ ? []
139
+ : [...muteAccessibilityAction, ...hideAccessibilityAction, ...readAccessibilityAction]
140
140
 
141
141
  const handleAccessibilityAction = useCallback(
142
142
  (event: AccessibilityActionEvent) => {
@@ -162,6 +162,10 @@ export function ConversationActions({
162
162
  [handleLatestMessageUnread, handleMute, handleHide]
163
163
  )
164
164
 
165
+ useEffect(() => {
166
+ if (selectMode) handleSwipeableClose()
167
+ }, [selectMode, handleSwipeableClose])
168
+
165
169
  useEffect(() => {
166
170
  if (activeConversationId === conversation.id) return
167
171
 
@@ -171,6 +175,7 @@ export function ConversationActions({
171
175
  return (
172
176
  <ReanimatedSwipeable
173
177
  ref={swipeableRef}
178
+ enabled={!selectMode}
174
179
  childrenContainerStyle={styles.swipeableChildContainer}
175
180
  containerStyle={styles.swipeableContainer}
176
181
  overshootFriction={8}
@@ -199,11 +204,12 @@ export function ConversationActions({
199
204
  <Pressable
200
205
  testID={`conversation-${conversation.id}`}
201
206
  onPress={handlePress}
202
- onLongPress={canHide ? handleLongPress : undefined}
207
+ onLongPress={canEnterSelectMode ? handleLongPress : undefined}
203
208
  style={({ pressed }) => [style, pressed && platformPressedOpacityStyle]}
204
209
  android_ripple={{ color: androidRippleColor, borderless: false, foreground: true }}
205
210
  accessibilityLabel={accessibilityLabel}
206
- accessibilityRole="button"
211
+ accessibilityRole={selectMode ? 'checkbox' : 'button'}
212
+ accessibilityState={selectMode ? { checked: selected } : undefined}
207
213
  accessibilityActions={accessibilityActions}
208
214
  onAccessibilityAction={handleAccessibilityAction}
209
215
  >
@@ -19,6 +19,7 @@ import {
19
19
  IconTile,
20
20
  Text,
21
21
  Badge,
22
+ Checkbox,
22
23
  type BadgeProps,
23
24
  } from '../display'
24
25
  import { ConversationActions } from './conversation_actions'
@@ -44,8 +45,12 @@ export const ConversationPreview = ({
44
45
  const styles = useStyles()
45
46
  const {
46
47
  args: { show_hidden: hidden = false },
48
+ selectMode,
49
+ selectedIds,
50
+ toggleSelected,
47
51
  } = useConversationsContext()
48
52
  const {
53
+ id,
49
54
  conversationPreview,
50
55
  lastMessageCreatedAt,
51
56
  title,
@@ -61,6 +66,7 @@ export const ConversationPreview = ({
61
66
  const fallbackIconName = emptyConversation ? 'people.noTextMessage' : 'general.person'
62
67
  const hasMetaContent = lastMessageCreatedAt || unreadCount > 0 || muted || hidden
63
68
  const isUnread = unreadCount > 0 || unreadReaction
69
+ const selected = selectMode ? selectedIds.includes(id) : undefined
64
70
 
65
71
  const numberOfLinesScaledTitle = useScalableNumberOfLines(1)
66
72
  const numberOfLinesScaledPreviewText = useScalableNumberOfLines(2)
@@ -80,9 +86,11 @@ export const ConversationPreview = ({
80
86
  <ConversationActions
81
87
  conversation={conversation}
82
88
  style={[styles.previewRow, disabled && !archived && styles.disabled, style]}
83
- onPress={onPress}
89
+ onPress={selectMode ? () => toggleSelected(id) : onPress}
84
90
  accessibilityLabel={conversationAccessibilityLabel}
91
+ selected={selected}
85
92
  >
93
+ {selected !== undefined && <Checkbox checked={selected} style={styles.checkbox} />}
86
94
  {archived ? (
87
95
  <IconTile
88
96
  icon={faBoxArchive}
@@ -284,6 +292,9 @@ const useStyles = () => {
284
292
  disabled: {
285
293
  opacity: 0.4,
286
294
  },
295
+ checkbox: {
296
+ alignSelf: 'center',
297
+ },
287
298
  title: {
288
299
  fontSize: 16,
289
300
  color: colors.textColorDefaultPrimary,
@@ -32,6 +32,7 @@ export const Conversations = ({ ListHeaderComponent }: ConversationsProps) => {
32
32
  isRefetching,
33
33
  isFetched,
34
34
  hasNextPage,
35
+ selectMode,
35
36
  args: {
36
37
  chat_group_graph_id,
37
38
  group_source_app_name,
@@ -88,7 +89,7 @@ export const Conversations = ({ ListHeaderComponent }: ConversationsProps) => {
88
89
  contentInsetAdjustmentBehavior="automatic"
89
90
  onRefresh={refetch}
90
91
  refreshing={!isFetched && isRefetching}
91
- ListHeaderComponent={ListHeaderComponent}
92
+ ListHeaderComponent={selectMode ? null : ListHeaderComponent}
92
93
  ListEmptyComponent={
93
94
  <ConversationsBlankState
94
95
  isFilterApplied={isFilterApplied}
@@ -0,0 +1,47 @@
1
+ import React from 'react'
2
+ import { StyleProp, StyleSheet, View, ViewStyle } from 'react-native'
3
+ import { useTheme } from '../../hooks'
4
+ import { tokens } from '../../vendor/tapestry/tokens'
5
+ import { Icon } from './icon'
6
+
7
+ interface CheckboxProps {
8
+ checked: boolean
9
+ style?: StyleProp<ViewStyle>
10
+ }
11
+
12
+ export function Checkbox({ checked, style }: CheckboxProps) {
13
+ const styles = useStyles()
14
+
15
+ return (
16
+ <View style={[checked ? styles.checkedContainer : styles.uncheckedContainer, style]}>
17
+ {checked && <Icon name="general.thickCheckmark" style={styles.checkedIcon} />}
18
+ </View>
19
+ )
20
+ }
21
+
22
+ const useStyles = () => {
23
+ const { colors } = useTheme()
24
+
25
+ const baseCheckboxStyles: ViewStyle = {
26
+ width: 20,
27
+ height: 20,
28
+ borderRadius: 40,
29
+ alignItems: 'center',
30
+ justifyContent: 'center',
31
+ }
32
+
33
+ return StyleSheet.create({
34
+ checkedContainer: {
35
+ ...baseCheckboxStyles,
36
+ backgroundColor: colors.statusSuccessIcon,
37
+ },
38
+ uncheckedContainer: {
39
+ ...baseCheckboxStyles,
40
+ borderWidth: 2,
41
+ borderColor: colors.borderColorDefaultDarker,
42
+ },
43
+ checkedIcon: {
44
+ color: tokens.colorNeutral100White,
45
+ },
46
+ })
47
+ }
@@ -8,6 +8,7 @@ export * from './icon_tile'
8
8
  export * from './banner_collapsible'
9
9
  export * from './banner'
10
10
  export * from './button'
11
+ export * from './checkbox'
11
12
  export * from './adult_requirement_notice'
12
13
  export * from './child_notice'
13
14
  export * from './heading'
@@ -0,0 +1,86 @@
1
+ import { act, renderHook } from '@testing-library/react-native'
2
+ import React from 'react'
3
+ import { ConversationFiltersParams } from '../../screens/conversation_filters/screen_props'
4
+ import { ConversationsContextProvider, useConversationsContext } from '../conversations_context'
5
+
6
+ let mockHideEnabled = true
7
+ jest.mock('../../hooks/use_hide_conversations_enabled', () => ({
8
+ useHideConversationsEnabled: () => mockHideEnabled,
9
+ }))
10
+ jest.mock('../../hooks/use_conversations', () => ({
11
+ useConversations: () => ({ conversations: [] }),
12
+ }))
13
+
14
+ let mockArgs: ConversationFiltersParams = {}
15
+
16
+ const renderContext = () =>
17
+ renderHook(() => useConversationsContext(), {
18
+ wrapper: ({ children }: { children: React.ReactNode }) => (
19
+ <ConversationsContextProvider args={mockArgs}>{children}</ConversationsContextProvider>
20
+ ),
21
+ })
22
+
23
+ describe('ConversationsContextProvider selection', () => {
24
+ beforeEach(() => {
25
+ mockHideEnabled = true
26
+ mockArgs = {}
27
+ })
28
+
29
+ it('toggles conversations in and out of the selection', () => {
30
+ const { result } = renderContext()
31
+
32
+ act(() => result.current.enterSelectMode(1))
33
+ act(() => result.current.toggleSelected(2))
34
+
35
+ expect(result.current.selectMode).toBe(true)
36
+ expect(result.current.selectedIds).toEqual([1, 2])
37
+
38
+ act(() => result.current.toggleSelected(1))
39
+
40
+ expect(result.current.selectedIds).toEqual([2])
41
+ })
42
+
43
+ it('leaves select mode on clear', () => {
44
+ const { result } = renderContext()
45
+
46
+ act(() => result.current.enterSelectMode(1))
47
+ act(() => result.current.clearSelection())
48
+
49
+ expect(result.current.selectMode).toBe(false)
50
+ expect(result.current.selectedIds).toEqual([])
51
+ })
52
+
53
+ it('clears the selection when the filter changes', () => {
54
+ const { result, rerender } = renderContext()
55
+
56
+ act(() => result.current.enterSelectMode(1))
57
+ mockArgs = { show_unread: true }
58
+ rerender({})
59
+
60
+ expect(result.current.selectMode).toBe(false)
61
+ expect(result.current.selectedIds).toEqual([])
62
+ })
63
+
64
+ it('stays out of select mode when the flag is off', () => {
65
+ mockHideEnabled = false
66
+ const { result } = renderContext()
67
+
68
+ act(() => result.current.enterSelectMode(1))
69
+
70
+ expect(result.current.selectMode).toBe(false)
71
+ expect(result.current.selectedIds).toEqual([])
72
+ })
73
+
74
+ it('does not revive the selection when the flag flips off and back on', () => {
75
+ const { result, rerender } = renderContext()
76
+
77
+ act(() => result.current.enterSelectMode(1))
78
+ mockHideEnabled = false
79
+ rerender({})
80
+ mockHideEnabled = true
81
+ rerender({})
82
+
83
+ expect(result.current.selectMode).toBe(false)
84
+ expect(result.current.selectedIds).toEqual([])
85
+ })
86
+ })
@@ -3,9 +3,18 @@ import {
3
3
  InfiniteQueryObserverResult,
4
4
  InfiniteData,
5
5
  } from '@tanstack/react-query'
6
- import React, { createContext, PropsWithChildren, useContext, useMemo, useState } from 'react'
6
+ import React, {
7
+ createContext,
8
+ PropsWithChildren,
9
+ useCallback,
10
+ useContext,
11
+ useEffect,
12
+ useMemo,
13
+ useState,
14
+ } from 'react'
7
15
  import { ApiGetQueryOptions } from '../hooks'
8
16
  import { useConversations, UseConversationsValue } from '../hooks/use_conversations'
17
+ import { useHideConversationsEnabled } from '../hooks/use_hide_conversations_enabled'
9
18
  import { ConversationFiltersParams } from '../screens/conversation_filters/screen_props'
10
19
  import { ApiCollection, ConversationResource } from '../types'
11
20
  import { ResponseError } from '../utils/response_error'
@@ -15,6 +24,11 @@ interface ConversationsContextValue extends UseConversationsValue {
15
24
  setActiveConversationId: (_id: number) => void
16
25
  args: ConversationFiltersParams
17
26
  hideable: boolean
27
+ selectMode: boolean
28
+ selectedIds: number[]
29
+ enterSelectMode: (_id?: number) => void
30
+ toggleSelected: (_id: number) => void
31
+ clearSelection: () => void
18
32
  }
19
33
 
20
34
  const defaultQueryValue: UseConversationsValue = {
@@ -35,6 +49,11 @@ const ConversationsContext = createContext<ConversationsContextValue>({
35
49
  activeConversationId: undefined,
36
50
  setActiveConversationId: () => {},
37
51
  hideable: true,
52
+ selectMode: false,
53
+ selectedIds: [],
54
+ enterSelectMode: () => {},
55
+ toggleSelected: () => {},
56
+ clearSelection: () => {},
38
57
  ...defaultQueryValue,
39
58
  })
40
59
 
@@ -49,6 +68,10 @@ export const ConversationsContextProvider = ({
49
68
  hideable?: boolean
50
69
  }>) => {
51
70
  const [activeConversationId, setActiveConversationId] = useState<number | undefined>()
71
+ const hideConversationsEnabled = useHideConversationsEnabled()
72
+ const [selecting, setSelecting] = useState(false)
73
+ const [selectedIds, setSelectedIds] = useState<number[]>([])
74
+ const selectMode = hideConversationsEnabled && selecting
52
75
  const {
53
76
  chat_group_graph_id,
54
77
  group_source_app_name,
@@ -70,15 +93,59 @@ export const ConversationsContextProvider = ({
70
93
  paginatorOptions
71
94
  )
72
95
 
96
+ const enterSelectMode = useCallback((id?: number) => {
97
+ setSelecting(true)
98
+ setSelectedIds(id === undefined ? [] : [id])
99
+ }, [])
100
+
101
+ const toggleSelected = useCallback((id: number) => {
102
+ setSelectedIds(ids =>
103
+ ids.includes(id) ? ids.filter(selectedId => selectedId !== id) : [...ids, id]
104
+ )
105
+ }, [])
106
+
107
+ const clearSelection = useCallback(() => {
108
+ setSelecting(false)
109
+ setSelectedIds([])
110
+ }, [])
111
+
112
+ useEffect(() => {
113
+ clearSelection()
114
+ }, [
115
+ clearSelection,
116
+ hideConversationsEnabled,
117
+ chat_group_graph_id,
118
+ group_source_app_name,
119
+ show_direct_messages,
120
+ show_archived,
121
+ show_hidden,
122
+ show_unread,
123
+ ])
124
+
73
125
  const value = useMemo(
74
126
  () => ({
75
127
  args,
76
128
  activeConversationId,
77
129
  setActiveConversationId,
78
130
  hideable,
131
+ selectMode,
132
+ selectedIds: selectMode ? selectedIds : [],
133
+ enterSelectMode,
134
+ toggleSelected,
135
+ clearSelection,
79
136
  ...query,
80
137
  }),
81
- [args, activeConversationId, hideable, query]
138
+ [
139
+ args,
140
+ activeConversationId,
141
+ hideable,
142
+ selectMode,
143
+ selectedIds,
144
+ enterSelectMode,
145
+ toggleSelected,
146
+ clearSelection,
147
+ query,
148
+ ]
82
149
  )
83
150
 
84
151
  return <ConversationsContext.Provider value={value}>{children}</ConversationsContext.Provider>
@@ -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
+ })
@@ -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)