@planningcenter/chat-react-native 4.3.0-rc.1 → 4.3.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 (140) hide show
  1. package/build/components/conversation/message_form.d.ts +2 -1
  2. package/build/components/conversation/message_form.d.ts.map +1 -1
  3. package/build/components/conversation/message_form.js +167 -370
  4. package/build/components/conversation/message_form.js.map +1 -1
  5. package/build/components/conversation/message_list.d.ts +5 -2
  6. package/build/components/conversation/message_list.d.ts.map +1 -1
  7. package/build/components/conversation/message_list.js +187 -67
  8. package/build/components/conversation/message_list.js.map +1 -1
  9. package/build/components/conversation/missing_message.d.ts +2 -0
  10. package/build/components/conversation/missing_message.d.ts.map +1 -0
  11. package/build/components/conversation/missing_message.js +139 -0
  12. package/build/components/conversation/missing_message.js.map +1 -0
  13. package/build/components/display/conversation_avatar.d.ts +1 -2
  14. package/build/components/display/conversation_avatar.d.ts.map +1 -1
  15. package/build/components/display/conversation_avatar.js.map +1 -1
  16. package/build/hooks/groups/use_group_members_for_new_conversation.d.ts +4 -3
  17. package/build/hooks/groups/use_group_members_for_new_conversation.d.ts.map +1 -1
  18. package/build/hooks/use_conversation_messages.d.ts +14 -5
  19. package/build/hooks/use_conversation_messages.d.ts.map +1 -1
  20. package/build/hooks/use_conversation_messages.js +218 -42
  21. package/build/hooks/use_conversation_messages.js.map +1 -1
  22. package/build/hooks/use_conversation_messages_jolt_events.d.ts.map +1 -1
  23. package/build/hooks/use_conversation_messages_jolt_events.js +58 -42
  24. package/build/hooks/use_conversation_messages_jolt_events.js.map +1 -1
  25. package/build/hooks/use_features.d.ts +2 -1
  26. package/build/hooks/use_features.d.ts.map +1 -1
  27. package/build/hooks/use_features.js +2 -1
  28. package/build/hooks/use_features.js.map +1 -1
  29. package/build/hooks/use_mark_latest_message_read.d.ts +2 -1
  30. package/build/hooks/use_mark_latest_message_read.d.ts.map +1 -1
  31. package/build/hooks/use_mark_latest_message_read.js +4 -3
  32. package/build/hooks/use_mark_latest_message_read.js.map +1 -1
  33. package/build/hooks/use_read_receipts.d.ts +4 -3
  34. package/build/hooks/use_read_receipts.d.ts.map +1 -1
  35. package/build/hooks/use_search_results.d.ts +19 -0
  36. package/build/hooks/use_search_results.d.ts.map +1 -0
  37. package/build/hooks/use_search_results.js +145 -0
  38. package/build/hooks/use_search_results.js.map +1 -0
  39. package/build/hooks/use_suspense_api.d.ts +10 -6
  40. package/build/hooks/use_suspense_api.d.ts.map +1 -1
  41. package/build/hooks/use_suspense_api.js +83 -63
  42. package/build/hooks/use_suspense_api.js.map +1 -1
  43. package/build/navigation/index.d.ts +5 -0
  44. package/build/navigation/index.d.ts.map +1 -1
  45. package/build/navigation/index.js +5 -0
  46. package/build/navigation/index.js.map +1 -1
  47. package/build/screens/conversation_screen.d.ts +1 -0
  48. package/build/screens/conversation_screen.d.ts.map +1 -1
  49. package/build/screens/conversation_screen.js +305 -203
  50. package/build/screens/conversation_screen.js.map +1 -1
  51. package/build/screens/conversations/components/search_list_header_component.d.ts.map +1 -1
  52. package/build/screens/conversations/components/search_list_header_component.js +159 -133
  53. package/build/screens/conversations/components/search_list_header_component.js.map +1 -1
  54. package/build/screens/message_actions_screen.d.ts.map +1 -1
  55. package/build/screens/message_actions_screen.js +103 -92
  56. package/build/screens/message_actions_screen.js.map +1 -1
  57. package/build/screens/notification_settings/hooks/groups.d.ts +4 -3
  58. package/build/screens/notification_settings/hooks/groups.d.ts.map +1 -1
  59. package/build/screens/search/components/search_blank_states.d.ts +7 -0
  60. package/build/screens/search/components/search_blank_states.d.ts.map +1 -0
  61. package/build/screens/search/components/search_blank_states.js +72 -0
  62. package/build/screens/search/components/search_blank_states.js.map +1 -0
  63. package/build/screens/search/components/search_field.d.ts +7 -0
  64. package/build/screens/search/components/search_field.d.ts.map +1 -0
  65. package/build/screens/search/components/search_field.js +152 -0
  66. package/build/screens/search/components/search_field.js.map +1 -0
  67. package/build/screens/search/search_screen.d.ts +5 -0
  68. package/build/screens/search/search_screen.d.ts.map +1 -0
  69. package/build/screens/search/search_screen.js +59 -0
  70. package/build/screens/search/search_screen.js.map +1 -0
  71. package/build/types/api_primitives.d.ts +1 -0
  72. package/build/types/api_primitives.d.ts.map +1 -1
  73. package/build/types/api_primitives.js.map +1 -1
  74. package/build/types/resources/conversation.d.ts +1 -0
  75. package/build/types/resources/conversation.d.ts.map +1 -1
  76. package/build/types/resources/conversation.js.map +1 -1
  77. package/build/types/resources/index.d.ts +1 -0
  78. package/build/types/resources/index.d.ts.map +1 -1
  79. package/build/types/resources/index.js +1 -0
  80. package/build/types/resources/index.js.map +1 -1
  81. package/build/types/resources/search_result.d.ts +29 -0
  82. package/build/types/resources/search_result.d.ts.map +1 -0
  83. package/build/types/resources/search_result.js +2 -0
  84. package/build/types/resources/search_result.js.map +1 -0
  85. package/build/utils/cache/messages_cache.d.ts +1 -0
  86. package/build/utils/cache/messages_cache.d.ts.map +1 -1
  87. package/build/utils/cache/messages_cache.js +37 -1
  88. package/build/utils/cache/messages_cache.js.map +1 -1
  89. package/build/utils/cache/messages_window.d.ts +11 -0
  90. package/build/utils/cache/messages_window.d.ts.map +1 -0
  91. package/build/utils/cache/messages_window.js +51 -0
  92. package/build/utils/cache/messages_window.js.map +1 -0
  93. package/build/utils/client/types.d.ts +1 -0
  94. package/build/utils/client/types.d.ts.map +1 -1
  95. package/build/utils/client/types.js.map +1 -1
  96. package/build/utils/request/get_search_results.d.ts +13 -0
  97. package/build/utils/request/get_search_results.d.ts.map +1 -0
  98. package/build/utils/request/get_search_results.js +20 -0
  99. package/build/utils/request/get_search_results.js.map +1 -0
  100. package/package.json +2 -2
  101. package/src/__tests__/hooks/use_features.test.ts +10 -2
  102. package/src/__utils__/query_client.ts +3 -0
  103. package/src/components/conversation/message_form.tsx +31 -3
  104. package/src/components/conversation/message_list.tsx +88 -4
  105. package/src/components/conversation/missing_message.tsx +66 -0
  106. package/src/components/display/conversation_avatar.tsx +1 -10
  107. package/src/hooks/__tests__/use_conversation_messages.test.tsx +333 -0
  108. package/src/hooks/__tests__/use_conversation_messages_jolt_events.test.tsx +87 -0
  109. package/src/hooks/__tests__/use_mark_latest_message_read.test.tsx +33 -0
  110. package/src/hooks/__tests__/use_message_create_or_update.test.tsx +2 -7
  111. package/src/hooks/__tests__/use_search_results.test.tsx +76 -0
  112. package/src/hooks/use_conversation_messages.ts +103 -17
  113. package/src/hooks/use_conversation_messages_jolt_events.ts +12 -2
  114. package/src/hooks/use_features.ts +3 -2
  115. package/src/hooks/use_mark_latest_message_read.ts +4 -3
  116. package/src/hooks/use_search_results.ts +77 -0
  117. package/src/hooks/use_suspense_api.ts +14 -6
  118. package/src/navigation/index.tsx +5 -0
  119. package/src/screens/conversation_screen.tsx +62 -13
  120. package/src/screens/conversations/components/__tests__/search_list_header_component.test.tsx +62 -0
  121. package/src/screens/conversations/components/search_list_header_component.tsx +11 -0
  122. package/src/screens/message_actions_screen.tsx +12 -1
  123. package/src/screens/search/components/__tests__/search_blank_states.test.tsx +20 -0
  124. package/src/screens/search/components/__tests__/search_field.test.tsx +29 -0
  125. package/src/screens/search/components/search_blank_states.tsx +34 -0
  126. package/src/screens/search/components/search_field.tsx +81 -0
  127. package/src/screens/search/search_screen.tsx +41 -0
  128. package/src/types/api_primitives.ts +1 -0
  129. package/src/types/resources/conversation.ts +9 -0
  130. package/src/types/resources/index.ts +1 -0
  131. package/src/types/resources/search_result.ts +32 -0
  132. package/src/utils/__tests__/get_search_results.test.ts +24 -0
  133. package/src/utils/cache/__tests__/messages_cache.test.ts +2 -1
  134. package/src/utils/cache/__tests__/messages_cache_deletion.test.ts +97 -0
  135. package/src/utils/cache/__tests__/messages_cache_reply_roots.test.ts +3 -2
  136. package/src/utils/cache/__tests__/messages_window.test.ts +78 -0
  137. package/src/utils/cache/messages_cache.ts +45 -1
  138. package/src/utils/cache/messages_window.ts +55 -0
  139. package/src/utils/client/types.ts +1 -0
  140. package/src/utils/request/get_search_results.ts +23 -0
