@planningcenter/chat-react-native 4.5.1-qa-staging.13 → 4.5.1-qa-staging.14

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 (100) hide show
  1. package/build/components/conversation/message.d.ts.map +1 -1
  2. package/build/components/conversation/message.js +73 -64
  3. package/build/components/conversation/message.js.map +1 -1
  4. package/build/components/conversation/message_list.d.ts.map +1 -1
  5. package/build/components/conversation/message_list.js +106 -89
  6. package/build/components/conversation/message_list.js.map +1 -1
  7. package/build/components/conversation/pinned_messages_bar.d.ts +4 -0
  8. package/build/components/conversation/pinned_messages_bar.d.ts.map +1 -0
  9. package/build/components/conversation/pinned_messages_bar.js +188 -0
  10. package/build/components/conversation/pinned_messages_bar.js.map +1 -0
  11. package/build/components/conversation/pinned_tag.d.ts +5 -0
  12. package/build/components/conversation/pinned_tag.d.ts.map +1 -0
  13. package/build/components/conversation/pinned_tag.js +89 -0
  14. package/build/components/conversation/pinned_tag.js.map +1 -0
  15. package/build/hooks/use_conversation.d.ts.map +1 -1
  16. package/build/hooks/use_conversation.js +1 -1
  17. package/build/hooks/use_conversation.js.map +1 -1
  18. package/build/hooks/use_conversation_messages_jolt_events.d.ts.map +1 -1
  19. package/build/hooks/use_conversation_messages_jolt_events.js +89 -52
  20. package/build/hooks/use_conversation_messages_jolt_events.js.map +1 -1
  21. package/build/hooks/use_features.d.ts +1 -0
  22. package/build/hooks/use_features.d.ts.map +1 -1
  23. package/build/hooks/use_features.js +1 -0
  24. package/build/hooks/use_features.js.map +1 -1
  25. package/build/hooks/use_message_pin.d.ts +11 -0
  26. package/build/hooks/use_message_pin.d.ts.map +1 -0
  27. package/build/hooks/use_message_pin.js +189 -0
  28. package/build/hooks/use_message_pin.js.map +1 -0
  29. package/build/hooks/use_pinned_messages.d.ts +8 -0
  30. package/build/hooks/use_pinned_messages.d.ts.map +1 -0
  31. package/build/hooks/use_pinned_messages.js +70 -0
  32. package/build/hooks/use_pinned_messages.js.map +1 -0
  33. package/build/navigation/index.d.ts +5 -0
  34. package/build/navigation/index.d.ts.map +1 -1
  35. package/build/navigation/index.js +5 -0
  36. package/build/navigation/index.js.map +1 -1
  37. package/build/screens/conversation/pinned_messages_screen.d.ts +7 -0
  38. package/build/screens/conversation/pinned_messages_screen.d.ts.map +1 -0
  39. package/build/screens/conversation/pinned_messages_screen.js +372 -0
  40. package/build/screens/conversation/pinned_messages_screen.js.map +1 -0
  41. package/build/screens/conversation_screen.d.ts.map +1 -1
  42. package/build/screens/conversation_screen.js +102 -88
  43. package/build/screens/conversation_screen.js.map +1 -1
  44. package/build/screens/message_actions_screen.d.ts.map +1 -1
  45. package/build/screens/message_actions_screen.js +135 -57
  46. package/build/screens/message_actions_screen.js.map +1 -1
  47. package/build/types/jolt_events/index.d.ts +4 -2
  48. package/build/types/jolt_events/index.d.ts.map +1 -1
  49. package/build/types/jolt_events/index.js.map +1 -1
  50. package/build/types/jolt_events/pin_events.d.ts +19 -0
  51. package/build/types/jolt_events/pin_events.d.ts.map +1 -0
  52. package/build/types/jolt_events/pin_events.js +2 -0
  53. package/build/types/jolt_events/pin_events.js.map +1 -0
  54. package/build/types/resources/member_ability.d.ts +1 -0
  55. package/build/types/resources/member_ability.d.ts.map +1 -1
  56. package/build/types/resources/member_ability.js.map +1 -1
  57. package/build/types/resources/message.d.ts +2 -0
  58. package/build/types/resources/message.d.ts.map +1 -1
  59. package/build/types/resources/message.js.map +1 -1
  60. package/build/utils/cache/messages_cache.d.ts +1 -0
  61. package/build/utils/cache/messages_cache.d.ts.map +1 -1
  62. package/build/utils/cache/messages_cache.js +19 -0
  63. package/build/utils/cache/messages_cache.js.map +1 -1
  64. package/build/utils/pinned_message_preview.d.ts +3 -0
  65. package/build/utils/pinned_message_preview.d.ts.map +1 -0
  66. package/build/utils/pinned_message_preview.js +7 -0
  67. package/build/utils/pinned_message_preview.js.map +1 -0
  68. package/build/utils/request/get_pinned_messages.d.ts +18 -0
  69. package/build/utils/request/get_pinned_messages.d.ts.map +1 -0
  70. package/build/utils/request/get_pinned_messages.js +18 -0
  71. package/build/utils/request/get_pinned_messages.js.map +1 -0
  72. package/build/utils/request/messages_data_options.d.ts.map +1 -1
  73. package/build/utils/request/messages_data_options.js +1 -1
  74. package/build/utils/request/messages_data_options.js.map +1 -1
  75. package/package.json +3 -3
  76. package/src/__tests__/hooks/use_message_pin.test.tsx +107 -0
  77. package/src/__tests__/hooks/use_pinned_messages.test.tsx +46 -0
  78. package/src/__tests__/utils/update_cache_with_pin.test.ts +54 -0
  79. package/src/components/conversation/__tests__/pinned_messages_bar.test.tsx +62 -0
  80. package/src/components/conversation/message.tsx +9 -1
  81. package/src/components/conversation/message_list.tsx +17 -4
  82. package/src/components/conversation/pinned_messages_bar.tsx +64 -0
  83. package/src/components/conversation/pinned_tag.tsx +32 -0
  84. package/src/hooks/use_conversation.ts +1 -0
  85. package/src/hooks/use_conversation_messages_jolt_events.ts +19 -1
  86. package/src/hooks/use_features.ts +1 -0
  87. package/src/hooks/use_message_pin.ts +86 -0
  88. package/src/hooks/use_pinned_messages.ts +16 -0
  89. package/src/navigation/index.tsx +8 -0
  90. package/src/screens/conversation/pinned_messages_screen.tsx +155 -0
  91. package/src/screens/conversation_screen.tsx +3 -0
  92. package/src/screens/message_actions_screen.tsx +38 -0
  93. package/src/types/jolt_events/index.ts +4 -1
  94. package/src/types/jolt_events/pin_events.ts +20 -0
  95. package/src/types/resources/member_ability.ts +1 -0
  96. package/src/types/resources/message.ts +2 -0
  97. package/src/utils/cache/messages_cache.ts +22 -0
  98. package/src/utils/pinned_message_preview.ts +9 -0
  99. package/src/utils/request/get_pinned_messages.ts +19 -0
  100. package/src/utils/request/messages_data_options.ts +2 -0