@@ -0,0 +1,33 @@
1
+ import { renderHook } from '@testing-library/react-native'
2
+ import type { ConversationResource } from '../../types'
3
+ import { useMarkLatestMessageRead } from '../use_mark_latest_message_read'
4
+
5
+ const mockMarkRead = jest.fn()
6
+ jest.mock('../use_conversations_actions', () => ({
7
+ useConversationsMarkRead: () => ({ markRead: mockMarkRead }),
8
+ }))
9
+ jest.mock('../use_app_state', () => ({ useAppState: () => 'active' }))
10
+
11
+ const conversation = { id: 7, unreadCount: 3 } as ConversationResource
12
+
13
+ beforeEach(() => mockMarkRead.mockReset())
14
+
15
+ describe('useMarkLatestMessageRead', () => {
16
+ it('marks the conversation read on open', () => {
17
+ renderHook(() => useMarkLatestMessageRead({ conversation, messages: [] }))
18
+
19
+ expect(mockMarkRead).toHaveBeenCalledTimes(1)
20
+ })
21
+
22
+ it('waits while disabled and marks read once enabled', () => {
23
+ const { rerender } = renderHook<void, { enabled: boolean }>(
24
+ ({ enabled }) => useMarkLatestMessageRead({ conversation, messages: [], enabled }),
25
+ { initialProps: { enabled: false } }
26
+ )
27
+ expect(mockMarkRead).not.toHaveBeenCalled()
28
+
29
+ rerender({ enabled: true })
30
+
31
+ expect(mockMarkRead).toHaveBeenCalledTimes(1)
32
+ })
33
+ })
@@ -7,13 +7,8 @@ import { getMessagesQueryKey } from '../../utils/request/get_messages'
7
7
  import { useMessageCreateOrUpdate } from '../use_message_create_or_update'
8
8
 
9
9
  jest.mock('../../contexts/api_provider', () => {
10
- const { QueryClient } = require('@tanstack/react-query')
11
- // gcTime 0 so nothing outlives the test and keeps jest from exiting
12
- return {
13
- chatQueryClient: new QueryClient({
14
- defaultOptions: { queries: { gcTime: 0 }, mutations: { gcTime: 0 } },
15
- }),
16
- }
10
+ const { buildTestQueryClient } = require('../../__utils__/query_client')
11
+ return { chatQueryClient: buildTestQueryClient() }
17
12
  })
18
13
 
19
14
  const mockPost = jest.fn()
@@ -0,0 +1,76 @@
1
+ import { QueryClientProvider } from '@tanstack/react-query'
2
+ import { act, renderHook, waitFor } from '@testing-library/react-native'
3
+ import React from 'react'
4
+ import { buildTestQueryClient } from '../../__utils__/query_client'
5
+ import type { SearchResultResource } from '../../types/resources/search_result'
6
+ import { NO_FAILED_TYPES, useSearchResults } from '../use_search_results'
7
+
8
+ const mockGet = jest.fn()
9
+ jest.mock('../use_api_client', () => ({ useApiClient: () => ({ chat: { get: mockGet } }) }))
10
+
11
+ const result = (type: SearchResultResource['type'], id: string) =>
12
+ ({ type, id, title: `${type} ${id}`, url: `/${type}s/${id}` }) as SearchResultResource
13
+
14
+ const page = (data: SearchResultResource[], meta: Record<string, unknown> = {}) => ({
15
+ data,
16
+ links: {},
17
+ meta: { count: data.length, totalCount: data.length, ...meta },
18
+ })
19
+
20
+ const wrapper = ({ children }: { children: React.ReactNode }) => (
21
+ <QueryClientProvider client={buildTestQueryClient()}>{children}</QueryClientProvider>
22
+ )
23
+
24
+ beforeEach(() => mockGet.mockReset())
25
+
26
+ describe('useSearchResults', () => {
27
+ it('flattens pages into one list without repeating a result', async () => {
28
+ mockGet
29
+ .mockResolvedValueOnce(
30
+ page([result('conversation', '1'), result('message', '1')], { next: { offset: '20' } })
31
+ )
32
+ .mockResolvedValueOnce(page([result('message', '1'), result('message', '2')]))
33
+
34
+ const { result: hook } = renderHook(() => useSearchResults('potluck'), { wrapper })
35
+ await waitFor(() => expect(hook.current.hasNextPage).toBe(true))
36
+
37
+ act(() => {
38
+ hook.current.loadMore()
39
+ })
40
+ await waitFor(() => expect(hook.current.hasNextPage).toBe(false))
41
+
42
+ expect(hook.current.results.map(({ type, id }) => `${type}:${id}`)).toEqual([
43
+ 'conversation:1',
44
+ 'message:1',
45
+ 'message:2',
46
+ ])
47
+ expect(mockGet).toHaveBeenLastCalledWith({
48
+ url: '/search_results',
49
+ data: expect.objectContaining({ q: 'potluck', offset: 20 }),
50
+ })
51
+ })
52
+
53
+ it('reads failedTypes from the first page', async () => {
54
+ mockGet
55
+ .mockResolvedValueOnce(page([], { failedTypes: ['message'], next: { offset: '20' } }))
56
+ .mockResolvedValueOnce(page([], { failedTypes: ['conversation'] }))
57
+
58
+ const { result: hook } = renderHook(() => useSearchResults('potluck'), { wrapper })
59
+ await waitFor(() => expect(hook.current.hasNextPage).toBe(true))
60
+
61
+ act(() => {
62
+ hook.current.loadMore()
63
+ })
64
+ await waitFor(() => expect(hook.current.hasNextPage).toBe(false))
65
+
66
+ expect(hook.current.failedTypes).toEqual(['message'])
67
+ })
68
+
69
+ it('makes no request for an empty term', () => {
70
+ const { result: hook } = renderHook(() => useSearchResults(''), { wrapper })
71
+
72
+ expect(mockGet).not.toHaveBeenCalled()
73
+ expect(hook.current.results).toEqual([])
74
+ expect(hook.current.failedTypes).toBe(NO_FAILED_TYPES)
75
+ })
76
+ })
@@ -1,33 +1,119 @@
1
- import { useMemo } from 'react'
2
- import { MessageResource } from '../types'
1
+ import { useQueryClient } from '@tanstack/react-query'
2
+ import { useEffect, useMemo } from 'react'
3
+ import { chatQueryClient } from '../contexts/api_provider'
4
+ import { ApiCollection, MessageResource } from '../types'
5
+ import {
6
+ anchoredPageParam,
7
+ isBehindLiveEdge,
8
+ livePageParam,
9
+ markLiveIfCaughtUp,
10
+ MessagesWindow,
11
+ newerPageParam,
12
+ newestFirst,
13
+ } from '../utils/cache/messages_window'
3
14
  import { replaceEqualById } from '../utils/replace_equal_by_id'