@@ -0,0 +1,107 @@
1
+ import { QueryClientProvider } from '@tanstack/react-query'
2
+ import { act, renderHook, waitFor } 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 * as useApiClientModule from '../../hooks/use_api_client'
7
+ import { useMessagePin } from '../../hooks/use_message_pin'
8
+ import { ApiCollection, MessageResource } from '../../types'
9
+ import { getMessagesQueryKey } from '../../utils/request/get_messages'
10
+ import { getPinnedMessagesQueryKey } from '../../utils/request/get_pinned_messages'
11
+
12
+ const conversationId = 7
13
+ const message = {
14
+ id: 'm1',
15
+ type: 'Message',
16
+ text: 'hello',
17
+ mine: true,
18
+ reactionCounts: [{ value: 'heart', count: 1 }],
19
+ pinnedAt: null,
20
+ } as unknown as MessageResource
21
+
22
+ const post = jest.fn()
23
+ jest.spyOn(useApiClientModule, 'useApiClient').mockReturnValue({ chat: { post } } as any)
24
+ const alertSpy = jest.spyOn(Alert, 'alert').mockImplementation(() => {})
25
+
26
+ const setup = () => {
27
+ const queryClient = buildTestQueryClient({ defaultOptions: { queries: { gcTime: Infinity } } })
28
+ queryClient.setQueryData(getMessagesQueryKey({ conversation_id: conversationId }), {
29
+ pages: [{ data: [message], links: {}, meta: {} } as ApiCollection<MessageResource>],
30
+ pageParams: [{}],
31
+ })
32
+ const invalidate = jest.spyOn(queryClient, 'invalidateQueries')
33
+ const wrapper = ({ children }: { children: React.ReactNode }) => (
34
+ <QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
35
+ )
36
+ const { result } = renderHook(() => useMessagePin({ conversation_id: conversationId, message }), {
37
+ wrapper,
38
+ })
39
+ const cachedMessage = () =>
40
+ queryClient.getQueryData<{ pages: ApiCollection<MessageResource>[] }>(
41
+ getMessagesQueryKey({ conversation_id: conversationId })
42
+ )?.pages[0].data[0]
43
+
44
+ return { result, invalidate, cachedMessage }
45
+ }
46
+
47
+ beforeEach(() => {
48
+ post.mockReset()
49
+ alertSpy.mockClear()
50
+ })
51
+
52
+ describe('useMessagePin', () => {
53
+ it('pins, marks the cached message, keeps its reactions, and refreshes the pinned list', async () => {
54
+ post.mockResolvedValue({
55
+ data: { ...message, reactionCounts: [], pinnedAt: '2026-01-02T00:00:00Z' },
56
+ })
57
+ const { result, invalidate, cachedMessage } = setup()
58
+
59
+ act(() => result.current.pin())
60
+
61
+ await waitFor(() => expect(cachedMessage()?.pinnedAt).toBe('2026-01-02T00:00:00Z'))
62
+ expect(post).toHaveBeenCalledWith(
63
+ expect.objectContaining({ url: `/me/conversations/${conversationId}/messages/m1/pin` })
64
+ )
65
+ expect(cachedMessage()?.reactionCounts).toEqual(message.reactionCounts)
66
+ expect(invalidate).toHaveBeenCalledWith({
67
+ queryKey: getPinnedMessagesQueryKey({ conversation_id: conversationId }),
68
+ })
69
+ })
70
+
71
+ it('unpins and clears the cached pin', async () => {
72
+ post.mockResolvedValue({ data: { ...message, pinnedAt: null } })
73
+ const { result, cachedMessage } = setup()
74
+
75
+ act(() => result.current.unpin())
76
+
77
+ await waitFor(() => expect(post).toHaveBeenCalled())
78
+ await waitFor(() => expect(result.current.isUnpinning).toBe(false))
79
+ expect(post).toHaveBeenCalledWith(
80
+ expect.objectContaining({ url: `/me/conversations/${conversationId}/messages/m1/unpin` })
81
+ )
82
+ expect(cachedMessage()?.pinnedAt).toBeNull()
83
+ })
84
+
85
+ it("shows the server's reason when the pin is refused", async () => {
86
+ const limitMessage = 'This conversation already has the maximum of 50 pinned messages'
87
+ post.mockRejectedValue({ errors: [{ detail: limitMessage }] })
88
+ const { result, cachedMessage } = setup()
89
+
90
+ act(() => result.current.pin())
91
+
92
+ await waitFor(() => expect(alertSpy).toHaveBeenCalledWith('Oops', limitMessage))
93
+ expect(cachedMessage()?.pinnedAt).toBeNull()
94
+ })
95
+
96
+ it('alerts and leaves the cache alone when pinning fails', async () => {
97
+ post.mockRejectedValue(new Error('nope'))
98
+ const { result, cachedMessage } = setup()
99
+
100
+ act(() => result.current.pin())
101
+
102
+ await waitFor(() =>
103
+ expect(alertSpy).toHaveBeenCalledWith('Oops', expect.stringContaining('pin'))
104
+ )
105
+ expect(cachedMessage()?.pinnedAt).toBeNull()
106
+ })
107
+ })
@@ -0,0 +1,46 @@
1
+ import { QueryClientProvider } from '@tanstack/react-query'
2
+ import { renderHook, waitFor } from '@testing-library/react-native'
3
+ import React from 'react'
4
+ import { buildTestQueryClient } from '../../__utils__/query_client'
5
+ import { ChatContext, ChatContextValue } from '../../contexts/chat_context'
6
+ import { ApiClient, useApiClient } from '../../hooks/use_api_client'
7
+ import { usePinnedMessages } from '../../hooks/use_pinned_messages'
8
+ import { Session } from '../../utils'
9
+
10
+ jest.mock('../../hooks/use_api_client')
11
+ jest.mock('../../hooks/use_features', () => ({
12
+ ...jest.requireActual('../../hooks/use_features'),
13
+ useFeatures: () => ({ featureEnabled: () => true }),
14
+ }))
15
+
16
+ const mockedUseApiClient = useApiClient as jest.MockedFunction<typeof useApiClient>
17
+ const session = new Session({ token: { access_token: 'a-real-token' } })
18
+
19
+ describe('usePinnedMessages', () => {
20
+ const get = jest.fn()
21
+
22
+ beforeEach(() => {
23
+ get.mockReset().mockResolvedValue({ data: [], links: {}, meta: {} })
24
+ mockedUseApiClient.mockReturnValue({ chat: { get } } as unknown as ApiClient)
25
+ })
26
+
27
+ it('refetches the pinned list each time the conversation mounts', async () => {
28
+ const queryClient = buildTestQueryClient({ defaultOptions: { queries: { gcTime: Infinity } } })
29
+ const wrapper = ({ children }: { children: React.ReactNode }) => (
30
+ <QueryClientProvider client={queryClient}>
31
+ <ChatContext.Provider value={{ session } as unknown as ChatContextValue}>
32
+ {children}
33
+ </ChatContext.Provider>
34
+ </QueryClientProvider>
35
+ )
36
+ const render = () => renderHook(() => usePinnedMessages({ conversation_id: 7 }), { wrapper })
37
+
38
+ const first = render()
39
+ await waitFor(() => expect(get).toHaveBeenCalledTimes(1))
40
+ first.unmount()
41
+
42
+ const second = render()
43
+ await waitFor(() => expect(get).toHaveBeenCalledTimes(2))
44
+ second.unmount()
45
+ })
46
+ })
@@ -0,0 +1,54 @@
1
+ import { InfiniteData, QueryClient } from '@tanstack/react-query'
2
+ import { buildTestQueryClient } from '../../__utils__/query_client'
3
+ import { ApiCollection, MessageResource } from '../../types'
4
+ import { getThreadedMessagesQueryKey, updateCacheWithPin } from '../../utils/cache/messages_cache'
5
+ import { getMessagesQueryKey } from '../../utils/request/get_messages'
6
+
7
+ type Pages = InfiniteData<ApiCollection<MessageResource>>
8
+
9
+ const message = (id: string): MessageResource =>
10
+ ({
11
+ id,
12
+ type: 'Message',
13
+ text: id,
14
+ reactionCounts: [],
15
+ pinnedAt: null,
16
+ }) as unknown as MessageResource
17
+
18
+ const pages = (...ids: string[]): Pages => ({
19
+ pages: [
20
+ { data: ids.map(message), links: {}, meta: { count: ids.length, totalCount: ids.length } },
21
+ ],
22
+ pageParams: [{}],
23
+ })
24
+
25
+ const cachedPinnedAt = (client: QueryClient, key: unknown[], id: string) =>
26
+ client.getQueryData<Pages>(key)?.pages[0].data.find(m => m.id === id)?.pinnedAt
27
+
28
+ describe('updateCacheWithPin', () => {
29
+ const conversationId = 7
30
+ const listKey = getMessagesQueryKey({ conversation_id: conversationId })
31
+ const threadKey = getThreadedMessagesQueryKey(conversationId, 'root')
32
+
33
+ it('marks only the pinned message in the conversation list', () => {
34
+ const client = buildTestQueryClient()
35
+ client.setQueryData(listKey, pages('a', 'b'))
36
+
37
+ updateCacheWithPin(client, conversationId, 'a', '2026-01-02T00:00:00Z')
38
+
39
+ expect(cachedPinnedAt(client, listKey, 'a')).toBe('2026-01-02T00:00:00Z')
40
+ expect(cachedPinnedAt(client, listKey, 'b')).toBeNull()
41
+ })
42
+
43
+ it('clears the pin in the thread cache too when a reply root is given', () => {
44
+ const client = buildTestQueryClient()
45
+ client.setQueryData(listKey, pages('a'))
46
+ client.setQueryData(threadKey, pages('a'))
47
+ updateCacheWithPin(client, conversationId, 'a', '2026-01-02T00:00:00Z', 'root')
48
+
49
+ updateCacheWithPin(client, conversationId, 'a', null, 'root')
50
+
51
+ expect(cachedPinnedAt(client, listKey, 'a')).toBeNull()
52
+ expect(cachedPinnedAt(client, threadKey, 'a')).toBeNull()
53
+ })
54
+ })
@@ -0,0 +1,62 @@
1
+ import { DefaultTheme, ThemeProvider } from '@react-navigation/native'
2
+ import { fireEvent, render, screen } from '@testing-library/react-native'
3
+ import React from 'react'
4
+ import { usePinnedMessages } from '../../../hooks/use_pinned_messages'
5
+ import { MessageResource } from '../../../types'
6
+ import { PinnedMessagesBar } from '../pinned_messages_bar'
7
+
8
+ const mockNavigate = jest.fn()
9
+ jest.mock('@react-navigation/native', () => ({
10
+ ...jest.requireActual('@react-navigation/native'),
11
+ useNavigation: () => ({ navigate: mockNavigate }),
12
+ }))
13
+ jest.mock('../../../hooks/use_pinned_messages', () => ({ usePinnedMessages: jest.fn() }))
14
+
15
+ const message = (id: string, text: string | null, attachments = 0) =>
16
+ ({
17
+ id,
18
+ type: 'Message',
19
+ text,
20
+ attachments: Array.from({ length: attachments }, (_, i) => ({ id: `${id}-${i}` })),
21
+ reactionCounts: [],
22
+ pinnedAt: '2026-01-02T00:00:00Z',
23
+ }) as unknown as MessageResource
24
+
25
+ const Wrapper = ({ children }: { children: React.ReactNode }) => (
26
+ <ThemeProvider value={DefaultTheme}>{children}</ThemeProvider>
27
+ )
28
+
29
+ const mount = (pinnedMessages: MessageResource[]) => {
30
+ jest.mocked(usePinnedMessages).mockReturnValue({ pinnedMessages, isLoading: false })
31
+ return render(<PinnedMessagesBar conversationId={7} />, { wrapper: Wrapper })
32
+ }
33
+
34
+ describe('PinnedMessagesBar', () => {
35
+ it('renders nothing when nothing is pinned', () => {
36
+ mount([])
37
+
38
+ expect(screen.queryByTestId('pinned-messages-bar')).toBeNull()
39
+ })
40
+
41
+ it('shows the count and previews the newest pin', () => {
42
+ mount([message('2', 'Group meets at 6 PM'), message('1', 'Older pin')])
43
+
44
+ expect(screen.getByText('Pinned · 2 items')).toBeTruthy()
45
+ expect(screen.getByText('Group meets at 6 PM')).toBeTruthy()
46
+ expect(screen.queryByText('Older pin')).toBeNull()
47
+ })
48
+
49
+ it('describes an attachment-only pin', () => {
50
+ mount([message('2', null, 2)])
51
+
52
+ expect(screen.getByText('2 attachments')).toBeTruthy()
53
+ })
54
+
55
+ it('opens the pinned list for the conversation', () => {
56
+ mount([message('2', 'Group meets at 6 PM')])
57
+
58
+ fireEvent.press(screen.getByTestId('pinned-messages-bar'))
59
+
60
+ expect(mockNavigate).toHaveBeenCalledWith('PinnedMessages', { conversation_id: 7 })
61
+ })
62
+ })
@@ -37,6 +37,7 @@ import { ComponentErrorBoundary } from '../page/component_error_boundary'
37
37
  import { MessageAttachments } from './message_attachments'