4
15
  import { getMessagesQueryKey, getMessagesRequestArgs } from '../utils/request/get_messages'
16
+ import { useApiClient } from './use_api_client'
5
17
  import { SuspensePaginatorOptions, useSuspensePaginator } from './use_suspense_api'
6
18
 
19
+ type WindowOptions = { conversation_id: number; reply_root_id?: string | null }
20
+ type Options = WindowOptions & { anchor?: string | null }
21
+
7
22
  export const useConversationMessages = (
8
- { conversation_id, reply_root_id }: { conversation_id: number; reply_root_id?: string | null },
23
+ { conversation_id, reply_root_id, anchor }: Options,
9
24
  opts?: SuspensePaginatorOptions
10
25
  ) => {
11
- const { data, refetch, isRefetching, fetchNextPage, hasNextPage } =
12
- useSuspensePaginator<MessageResource>(
13
- getMessagesRequestArgs({ conversation_id, reply_root_id }),
14
- {
15
- structuralSharing: replaceEqualById,
16
- ...opts,
17
- }
18
- )
26
+ const queryClient = useQueryClient()
27
+ const apiClient = useApiClient()
19
28
  const queryKey = getMessagesQueryKey({ conversation_id, reply_root_id })
29
+ const requestArgs = getMessagesRequestArgs({ conversation_id, reply_root_id })
30
+ const {
31
+ data,
32
+ infiniteData,
33
+ refetch,
34
+ isRefetching,
35
+ fetchNextPage,
36
+ fetchPreviousPage,
37
+ hasNextPage,
38
+ hasPreviousPage,
39
+ } = useSuspensePaginator<MessageResource>(requestArgs, {
40
+ structuralSharing: replaceEqualById,
41
+ initialPageParam: anchor ? anchoredPageParam(anchor) : livePageParam,
42
+ getPreviousPageParam: newerPageParam,
43
+ transformPage: newestFirst,
44
+ ...opts,
45
+ })
46
+ const behind = isBehindLiveEdge(infiniteData)
47
+
48
+ const fetchOlder = () => fetchNextPage({ cancelRefetch: false })
49
+
50
+ const fetchNewer = async () => {
51
+ if (!hasPreviousPage) return
52
+
53
+ await fetchPreviousPage({ cancelRefetch: false })
54
+ }
55
+
56
+ const fetchLiveWindow = async () => {
57
+ if (!behind) return
58
+
59
+ const page = await apiClient.chat.get<ApiCollection<MessageResource>>(requestArgs)
60
+ await queryClient.cancelQueries({ queryKey, exact: true })
61
+ queryClient.setQueryData<MessagesWindow>(queryKey, {
62
+ pages: [page],
63
+ pageParams: [livePageParam],
64
+ })
65
+ }
66
+
20
67
  const messages = useMemo(
21
68
  () =>
22
69
  data
23
- .filter(
24
- message =>
25
- (!message.deletedAt || message.replyRootId) &&
26
- (message.attachments?.length || message.text?.length)
27
- )
70
+ .filter(message => message.deletedAt || message.attachments?.length || message.text?.length)
28
71
  .sort((a, b) => -a.id.localeCompare(b.id)),
29
72
  [data]
30
73
  )
31
74
 
32
- return { messages, refetch, isRefetching, fetchNextPage, hasNextPage, queryKey }
75
+ // Once nothing newer remains, the top of the window is the live edge. Without this,
76
+ // a refetch would replay from the anchor and drop rows Jolt has added since.
77
+ useEffect(() => {
78
+ const settled = markLiveIfCaughtUp(infiniteData)
79
+
80
+ if (settled !== infiniteData) {
81
+ queryClient.setQueryData(queryKey, settled)
82
+ }
83
+ }, [infiniteData, queryClient, queryKey])
84
+
85
+ useEnsureWindowHoldsAnchor({ conversation_id, reply_root_id, anchor })
86
+
87
+ return {
88
+ messages,
89
+ behind,
90
+ refetch,
91
+ isRefetching,
92
+ fetchNextPage: fetchOlder,
93
+ fetchNewer,
94
+ fetchLiveWindow,
95
+ hasNextPage,
96
+ queryKey,
97
+ }
98
+ }
99
+
100
+ const useEnsureWindowHoldsAnchor = ({ conversation_id, reply_root_id, anchor }: Options) => {
101
+ const queryClient = useQueryClient()
102
+
103
+ useEffect(() => {
104
+ if (!anchor) return
105
+
106
+ const queryKey = getMessagesQueryKey({ conversation_id, reply_root_id })
107
+ const cached = queryClient.getQueryData<MessagesWindow>(queryKey)
108
+ const holdsAnchor = cached?.pages.some(page => page.data.some(m => m.id === anchor))
109
+ if (cached && !holdsAnchor) {
110
+ queryClient.resetQueries({ queryKey, exact: true })
111
+ }
112
+ }, [anchor, conversation_id, reply_root_id, queryClient])
113
+ }
114
+
115
+ export const dropMessagesWindowIfBehind = (options: WindowOptions) => {
116
+ const queryKey = getMessagesQueryKey(options)
117
+ const cached = chatQueryClient.getQueryData<MessagesWindow>(queryKey)
118
+ if (isBehindLiveEdge(cached)) chatQueryClient.removeQueries({ queryKey, exact: true })
33
119
  }
@@ -14,6 +14,7 @@ import {
14
14
  updateCacheReplyRoots,
15
15
  getThreadedMessagesQueryKey,
16
16
  } from '../utils/cache/messages_cache'
17
+ import { isBehindLiveEdge, MessagesWindow } from '../utils/cache/messages_window'
17
18
  import { transformMessageEventDataToMessageResource } from '../utils/jolt/transform_message_event_data_to_message_resource'
18
19
  import { completeMessageCreationTracking } from '../utils/performance_tracking'
19
20
  import { getMessageQueryKey } from '../utils/request/get_message'
@@ -39,12 +40,17 @@ export function useConversationMessagesJoltEvents({ conversationId }: Props) {
39
40
  const { addTypingEvent, removeTypingEventById, removeAllTypingEventsByAuthorId } =
40
41
  useTypingStatusCache(conversationId)
41
42
 
43
+ // While behind, a new message would land after a gap; the newer fetch brings it in.
44
+ const acceptsCreates = (queryKey: unknown[]) =>
45
+ !isBehindLiveEdge(queryClient.getQueryData<MessagesWindow>(queryKey))
46
+
42
47
  const handleMessageUpdateOrCreate = async (e: MessageCreatedEvent | MessageUpdatedEvent) => {
43
48
  const { data } = e.data
44
49
  const message = transformMessageEventDataToMessageResource({
45
50
  data,
46
51
  currentPersonId: currentPerson.id,
47
52
  })
53
+ const isCreate = e.event === 'message.created'
48
54
  const isReplyRootUpdate = e.event === 'message.updated' && data.reply_root_id === data.sort_key
49
55
 
50
56
  if (e.event === 'message.created' && data.author_id) {
@@ -55,7 +61,9 @@ export function useConversationMessagesJoltEvents({ conversationId }: Props) {
55
61
  }
56
62
 
57
63
  // Update the main conversation cache
58
- updateCacheWithMessage(queryClient, messagesQueryKey, message, e.event)
64
+ if (!isCreate || acceptsCreates(messagesQueryKey)) {
65
+ updateCacheWithMessage(queryClient, messagesQueryKey, message, e.event)
66
+ }
59
67
 
60
68
  // If message has a reply_root_id, also update the threaded cache
61
69
  if (data.reply_root_id) {
@@ -63,7 +71,9 @@ export function useConversationMessagesJoltEvents({ conversationId }: Props) {
63
71
  conversationId,
64
72
  data.reply_root_id
65
73
  )
66
- updateCacheWithMessage(queryClient, threadedMessagesQueryKey, message, e.event)
74
+ if (!isCreate || acceptsCreates(threadedMessagesQueryKey)) {
75
+ updateCacheWithMessage(queryClient, threadedMessagesQueryKey, message, e.event)
76
+ }
67
77
 
68
78
  if (isReplyRootUpdate) {
69
79
  updateCacheReplyRoots(queryClient, messagesQueryKey, message)
@@ -55,8 +55,9 @@ export const availableFeatures = {
55
55
  conversation_safety_lock: 'ROLLOUT_conversation_safety_lock',
56
56
  video_moderation: 'ROLLOUT_MOBILE_video_moderation',
57
57
  dm_search_clear_fix: 'ROLLOUT_MOBILE_dm_search_clear_fix',
58
- search: 'ROLLOUT_search',
59
- } as const satisfies Record<string, `ROLLOUT_${string}`>
58
+ search: 'QA_MOBILE_search',
59
+ search_rollout: 'ROLLOUT_MOBILE_search',
60
+ } as const satisfies Record<string, `${'QA' | 'ROLLOUT'}_${string}`>
60
61
 
61
62
  const stableEmptyFeatures: ApiCollection<FeatureResource> = {
62
63
  data: [],
@@ -7,9 +7,10 @@ import { useConversationsMarkRead } from './use_conversations_actions'
7
7
  interface Props {
8
8
  conversation: ConversationResource
9
9
  messages: MessageResource[]
10
+ enabled?: boolean
10
11
  }
11
12
 
12
- export function useMarkLatestMessageRead({ conversation }: Props) {
13
+ export function useMarkLatestMessageRead({ conversation, enabled = true }: Props) {
13
14
  const firedOnce = useRef<boolean>(false)
14
15
  const { markRead } = useConversationsMarkRead({ conversation })
15
16
  const debouncedMarkRead = useMemo(
@@ -24,10 +25,10 @@ export function useMarkLatestMessageRead({ conversation }: Props) {
24
25
  const isActive = appState === 'active'
25
26
 
26
27
  useEffect(() => {
27
- if (!isActive || !shouldMarkRead) return
28
+ if (!enabled || !isActive || !shouldMarkRead) return
28
29
 
29
30
  firedOnce.current = true
30
31
 
31
32
  debouncedMarkRead(true)
32
- }, [debouncedMarkRead, isActive, shouldMarkRead, unreadReaction])
33
+ }, [debouncedMarkRead, enabled, isActive, shouldMarkRead, unreadReaction])
33
34
  }
@@ -0,0 +1,77 @@
1
+ import { useInfiniteQuery } from '@tanstack/react-query'
2
+ import { useCallback, useMemo } from 'react'
3
+ import type { ApiCollection } from '../types'
4
+ import type { SearchResultResource } from '../types/resources/search_result'
5
+ import {
6
+ getSearchResultsQueryKey,
7
+ getSearchResultsRequestArgs,
8
+ } from '../utils/request/get_search_results'
9
+ import { ONE_MINUTE } from '../utils/time'
10
+ import { useApiClient } from './use_api_client'
11
+
12
+ export type SearchResultsCollection = ApiCollection<SearchResultResource> & {
13
+ meta: { failedTypes?: SearchResultResource['type'][] }
14
+ }
15
+
16
+ type SearchResultsPageParam = { offset?: number }
17
+
18
+ export const NO_FAILED_TYPES: SearchResultResource['type'][] = []
19
+
20
+ export function useSearchResults(term: string) {
21
+ const apiClient = useApiClient()
22
+
23
+ const {
24
+ data,
25
+ isPending,
26
+ isError,
27
+ isFetchNextPageError,
28
+ fetchNextPage,
29
+ hasNextPage,
30
+ isFetchingNextPage,
31
+ } = useInfiniteQuery({
32
+ queryKey: getSearchResultsQueryKey(term),
33
+ queryFn: ({ pageParam }) => {
34
+ const requestArgs = getSearchResultsRequestArgs(term)
35
+ return apiClient.chat.get<SearchResultsCollection>({
36
+ url: requestArgs.url,
37
+ data: { ...requestArgs.data, ...pageParam },
38
+ })
39
+ },
40
+ initialPageParam: {} as SearchResultsPageParam,
41
+ getNextPageParam: lastPage => nextPageParam(lastPage.meta.next?.offset),
42
+ enabled: term.length >= 1,
43
+ staleTime: ONE_MINUTE,
44
+ refetchOnWindowFocus: false,
45
+ refetchOnMount: false,
46
+ retry: 1,
47
+ })
48
+
49
+ const results = useMemo(() => uniqueResults(data?.pages.flatMap(page => page.data) ?? []), [data])
50
+ const failedTypes = data?.pages[0]?.meta.failedTypes ?? NO_FAILED_TYPES
51
+ const loadMore = useCallback(() => fetchNextPage({ cancelRefetch: false }), [fetchNextPage])
52
+
53
+ return {
54
+ results,
55
+ failedTypes,
56
+ isPending,
57
+ isError: isError && !isFetchNextPageError,
58
+ isFetchNextPageError,
59
+ loadMore,
60
+ hasNextPage,
61
+ isFetchingNextPage,
62
+ }
63
+ }
64
+
65
+ function nextPageParam(offset?: string): SearchResultsPageParam | undefined {
66
+ return offset ? { offset: Number(offset) } : undefined
67
+ }
68
+
69
+ function uniqueResults(results: SearchResultResource[]) {
70
+ const seen = new Set<string>()
71
+ return results.filter(result => {
72
+ const key = `${result.type}:${result.id}`
73
+ if (seen.has(key)) return false
74
+ seen.add(key)
75
+ return true
76
+ })
77
+ }
@@ -47,17 +47,23 @@ export const useSuspenseGet = <T extends ResourceObject | ResourceObject[]>(
47
47
  export type SuspensePaginatorOptions = Omit<
48
48
  AnyUseSuspenseInfiniteQueryOptions,
49
49
  'getNextPageParam' | 'initialPageParam' | 'queryFn' | 'queryKey'
50
- >
50
+ > & {
51
+ initialPageParam?: Partial<RequestData>
52
+ transformPage?(
53
+ page: ApiCollection<ResourceObject>,
54
+ pageParam: Partial<RequestData> | undefined
55
+ ): ApiCollection<ResourceObject>
56
+ }
51
57
 
52
58
  export const useSuspensePaginator = <T extends ResourceObject>(
53
59
  args: SuspenseGetOptions,
54
- opts?: SuspensePaginatorOptions
60
+ { transformPage, ...opts }: SuspensePaginatorOptions = {}
55
61
  ) => {
56
62
  const apiClient = useApiClient()
57
63
  const query = useSuspenseInfiniteQuery<
58
64
  ApiCollection<T>,
59
65
  Response,
60
- InfiniteData<ApiCollection<T>>,
66
+ InfiniteData<ApiCollection<T>, Partial<RequestData> | undefined>,
61
67
  any,
62
68
  Partial<RequestData> | undefined
63
69
  >({
@@ -70,7 +76,8 @@ export const useSuspensePaginator = <T extends ResourceObject>(
70
76
  const where = { ...argsWhere, ...pageParmWhere }
71
77
  const app = args.app || 'chat'
72
78
  const offset = pageParam?.offset || args.data.offset
73
- const data = { ...args.data, where, offset }
79
+ const order = pageParam?.order || args.data.order
80
+ const data = { ...args.data, where, offset, ...(order && { order }) }
74
81
 
75
82
  return apiClient[app]
76
83
  .get<ApiCollection<T>>({
@@ -78,16 +85,17 @@ export const useSuspensePaginator = <T extends ResourceObject>(
78
85
  data,
79
86
  })
80
87
  .catch(throwResponseError)
88
+ .then(page => (transformPage ? (transformPage(page, pageParam) as ApiCollection<T>) : page))
81
89
  },
82
90
  initialPageParam: {} as Partial<RequestData>,
83
91
  getNextPageParam: lastPage => getNextPageParamFromMeta(lastPage.meta?.next),
84
- ...(opts || {}),
92
+ ...opts,
85
93
  })
86
94
 
87
95
  const data: T[] = query.data?.pages.flatMap(page => page.data) || []
88
96
  const totalCount = query.data?.pages[0]?.meta?.totalCount || data.length
89
97
 
90
- return { ...query, data, totalCount }
98
+ return { ...query, data, totalCount, infiniteData: query.data }
91
99
  }
92
100
 
93
101
  export type RequestQueryKey = [
@@ -72,6 +72,7 @@ import { NotFound } from '../screens/not_found'
72
72
  import { NotificationSettingsScreen } from '../screens/notification_settings_screen'
73
73
  import { PreferredAppSelectionScreen } from '../screens/preferred_app_selection_screen'
74
74
  import { ReactionsScreen, ReactionsScreenOptions } from '../screens/reactions_screen'
75
+ import { SearchScreen, SearchScreenOptions } from '../screens/search/search_screen'
75
76
  import { SendGiphyScreen, SendGiphyScreenOptions } from '../screens/send_giphy_screen'
76
77
  import { SettingsScreen } from '../screens/settings_screen'
77
78
  import {
@@ -186,6 +187,10 @@ export const ChatStack = createNativeStackNavigator({
186
187
  screen: ConversationFiltersScreen,
187
188
  options: ConversationFiltersScreenOptions,
188
189
  },
190
+ Search: {
191
+ screen: SearchScreen,
192
+ options: SearchScreenOptions,
193
+ },
189
194
  Conversation: {
190
195
  screen: ConversationScreen,
191
196
  options: ({ route, navigation }) =>
@@ -28,7 +28,10 @@ import { ConversationContextProvider } from '../contexts/conversation_context'
28
28
  import { useMessageAvailableMembersAction } from '../hooks/direct_messages/use_message_available_members_action'
29
29
  import { useConversation } from '../hooks/use_conversation'
30
30
  import { useConversationJoltEvents } from '../hooks/use_conversation_jolt_events'
31
- import { useConversationMessages } from '../hooks/use_conversation_messages'
31
+ import {
32
+ dropMessagesWindowIfBehind,
33
+ useConversationMessages,
34
+ } from '../hooks/use_conversation_messages'
32
35
  import { useConversationMessagesJoltEvents } from '../hooks/use_conversation_messages_jolt_events'
33
36
  import { useMarkLatestMessageRead } from '../hooks/use_mark_latest_message_read'
34
37
  import {
@@ -41,10 +44,12 @@ import { useVideoModerationJoltEvents } from '../hooks/use_video_moderation_jolt
41
44
  import { ConversationResource } from '../types/resources/conversation'
42
45
  import { ConversationBadgeResource } from '../types/resources/conversation_badge'
43
46
  import { MessageResource } from '../types/resources/message'
47
+ import { Log } from '../utils'
44
48
 
45
49
  export type ConversationRouteProps = {
46
50
  conversation_id: number
47
51
  reply_root_id?: string | null
52
+ initial_message_id?: string | null
48
53
  reply_root_author_name?: string
49
54
  chat_group_graph_id?: string
50
55
  clear_input?: boolean
@@ -81,18 +86,25 @@ export function ConversationScreen({ route }: ConversationScreenProps) {
81
86
  function ConversationScreenContent({ route }: ConversationScreenProps) {
82
87
  const styles = useStyles()
83
88
  const navigation = useNavigation()
84
- const { conversation_id, editing_message_id, reply_root_id, reply_root_author_name } =
85
- route.params
86
- const { data: conversation } = useConversation(route.params)
87
- const { messages, fetchNextPage, hasNextPage } = useConversationMessages({
89
+ const {
88
90
  conversation_id,
91
+ editing_message_id,
89
92
  reply_root_id,
90
- })
93
+ reply_root_author_name,
94
+ initial_message_id,
95
+ } = route.params
96
+ const { data: conversation } = useConversation(route.params)
97
+ const { messages, behind, fetchNextPage, fetchNewer, fetchLiveWindow, hasNextPage } =
98
+ useConversationMessages({
99
+ conversation_id,
100
+ reply_root_id,
101
+ anchor: initial_message_id,
102
+ })
91
103
  useConversationJoltEvents({ conversationId: conversation_id })
92
104
  useConversationMessagesJoltEvents({ conversationId: conversation_id })
93
105
  const { markHandledByMessageForm } = useVideoModerationJoltEvents()
94
106
  useEnsureConversationsRouteExists()
95
- useMarkLatestMessageRead({ conversation, messages })
107
+ useMarkLatestMessageRead({ conversation, messages, enabled: !behind })
96
108
  const noMessages = messages.length === 0
97
109
 
98
110
  const { repliesDisabled, memberAbility, badges, title } = conversation
@@ -120,11 +132,24 @@ function ConversationScreenContent({ route }: ConversationScreenProps) {
120
132
  enabled: Platform.OS === 'ios',
121
133
  })
122
134
 
123
- const handleReturnToBottom = useCallback(() => {
124
- listRef.current?.scrollToOffset({
125
- offset: restOffset,
126
- })
127
- }, [restOffset])
135
+ const [anchorMessageId, setAnchorMessageId] = useState(initial_message_id)
136
+ const releaseAnchor = useCallback(() => setAnchorMessageId(null), [])
137
+
138
+ const handleReturnToBottom = useCallback(
139
+ (animated = true) => {
140
+ releaseAnchor()
141
+ listRef.current?.scrollToOffset({ offset: restOffset, animated })
142
+ },
143
+ [releaseAnchor, restOffset]
144
+ )
145
+
146
+ const logWindowFetchFailure = (error: unknown) =>
147
+ Log.error('conversation window fetch failed', error)
148
+
149
+ const returnToLatest = async () => {
150
+ if (behind) await fetchLiveWindow()
151
+ handleReturnToBottom(false)
152
+ }
128
153
 
129
154
  useEffect(() => {
130
155
  if (reply_root_id) {
@@ -141,6 +166,18 @@ function ConversationScreenContent({ route }: ConversationScreenProps) {
141
166
  }
142
167
  }, [navigation, title, badges, conversation?.deleted, reply_root_id, replyHeaderTitle, muted])
143
168
 
169
+ useEffect(() => {
170
+ if (!initial_message_id) return
171
+
172
+ navigation.setParams({ initial_message_id: null })
173
+ }, [initial_message_id, navigation])
174
+
175
+ // A window left behind the live edge would make the next open from the list start
176
+ // mid-history with no pill, so we only keep windows that are live.
177
+ useEffect(() => {
178
+ return () => dropMessagesWindowIfBehind({ conversation_id, reply_root_id })
179
+ }, [conversation_id, reply_root_id])
180
+
144
181
  if (!conversation || conversation.deleted) {
145
182
  return (
146
183
  <View style={styles.container}>
@@ -174,8 +211,11 @@ function ConversationScreenContent({ route }: ConversationScreenProps) {
174
211
  conversationId={conversation_id}
175
212
  messages={messages}
176
213
  replyRootId={reply_root_id}
214
+ anchorMessageId={anchorMessageId}
215
+ behind={behind}
177
216
  hasNextPage={hasNextPage}
178
217
  onEndReached={() => fetchNextPage()}
218
+ onStartReached={() => fetchNewer().catch(logWindowFetchFailure)}
179
219
  onScroll={trackScroll}
180
220
  onLayout={onLayout}
181
221
  onContentSizeChange={onContentSizeChange}
@@ -183,7 +223,12 @@ function ConversationScreenContent({ route }: ConversationScreenProps) {
183
223
  onMomentumScrollEnd={onMomentumScrollEnd}
184
224
  />
185
225
  )}
186
- <JumpToBottomButton onPress={handleReturnToBottom} visible={showJumpToBottomButton} />
226
+ <JumpToBottomButton
227
+ onPress={() =>
228
+ behind ? returnToLatest().catch(logWindowFetchFailure) : handleReturnToBottom()
229
+ }
230
+ visible={showJumpToBottomButton || behind}
231
+ />
187
232
  {!noMessages && <TypingIndicator />}
188
233
  {showLeaderDisabledReplyBanner && <LeaderMessagesDisabledBanner />}
189
234
  <ConversationBottomBar
@@ -193,6 +238,7 @@ function ConversationScreenContent({ route }: ConversationScreenProps) {
193
238
  replyRootId={reply_root_id}
194
239
  currentlyEditingMessage={currentlyEditingMessage}
195
240
  onFlaggedInMessageForm={markHandledByMessageForm}
241
+ onBeforeSubmit={returnToLatest}
196
242
  />
197
243
  </KeyboardView>
198
244
  </View>
@@ -206,6 +252,7 @@ interface ConversationBottomBarProps {
206
252
  replyRootId: string | null | undefined
207
253
  currentlyEditingMessage: MessageResource | undefined
208
254
  onFlaggedInMessageForm?: (id: string) => void
255
+ onBeforeSubmit?: () => void
209
256
  }
210
257
 
211
258
  function ConversationBottomBar({
@@ -215,6 +262,7 @@ function ConversationBottomBar({
215
262
  replyRootId,
216
263
  currentlyEditingMessage,
217
264
  onFlaggedInMessageForm,
265
+ onBeforeSubmit,
218
266
  }: ConversationBottomBarProps) {
219
267
  const messageLink = useMessageAvailableMembersAction(conversation)
220
268
 
@@ -233,6 +281,7 @@ function ConversationBottomBar({
233
281
  replyRootId={replyRootId}
234
282
  currentlyEditingMessage={currentlyEditingMessage}
235
283
  onFlaggedInMessageForm={onFlaggedInMessageForm}
284
+ onBeforeSubmit={onBeforeSubmit}
236
285
  key={
237
286
  currentlyEditingMessage
238
287
  ? `edit-message-form-${currentlyEditingMessage.id}`