38
38
  import { MessageMarkdown } from './message_markdown'
39
39
  import { MessageReadReceipts } from './message_read_receipts'
40
+ import { PinnedTag } from './pinned_tag'
40
41
  import { TheirReplyConnector, MyReplyConnector, AVATAR_CONNECTOR_SPACING } from './reply_connectors'
41
42
 
42
43
  /** Message
@@ -114,13 +115,14 @@ export const Message = memo(function MessageRow({
114
115
 
115
116
  const messageIsReplyLabel = replyToReplyRootMessage ? 'Reply' : ''
116
117
  const attachmentLabel = some(attachments) ? pluralize(attachments.length, 'attachment') : ''
118
+ const pinnedLabel = message.pinnedAt ? 'Pinned' : ''
117
119
  const replyCountLabel = isReplyRootMessage ? replyCountText : ''
118
120
  const saveStatusLabel = error
119
121
  ? `Failed to ${isPersisted ? 'edit' : 'send'}`
120
122
  : pending
121
123
  ? messagePendingLabel
122
124
  : ''
123
- const accessibilityLabel = `${author?.name || ''} ${messageIsReplyLabel} ${attachmentLabel} ${
125
+ const accessibilityLabel = `${author?.name || ''} ${messageIsReplyLabel} ${pinnedLabel} ${attachmentLabel} ${
124
126
  messageText || ''
125
127
  } ${saveStatusLabel} ${timestamp} ${replyCountLabel}`
126
128
 
@@ -256,6 +258,9 @@ export const Message = memo(function MessageRow({
256
258
  {author.name}
257
259
  </Text>
258
260
  )}
261
+ {!!message.pinnedAt && !isDeletedReplyRootMessage && (
262
+ <PinnedTag style={styles.pinnedTag} />
263
+ )}
259
264
  <View
260
265
  style={styles.messageBubble}
261
266
  onLayout={e => setMessageBubbleHeight(e.nativeEvent.layout.height)}
@@ -410,6 +415,9 @@ const useMessageStyles = (mine: boolean, isDeleting: boolean) => {
410
415
  messageReplyCount: {
411
416
  alignSelf: mine ? 'flex-end' : 'flex-start',
412
417
  },
418
+ pinnedTag: {
419
+ alignSelf: mine ? 'flex-end' : 'flex-start',
420
+ },
413
421
  messageMeta: {
414
422
  flexDirection: 'row',
415
423
  alignItems: 'center',
@@ -90,10 +90,6 @@ export function MessageList({
90
90
  const flashedAnchorId = useRef<string | null>(null)
91
91
  const [highlightedMessageId, setHighlightedMessageId] = useState<string | null>(null)
92
92
 
93
- useEffect(() => {
94
- latestAnchorMessageId.current = anchorMessageId
95
- }, [anchorMessageId])
96
-
97
93
  // Row heights keep settling after the first layout (images, attachments), so we
98
94
  // re-pin on every layout pass until the reader takes over with a drag.
99
95
  const pinAnchorToBottomEdge = () => {
@@ -111,6 +107,23 @@ export function MessageList({
111
107
  })
112
108
  }
113
109
 
110
+ useEffect(() => {
111
+ const previousAnchorMessageId = latestAnchorMessageId.current
112
+ latestAnchorMessageId.current = anchorMessageId
113
+ if (!anchorMessageId || anchorMessageId === previousAnchorMessageId) return
114
+
115
+ userHasScrolled.current = false
116
+ flashedAnchorId.current = null
117
+ if (anchorIndex < 0) return
118
+
119
+ listRef.current?.scrollToIndex({
120
+ index: anchorIndex,
121
+ viewPosition: 0,
122
+ viewOffset: ANCHOR_CLEARS_JUMP_BUTTON,
123
+ animated: false,
124
+ })
125
+ }, [anchorMessageId, anchorIndex, listRef])
126
+
114
127
  const handleLayout: FlatListProps<EnrichedMessage>['onLayout'] = event => {
115
128
  onLayout?.(event)
116
129
  layoutHeight.current = event.nativeEvent.layout.height
@@ -0,0 +1,64 @@
1
+ import { PlatformPressable } from '@react-navigation/elements'
2
+ import { useNavigation } from '@react-navigation/native'
3
+ import { StyleSheet, View } from 'react-native'
4
+ import { useTheme } from '../../hooks'
5
+ import { usePinnedMessages } from '../../hooks/use_pinned_messages'
6
+ import { pinnedMessagePreview } from '../../utils/pinned_message_preview'
7
+ import { pluralize } from '../../utils/pluralize'
8
+ import { Icon, Text } from '../display'
9
+
10
+ export const PinnedMessagesBar = ({ conversationId }: { conversationId: number }) => {
11
+ const styles = useStyles()
12
+ const { colors } = useTheme()
13
+ const navigation = useNavigation()
14
+ const { pinnedMessages } = usePinnedMessages({ conversation_id: conversationId })
15
+
16
+ if (pinnedMessages.length === 0) return null
17
+
18
+ const newest = pinnedMessages[0]
19
+ const countText = pluralize(pinnedMessages.length, 'item')
20
+
21
+ return (
22
+ <PlatformPressable
23
+ testID="pinned-messages-bar"
24
+ style={styles.bar}
25
+ accessibilityRole="button"
26
+ accessibilityLabel={`Pinned, ${countText}`}
27
+ accessibilityHint="Opens the list of pinned messages"
28
+ onPress={() => navigation.navigate('PinnedMessages', { conversation_id: conversationId })}
29
+ >
30
+ <Icon name="services.pin" size={18} color={colors.interaction} />
31
+ <View style={styles.textColumn}>
32
+ <Text variant="footnote">Pinned · {countText}</Text>
33
+ <Text numberOfLines={1} style={styles.preview}>
34
+ {pinnedMessagePreview(newest)}
35
+ </Text>
36
+ </View>
37
+ <Icon name="general.rightChevron" size={14} color={colors.iconColorDefaultSecondary} />
38
+ </PlatformPressable>
39
+ )
40
+ }
41
+
42
+ const useStyles = () => {
43
+ const { colors } = useTheme()
44
+
45
+ return StyleSheet.create({
46
+ bar: {
47
+ flexDirection: 'row',
48
+ alignItems: 'center',
49
+ gap: 12,
50
+ paddingHorizontal: 16,
51
+ paddingVertical: 8,
52
+ backgroundColor: colors.statusNeutralComposedBackground,
53
+ borderBottomWidth: 1,
54
+ borderBottomColor: colors.borderColorDefaultBase,
55
+ },
56
+ textColumn: {
57
+ flex: 1,
58
+ minWidth: 0,
59
+ },
60
+ preview: {
61
+ fontWeight: '500',
62
+ },
63
+ })
64
+ }
@@ -0,0 +1,32 @@
1
+ import { StyleSheet, View, type ViewStyle } from 'react-native'
2
+ import { useTheme } from '../../hooks'
3
+ import { Icon, Text } from '../display'
4
+
5
+ export const PinnedTag = ({ style }: { style?: ViewStyle }) => {
6
+ const styles = useStyles()
7
+ const { colors } = useTheme()
8
+
9
+ return (
10
+ <View style={[styles.tag, style]} testID="pinned-tag" accessibilityLabel="Pinned">
11
+ <Icon name="services.pin" size={12} color={colors.interaction} />
12
+ <Text variant="footnote" style={styles.text}>
13
+ Pinned
14
+ </Text>
15
+ </View>
16
+ )
17
+ }
18
+
19
+ const useStyles = () => {
20
+ const { colors } = useTheme()
21
+
22
+ return StyleSheet.create({
23
+ tag: {
24
+ flexDirection: 'row',
25
+ alignItems: 'center',
26
+ gap: 4,
27
+ },
28
+ text: {
29
+ color: colors.interaction,
30
+ },
31
+ })
32
+ }
@@ -53,6 +53,7 @@ export const getConversationRequestArgs = ({ conversation_id }: { conversation_i
53
53
  'can_message_available_members',
54
54
  'can_archive',
55
55
  'can_unarchive',
56
+ 'can_pin',
56
57
  ],
57
58
  ConversationMembership: [
58
59
  'last_read_message_sort_key',
@@ -1,6 +1,6 @@
1
1
  import { InfiniteData, useQueryClient } from '@tanstack/react-query'
2
2
  import { ApiCollection, MessageResource } from '../types'
3
- import { JoltReactionEvent, JoltTypingEvent } from '../types/jolt_events'
3
+ import { JoltPinEvent, JoltReactionEvent, JoltTypingEvent } from '../types/jolt_events'
4
4
  import {
5
5
  MessageCreatedEvent,
6
6
  MessageUpdatedEvent,
@@ -11,6 +11,7 @@ import {
11
11
  updateCacheWithMessage,
12
12
  updateCacheWithIndividualMessage,
13
13
  updateCacheWithReaction,
14
+ updateCacheWithPin,
14
15
  updateCacheReplyRoots,
15
16
  getThreadedMessagesQueryKey,
16
17
  } from '../utils/cache/messages_cache'
@@ -19,6 +20,7 @@ import { transformMessageEventDataToMessageResource } from '../utils/jolt/transf
19
20
  import { completeMessageCreationTracking } from '../utils/performance_tracking'
20
21
  import { getMessageQueryKey } from '../utils/request/get_message'
21
22
  import { getMessagesRequestArgs } from '../utils/request/get_messages'
23
+ import { getPinnedMessagesQueryKey } from '../utils/request/get_pinned_messages'
22
24
  import { useApiClient } from './use_api_client'
23
25
  import { useCurrentPerson } from './use_current_person'
24
26
  import { useJoltChannel, useJoltEvent } from './use_jolt'
@@ -35,6 +37,7 @@ export function useConversationMessagesJoltEvents({ conversationId }: Props) {
35
37
  const joltChannel = useJoltChannel(`chat.conversations.${conversationId}`)
36
38
  const messagesRequestArgs = getMessagesRequestArgs({ conversation_id: conversationId })
37
39
  const messagesQueryKey = getRequestQueryKey(messagesRequestArgs)
40
+ const pinnedMessagesQueryKey = getPinnedMessagesQueryKey({ conversation_id: conversationId })
38
41
  const apiClient = useApiClient()
39
42
 
40
43
  const { addTypingEvent, removeTypingEventById, removeAllTypingEventsByAuthorId } =
@@ -102,6 +105,7 @@ export function useConversationMessagesJoltEvents({ conversationId }: Props) {
102
105
  queryClient.setQueryData<QueryData>(messagesQueryKey, prev =>
103
106
  deleteRecordInPagesData({ data: prev, record: message })
104
107
  )
108
+ queryClient.invalidateQueries({ queryKey: pinnedMessagesQueryKey })
105
109
 
106
110
  // If message has a reply_root_id, also update the threaded cache
107
111
  if (data.reply_root_id) {
@@ -128,6 +132,19 @@ export function useConversationMessagesJoltEvents({ conversationId }: Props) {
128
132
  }
129
133
  }
130
134
 
135
+ const handlePinJoltEvent = async (e: JoltPinEvent) => {
136
+ const { data } = e.data
137
+ const pinnedAt = e.event === 'pin.created' ? data.pinned_at : null
138
+ updateCacheWithPin(
139
+ queryClient,
140
+ conversationId,
141
+ data.message_sort_key,
142
+ pinnedAt,
143
+ data.reply_root_id
144
+ )
145
+ queryClient.invalidateQueries({ queryKey: pinnedMessagesQueryKey })
146
+ }
147
+
131
148
  const handleTypingEvent = async (e: JoltTypingEvent) => {
132
149
  const { data } = e.data
133
150
  addTypingEvent(data)
@@ -138,6 +155,7 @@ export function useConversationMessagesJoltEvents({ conversationId }: Props) {
138
155
  useJoltEvent(joltChannel, 'message.updated', handleMessageUpdateOrCreate)
139
156
  useJoltEvent(joltChannel, 'message.destroyed', handleMessageDeleted)
140
157
  useJoltEvent(joltChannel, 'reaction.*', handleReactionJoltEvent)
158
+ useJoltEvent(joltChannel, 'pin.*', handlePinJoltEvent)
141
159
  useJoltEvent(joltChannel, 'typing.broadcast', handleTypingEvent)
142
160
  }
143
161
 
@@ -58,6 +58,7 @@ export const availableFeatures = {
58
58
  search: 'QA_MOBILE_search',
59
59
  search_rollout: 'ROLLOUT_MOBILE_search',
60
60
  filter_dropdown: 'QA_MOBILE_filter_dropdown',
61
+ pinned_messages: 'ROLLOUT_pinned_messages',
61
62
  filter_dropdown_rollout: 'ROLLOUT_MOBILE_filter_dropdown',
62
63
  manual_archiving: 'QA_MOBILE_manual_archiving',
63
64
  manual_archiving_rollout: 'ROLLOUT_MOBILE_manual_archiving',
@@ -0,0 +1,86 @@
1
+ import { InfiniteData, useMutation, useQueryClient } from '@tanstack/react-query'
2
+ import { useCallback } from 'react'
3
+ import { Alert } from 'react-native'
4
+ import { ApiCollection, ApiResource, FailedResponse, MessageResource } from '../types'
5
+ import { mergeMessageUpdate, updateCacheWithPin } from '../utils/cache/messages_cache'
6
+ import { updateRecordInPagesData } from '../utils/cache/page_mutations'
7
+ import { Haptic } from '../utils/native_adapters'
8
+ import { getMessagesQueryKey } from '../utils/request/get_messages'
9
+ import { getPinnedMessagesQueryKey } from '../utils/request/get_pinned_messages'
10
+ import { getMessageFields } from '../utils/request/messages_data_options'
11
+ import { useApiClient } from './use_api_client'
12
+
13
+ type QueryData = InfiniteData<ApiCollection<MessageResource>>
14
+
15
+ const PIN_FAILED_MESSAGE = "We couldn't pin this message. Please try again."
16
+
17
+ function pinFailureMessage(error: unknown) {
18
+ const detail = (error as Partial<FailedResponse> | null)?.errors?.[0]?.detail
19
+ return typeof detail === 'string' && detail.trim() ? detail : PIN_FAILED_MESSAGE
20
+ }
21
+
22
+ export function useMessagePin({
23
+ conversation_id,
24
+ message,
25
+ }: {
26
+ conversation_id: number
27
+ message: MessageResource
28
+ }) {
29
+ const apiClient = useApiClient()
30
+ const queryClient = useQueryClient()
31
+ const messagesQueryKey = getMessagesQueryKey({ conversation_id })
32
+ const pinnedMessagesQueryKey = getPinnedMessagesQueryKey({ conversation_id })
33
+
34
+ const request = useCallback(
35
+ (action: 'pin' | 'unpin') =>
36
+ apiClient.chat.post<ApiResource<MessageResource>>({
37
+ url: `/me/conversations/${conversation_id}/messages/${message.id}/${action}`,
38
+ data: {
39
+ data: { type: 'Message', attributes: {} },
40
+ include: ['author', 'reaction_counts'],
41
+ fields: Object.fromEntries(
42
+ Object.entries(getMessageFields).map(([type, fields]) => [type, fields.join(',')])
43
+ ),
44
+ },
45
+ }),
46
+ [apiClient, conversation_id, message.id]
47
+ )
48
+
49
+ const applyResult = (result: ApiResource<MessageResource>, pinnedAt: string | null) => {
50
+ queryClient.setQueryData<QueryData>(messagesQueryKey, data =>
51
+ updateRecordInPagesData({
52
+ data,
53
+ record: { ...result.data, pinnedAt: result.data.pinnedAt ?? pinnedAt },
54
+ processRecord: (record, current) => mergeMessageUpdate(record, current),
55
+ })
56
+ )
57
+ if (message.replyRootId) {
58
+ updateCacheWithPin(queryClient, conversation_id, message.id, pinnedAt, message.replyRootId)
59
+ }
60
+ queryClient.invalidateQueries({ queryKey: pinnedMessagesQueryKey })
61
+ Haptic.notificationSuccess()
62
+ }
63
+
64
+ const pinMutation = useMutation({
65
+ mutationFn: () => request('pin'),
66
+ onSuccess: result => applyResult(result, result.data.pinnedAt ?? new Date().toISOString()),
67
+ onError: error => {
68
+ Alert.alert('Oops', pinFailureMessage(error))
69
+ },
70
+ })
71
+
72
+ const unpinMutation = useMutation({
73
+ mutationFn: () => request('unpin'),
74
+ onSuccess: result => applyResult(result, null),
75
+ onError: () => {
76
+ Alert.alert('Oops', "We couldn't unpin this message. Please try again.")
77
+ },
78
+ })
79
+
80
+ return {
81
+ pin: pinMutation.mutate,
82
+ unpin: unpinMutation.mutate,
83
+ isPinning: pinMutation.isPending,
84
+ isUnpinning: unpinMutation.isPending,
85
+ }
86
+ }
@@ -0,0 +1,16 @@
1
+ import { MessageResource } from '../types'
2
+ import { getPinnedMessagesRequestArgs } from '../utils/request/get_pinned_messages'
3
+ import { useApiPaginator } from './use_api'
4
+ import { availableFeatures, useFeatures } from './use_features'
5
+
6
+ export function usePinnedMessages({ conversation_id }: { conversation_id: number }) {
7
+ const { featureEnabled } = useFeatures()
8
+ const enabled = featureEnabled(availableFeatures.pinned_messages)
9
+
10
+ const { data, isLoading } = useApiPaginator<MessageResource>(
11
+ getPinnedMessagesRequestArgs({ conversation_id }),
12
+ { enabled }
13
+ )
14
+
15
+ return { pinnedMessages: enabled ? data : [], isLoading: enabled && isLoading }
16
+ }
@@ -27,6 +27,10 @@ import {
27
27
  MessageReadReceiptsScreen,
28
28
  MessageReadReceiptsScreenOptions,
29
29
  } from '../screens/conversation/message_read_receipts_screen'
30
+ import {
31
+ PinnedMessagesScreen,
32
+ PinnedMessagesScreenOptions,
33
+ } from '../screens/conversation/pinned_messages_screen'
30
34
  import { ConversationDetailsScreen } from '../screens/conversation_details_screen'
31
35
  import {
32
36
  ConversationFilterReceipientsScreenOptions,
@@ -366,6 +370,10 @@ export const ChatStack = createNativeStackNavigator({
366
370
  screen: MessageReadReceiptsScreen,
367
371
  options: MessageReadReceiptsScreenOptions,
368
372
  },
373
+ PinnedMessages: {
374
+ screen: PinnedMessagesScreen,
375
+ options: PinnedMessagesScreenOptions,
376
+ },
369
377
  BugReport: {
370
378
  screen: BugReportScreen,
371
379
  options: BugReportScreenOptions,