@planningcenter/chat-react-native 4.5.1-qa-1061.0 → 4.5.1-qa-staging.11
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.
- package/build/components/display/conversation_avatar.d.ts +3 -1
- package/build/components/display/conversation_avatar.d.ts.map +1 -1
- package/build/components/display/conversation_avatar.js +77 -66
- package/build/components/display/conversation_avatar.js.map +1 -1
- package/build/contexts/api_provider.d.ts +1 -0
- package/build/contexts/api_provider.d.ts.map +1 -1
- package/build/contexts/api_provider.js +11 -5
- package/build/contexts/api_provider.js.map +1 -1
- package/build/hooks/index.d.ts +1 -0
- package/build/hooks/index.d.ts.map +1 -1
- package/build/hooks/index.js +1 -0
- package/build/hooks/index.js.map +1 -1
- package/build/hooks/use_conversation_avatar_update.d.ts +4 -3
- package/build/hooks/use_conversation_avatar_update.d.ts.map +1 -1
- package/build/hooks/use_conversation_avatar_update.js +146 -48
- package/build/hooks/use_conversation_avatar_update.js.map +1 -1
- package/build/hooks/use_system_message_people.d.ts +14 -0
- package/build/hooks/use_system_message_people.d.ts.map +1 -0
- package/build/hooks/use_system_message_people.js +101 -0
- package/build/hooks/use_system_message_people.js.map +1 -0
- package/build/screens/avatar_picker/avatar_picker_screen.d.ts.map +1 -1
- package/build/screens/avatar_picker/avatar_picker_screen.js +76 -66
- package/build/screens/avatar_picker/avatar_picker_screen.js.map +1 -1
- package/build/screens/system_message_people_screen.d.ts.map +1 -1
- package/build/screens/system_message_people_screen.js +33 -96
- package/build/screens/system_message_people_screen.js.map +1 -1
- package/package.json +5 -5
- package/src/__utils__/render_with_query_client.tsx +13 -0
- package/src/components/conversations/__tests__/conversation_preview.test.tsx +2 -2
- package/src/components/display/__tests__/conversation_avatar.test.tsx +94 -0
- package/src/components/display/conversation_avatar.tsx +9 -2
- package/src/contexts/__tests__/configured_retry.test.ts +39 -0
- package/src/contexts/api_provider.tsx +12 -5
- package/src/hooks/__tests__/use_conversation_avatar_update.test.tsx +40 -0
- package/src/hooks/__tests__/use_system_message_people.test.tsx +79 -0
- package/src/hooks/index.ts +1 -0
- package/src/hooks/use_conversation_avatar_update.ts +67 -11
- package/src/hooks/use_system_message_people.ts +55 -0
- package/src/screens/avatar_picker/__tests__/avatar_picker_screen.test.tsx +67 -0
- package/src/screens/avatar_picker/avatar_picker_screen.tsx +7 -1
- package/src/screens/search/__tests__/search_screen.test.tsx +6 -5
- package/src/screens/search/components/__tests__/conversation_results.test.tsx +14 -5
- package/src/screens/search/components/__tests__/message_result_row.test.tsx +5 -4
- package/src/screens/search/components/__tests__/search_results_list.test.tsx +4 -3
- package/src/screens/system_message_people_screen.tsx +6 -20
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import { QueryClientProvider } from '@tanstack/react-query'
|
|
2
|
+
import { render, type RenderOptions } from '@testing-library/react-native'
|
|
3
|
+
import React from 'react'
|
|
4
|
+
import { buildTestQueryClient } from './query_client'
|
|
5
|
+
|
|
6
|
+
export const renderWithQueryClient = (ui: React.ReactElement, options: RenderOptions = {}) => {
|
|
7
|
+
const queryClient = buildTestQueryClient()
|
|
8
|
+
const wrapper = ({ children }: { children: React.ReactNode }) => (
|
|
9
|
+
<QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
|
|
10
|
+
)
|
|
11
|
+
|
|
12
|
+
return render(ui, { wrapper, ...options })
|
|
13
|
+
}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { render } from '@testing-library/react-native'
|
|
2
1
|
import React from 'react'
|
|
2
|
+
import { renderWithQueryClient } from '../../../__utils__/render_with_query_client'
|
|
3
3
|
import type { ConversationPreviewData, ConversationResource } from '../../../types'
|
|
4
4
|
import { formatDatePreview } from '../../../utils/date'
|
|
5
5
|
import { ConversationPreview } from '../conversation_preview'
|
|
@@ -49,7 +49,7 @@ const renderPreview = (
|
|
|
49
49
|
preview: ConversationPreviewData,
|
|
50
50
|
overrides: Partial<ConversationResource> = {}
|
|
51
51
|
) =>
|
|
52
|
-
|
|
52
|
+
renderWithQueryClient(
|
|
53
53
|
<ConversationPreview conversation={conversation(preview, overrides)} onPress={jest.fn()} />
|
|
54
54
|
)
|
|
55
55
|
|
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
|
|
2
|
+
import { render, waitFor } from '@testing-library/react-native'
|
|
3
|
+
import React from 'react'
|
|
4
|
+
import { Image } from 'react-native'
|
|
5
|
+
import { buildTestQueryClient } from '../../../__utils__/query_client'
|
|
6
|
+
import type { AvatarUpdatePayload } from '../../../hooks/use_conversation_avatar_update'
|
|
7
|
+
import { ConversationAvatar } from '../conversation_avatar'
|
|
8
|
+
|
|
9
|
+
const conversation = {
|
|
10
|
+
id: 7,
|
|
11
|
+
customAvatarType: 'emoji' as const,
|
|
12
|
+
customAvatarKey: '🎉',
|
|
13
|
+
customAvatarColor: 'cosmic',
|
|
14
|
+
customAvatarImageUrl: null,
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
const imagePayload: AvatarUpdatePayload = {
|
|
18
|
+
kind: 'image',
|
|
19
|
+
color: 'cosmic',
|
|
20
|
+
imageAsset: { uri: 'file:///photo.jpg', width: 100, height: 100 },
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
let queryClient: QueryClient
|
|
24
|
+
let inFlight: { settle: () => void; done: Promise<unknown> }[]
|
|
25
|
+
|
|
26
|
+
beforeEach(() => {
|
|
27
|
+
queryClient = buildTestQueryClient({ defaultOptions: { mutations: { gcTime: Infinity } } })
|
|
28
|
+
inFlight = []
|
|
29
|
+
})
|
|
30
|
+
|
|
31
|
+
afterEach(async () => {
|
|
32
|
+
inFlight.forEach(({ settle }) => settle())
|
|
33
|
+
await Promise.all(inFlight.map(({ done }) => done))
|
|
34
|
+
queryClient.clear()
|
|
35
|
+
})
|
|
36
|
+
|
|
37
|
+
function startAvatarUpdate(conversationId: number) {
|
|
38
|
+
let settle = () => {}
|
|
39
|
+
const upload = new Promise<void>(resolve => (settle = resolve))
|
|
40
|
+
const mutation = queryClient.getMutationCache().build(queryClient, {
|
|
41
|
+
mutationKey: ['updateConversationAvatar', conversationId],
|
|
42
|
+
mutationFn: () => upload,
|
|
43
|
+
networkMode: 'always',
|
|
44
|
+
})
|
|
45
|
+
const done = mutation.execute(imagePayload)
|
|
46
|
+
inFlight.push({ settle, done })
|
|
47
|
+
return settle
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
function renderAvatar() {
|
|
51
|
+
return render(
|
|
52
|
+
<QueryClientProvider client={queryClient}>
|
|
53
|
+
<ConversationAvatar conversation={conversation} />
|
|
54
|
+
</QueryClientProvider>
|
|
55
|
+
)
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
describe('ConversationAvatar', () => {
|
|
59
|
+
it('renders the pending avatar update over the cached conversation data', () => {
|
|
60
|
+
startAvatarUpdate(conversation.id)
|
|
61
|
+
|
|
62
|
+
const view = renderAvatar()
|
|
63
|
+
|
|
64
|
+
expect(view.UNSAFE_getByType(Image).props.source).toEqual({ uri: 'file:///photo.jpg' })
|
|
65
|
+
expect(view.queryByText('🎉')).toBeNull()
|
|
66
|
+
})
|
|
67
|
+
|
|
68
|
+
it('ignores pending avatar updates for other conversations', () => {
|
|
69
|
+
startAvatarUpdate(conversation.id + 1)
|
|
70
|
+
|
|
71
|
+
const view = renderAvatar()
|
|
72
|
+
|
|
73
|
+
expect(view.getByText('🎉')).toBeTruthy()
|
|
74
|
+
})
|
|
75
|
+
|
|
76
|
+
it('returns to the cached conversation data once the update settles', async () => {
|
|
77
|
+
const settle = startAvatarUpdate(conversation.id)
|
|
78
|
+
const view = renderAvatar()
|
|
79
|
+
|
|
80
|
+
settle()
|
|
81
|
+
|
|
82
|
+
await waitFor(() => expect(view.getByText('🎉')).toBeTruthy())
|
|
83
|
+
})
|
|
84
|
+
|
|
85
|
+
it('ignores an older pending update once a newer one has settled', async () => {
|
|
86
|
+
startAvatarUpdate(conversation.id)
|
|
87
|
+
const settleNewer = startAvatarUpdate(conversation.id)
|
|
88
|
+
const view = renderAvatar()
|
|
89
|
+
|
|
90
|
+
settleNewer()
|
|
91
|
+
|
|
92
|
+
await waitFor(() => expect(view.getByText('🎉')).toBeTruthy())
|
|
93
|
+
})
|
|
94
|
+
})
|
|
@@ -1,5 +1,9 @@
|
|
|
1
1
|
import React from 'react'
|
|
2
2
|
import type { ViewStyle } from 'react-native'
|
|
3
|
+
import {
|
|
4
|
+
applyAvatarUpdate,
|
|
5
|
+
usePendingConversationAvatarUpdate,
|
|
6
|
+
} from '../../hooks/use_conversation_avatar_update'
|
|
3
7
|
import type { ConversationAvatarData } from '../../types'
|
|
4
8
|
import AvatarPrimitive, { type AvatarRootProps } from '../primitive/avatar_primitive'
|
|
5
9
|
import { AvatarGroup } from './avatar_group'
|
|
@@ -38,7 +42,7 @@ function resolveAvatar(conversation: ConversationAvatarData): ResolvedAvatar {
|
|
|
38
42
|
}
|
|
39
43
|
|
|
40
44
|
interface ConversationAvatarProps {
|
|
41
|
-
conversation: ConversationAvatarData
|
|
45
|
+
conversation: ConversationAvatarData & { id?: number }
|
|
42
46
|
size?: AvatarRootProps['size']
|
|
43
47
|
showFallback?: boolean
|
|
44
48
|
fallbackIconName?: IconString
|
|
@@ -54,7 +58,10 @@ export function ConversationAvatar({
|
|
|
54
58
|
style,
|
|
55
59
|
maxFontSizeMultiplier,
|
|
56
60
|
}: ConversationAvatarProps) {
|
|
57
|
-
const
|
|
61
|
+
const pendingUpdate = usePendingConversationAvatarUpdate(conversation.id)
|
|
62
|
+
const avatar = resolveAvatar(
|
|
63
|
+
pendingUpdate ? applyAvatarUpdate(conversation, pendingUpdate) : conversation
|
|
64
|
+
)
|
|
58
65
|
const sizeProps = { size, maxFontSizeMultiplier, style }
|
|
59
66
|
|
|
60
67
|
switch (avatar.kind) {
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import { ResponseError } from '../../utils/response_error'
|
|
2
|
+
import { configuredRetry } from '../api_provider'
|
|
3
|
+
|
|
4
|
+
jest.mock('../../hooks/use_api_client')
|
|
5
|
+
|
|
6
|
+
const responseWithStatus = (status: number) =>
|
|
7
|
+
({
|
|
8
|
+
status,
|
|
9
|
+
statusText: 'Error',
|
|
10
|
+
ok: false,
|
|
11
|
+
url: 'https://api.pco.test/chat/v2/me',
|
|
12
|
+
headers: {},
|
|
13
|
+
clone: () => ({}),
|
|
14
|
+
json: () => Promise.resolve({}),
|
|
15
|
+
text: () => Promise.resolve(''),
|
|
16
|
+
arrayBuffer: () => Promise.resolve(new ArrayBuffer(0)),
|
|
17
|
+
errors: [],
|
|
18
|
+
}) as unknown as Response
|
|
19
|
+
|
|
20
|
+
describe('configuredRetry', () => {
|
|
21
|
+
it('does not retry client errors', () => {
|
|
22
|
+
;[400, 404, 414, 422, 429].forEach(status => {
|
|
23
|
+
expect(configuredRetry(0, new ResponseError(responseWithStatus(status) as any))).toBe(false)
|
|
24
|
+
expect(configuredRetry(0, responseWithStatus(status))).toBe(false)
|
|
25
|
+
})
|
|
26
|
+
})
|
|
27
|
+
|
|
28
|
+
it('retries server errors up to three times', () => {
|
|
29
|
+
const error = new ResponseError(responseWithStatus(503) as any)
|
|
30
|
+
|
|
31
|
+
expect(configuredRetry(0, error)).toBe(true)
|
|
32
|
+
expect(configuredRetry(2, error)).toBe(true)
|
|
33
|
+
expect(configuredRetry(3, error)).toBe(false)
|
|
34
|
+
})
|
|
35
|
+
|
|
36
|
+
it('retries network failures', () => {
|
|
37
|
+
expect(configuredRetry(0, new TypeError('Network request failed'))).toBe(true)
|
|
38
|
+
})
|
|
39
|
+
})
|
|
@@ -14,7 +14,7 @@ import { featuresQueryOptions } from '../hooks/use_features'
|
|
|
14
14
|
import { useJoltForegroundPing } from '../hooks/use_jolt'
|
|
15
15
|
import { RequestQueryKey } from '../hooks/use_suspense_api'
|
|
16
16
|
import { emitAuthRefresh } from '../utils/auth_events'
|
|
17
|
-
import { ResponseError } from '../utils/response_error'
|
|
17
|
+
import { isResponseLike, ResponseError } from '../utils/response_error'
|
|
18
18
|
import { ChatContext, ChatContextValue } from './chat_context'
|
|
19
19
|
|
|
20
20
|
let apiClient: ApiClient | undefined
|
|
@@ -29,14 +29,21 @@ const defaultQueryFn = ({ queryKey }: { queryKey: QueryKey }) => {
|
|
|
29
29
|
return apiClient[app].get({ url, data, headers })
|
|
30
30
|
}
|
|
31
31
|
|
|
32
|
-
const configuredRetry = (failureCount: number, error:
|
|
33
|
-
if (
|
|
32
|
+
export const configuredRetry = (failureCount: number, error: unknown) => {
|
|
33
|
+
if (isClientError(error)) return false
|
|
34
34
|
|
|
35
35
|
return failureCount < 3
|
|
36
36
|
}
|
|
37
37
|
|
|
38
|
-
const
|
|
39
|
-
|
|
38
|
+
const isClientError = (error: unknown): boolean => {
|
|
39
|
+
const status = errorStatus(error)
|
|
40
|
+
return status !== undefined && status >= 400 && status < 500
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
const errorStatus = (error: unknown): number | undefined => {
|
|
44
|
+
if (error instanceof ResponseError) return error.status
|
|
45
|
+
if (isResponseLike(error)) return error.status
|
|
46
|
+
return undefined
|
|
40
47
|
}
|
|
41
48
|
|
|
42
49
|
export const chatQueryClient = new QueryClient({
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
import { QueryClientProvider } from '@tanstack/react-query'
|
|
2
|
+
import { act, renderHook } from '@testing-library/react-native'
|
|
3
|
+
import React from 'react'
|
|
4
|
+
import { buildTestQueryClient } from '../../__utils__/query_client'
|
|
5
|
+
import { useConversationAvatarUpdate } from '../use_conversation_avatar_update'
|
|
6
|
+
|
|
7
|
+
const mockPatch = jest.fn().mockResolvedValue({ data: { id: 7 } })
|
|
8
|
+
let finishUpload = () => {}
|
|
9
|
+
jest.mock('../use_api_client', () => ({ useApiClient: () => ({ chat: { patch: mockPatch } }) }))
|
|
10
|
+
jest.mock('../use_upload_client', () => ({
|
|
11
|
+
useUploadClient: () => ({
|
|
12
|
+
uploadFile: () => new Promise(resolve => (finishUpload = () => resolve({ id: 'upload-1' }))),
|
|
13
|
+
}),
|
|
14
|
+
}))
|
|
15
|
+
|
|
16
|
+
describe('useConversationAvatarUpdate', () => {
|
|
17
|
+
it('saves only the newest pick when an icon is chosen during a photo upload', async () => {
|
|
18
|
+
const queryClient = buildTestQueryClient({
|
|
19
|
+
defaultOptions: { mutations: { gcTime: Infinity } },
|
|
20
|
+
})
|
|
21
|
+
const wrapper = ({ children }: { children: React.ReactNode }) => (
|
|
22
|
+
<QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
|
|
23
|
+
)
|
|
24
|
+
const { result } = renderHook(() => useConversationAvatarUpdate({ conversationId: 7 }), {
|
|
25
|
+
wrapper,
|
|
26
|
+
})
|
|
27
|
+
|
|
28
|
+
const photoSave = result.current.mutateAsync({
|
|
29
|
+
kind: 'image',
|
|
30
|
+
color: 'cosmic',
|
|
31
|
+
imageAsset: { uri: 'file:///photo.jpg', width: 100, height: 100 },
|
|
32
|
+
})
|
|
33
|
+
await act(() => result.current.mutateAsync({ kind: 'icon', key: 'star', color: 'cosmic' }))
|
|
34
|
+
finishUpload()
|
|
35
|
+
await act(() => photoSave)
|
|
36
|
+
|
|
37
|
+
expect(mockPatch).toHaveBeenCalledTimes(1)
|
|
38
|
+
expect(mockPatch.mock.calls[0][0].data.data.attributes.custom_avatar_type).toBe('icon')
|
|
39
|
+
})
|
|
40
|
+
})
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
import { notifyManager, QueryClient, QueryClientProvider } from '@tanstack/react-query'
|
|
2
|
+
import { act, renderHook, waitFor } from '@testing-library/react-native'
|
|
3
|
+
import React, { Suspense } from 'react'
|
|
4
|
+
import { MEMBERS_PER_REQUEST, useSystemMessagePeople } from '../use_system_message_people'
|
|
5
|
+
|
|
6
|
+
const mockGet = jest.fn()
|
|
7
|
+
jest.mock('../use_api_client', () => ({
|
|
8
|
+
useApiClient: () => ({ chat: { get: mockGet } }),
|
|
9
|
+
}))
|
|
10
|
+
|
|
11
|
+
notifyManager.setNotifyFunction(fn => act(fn))
|
|
12
|
+
|
|
13
|
+
const conversationId = 7
|
|
14
|
+
|
|
15
|
+
const member = (id: number) => ({ type: 'Member', id, name: `Person ${id}`, avatar: '' })
|
|
16
|
+
|
|
17
|
+
const membersPage = (ids: number[]) => ({
|
|
18
|
+
data: ids.map(member),
|
|
19
|
+
links: {},
|
|
20
|
+
meta: { count: ids.length, totalCount: ids.length },
|
|
21
|
+
})
|
|
22
|
+
|
|
23
|
+
const requestedIds = () => mockGet.mock.calls.map(([request]) => request.data.where.id as number[])
|
|
24
|
+
|
|
25
|
+
const render = (personIds: number[]) => {
|
|
26
|
+
const queryClient = new QueryClient({
|
|
27
|
+
defaultOptions: { queries: { retry: false, gcTime: 0 } },
|
|
28
|
+
})
|
|
29
|
+
const wrapper = ({ children }: { children: React.ReactNode }) => (
|
|
30
|
+
<QueryClientProvider client={queryClient}>
|
|
31
|
+
<Suspense fallback={null}>{children}</Suspense>
|
|
32
|
+
</QueryClientProvider>
|
|
33
|
+
)
|
|
34
|
+
|
|
35
|
+
return renderHook(() => useSystemMessagePeople({ conversationId, personIds }), { wrapper })
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
beforeEach(() => {
|
|
39
|
+
mockGet.mockReset()
|
|
40
|
+
mockGet.mockImplementation(({ data }) =>
|
|
41
|
+
Promise.resolve(membersPage([...(data.where.id as number[])].reverse()))
|
|
42
|
+
)
|
|
43
|
+
})
|
|
44
|
+
|
|
45
|
+
describe('useSystemMessagePeople', () => {
|
|
46
|
+
it('requests members in batches no larger than a page', async () => {
|
|
47
|
+
const personIds = Array.from({ length: 250 }, (_, i) => i + 1)
|
|
48
|
+
|
|
49
|
+
render(personIds)
|
|
50
|
+
|
|
51
|
+
await waitFor(() => expect(mockGet).toHaveBeenCalledTimes(3))
|
|
52
|
+
|
|
53
|
+
expect(requestedIds().map(ids => ids.length)).toEqual([100, 100, 50])
|
|
54
|
+
expect(requestedIds().flat()).toEqual(personIds)
|
|
55
|
+
mockGet.mock.calls.forEach(([request]) => {
|
|
56
|
+
expect(request.url).toEqual(`/me/conversations/${conversationId}/members`)
|
|
57
|
+
expect(request.data.perPage).toEqual(MEMBERS_PER_REQUEST)
|
|
58
|
+
})
|
|
59
|
+
})
|
|
60
|
+
|
|
61
|
+
it('returns everyone in the order of the system message', async () => {
|
|
62
|
+
const personIds = Array.from({ length: 150 }, (_, i) => 1000 - i)
|
|
63
|
+
|
|
64
|
+
const { result } = render(personIds)
|
|
65
|
+
|
|
66
|
+
await waitFor(() => expect(result.current?.data).toHaveLength(150))
|
|
67
|
+
|
|
68
|
+
expect(result.current.data.map(({ id }) => id)).toEqual(personIds)
|
|
69
|
+
})
|
|
70
|
+
|
|
71
|
+
it('makes a single request for a small list', async () => {
|
|
72
|
+
const { result } = render([3, 1, 2])
|
|
73
|
+
|
|
74
|
+
await waitFor(() => expect(result.current?.data).toHaveLength(3))
|
|
75
|
+
|
|
76
|
+
expect(mockGet).toHaveBeenCalledTimes(1)
|
|
77
|
+
expect(result.current.data.map(({ id }) => id)).toEqual([3, 1, 2])
|
|
78
|
+
})
|
|
79
|
+
})
|
package/src/hooks/index.ts
CHANGED
|
@@ -1,7 +1,12 @@
|
|
|
1
|
-
import { useMutation, useQueryClient } from '@tanstack/react-query'
|
|
2
|
-
import { Alert } from 'react-native'
|
|
3
|
-
import type {
|
|
4
|
-
|
|
1
|
+
import { InfiniteData, useMutation, useMutationState, useQueryClient } from '@tanstack/react-query'
|
|
2
|
+
import { Alert, Image } from 'react-native'
|
|
3
|
+
import type {
|
|
4
|
+
ApiCollection,
|
|
5
|
+
ApiResource,
|
|
6
|
+
ConversationAvatarData,
|
|
7
|
+
ConversationResource,
|
|
8
|
+
} from '../types'
|
|
9
|
+
import { updateAllRecordsInPagesData } from '../utils/cache/page_mutations'
|
|
5
10
|
import { transformGetToPost } from '../utils/client/request_helpers'
|
|
6
11
|
import type { ImagePickerAsset } from '../utils/native_adapters/image_picker'
|
|
7
12
|
import { ApiClient, useApiClient } from './use_api_client'
|
|
@@ -16,6 +21,18 @@ export type AvatarUpdatePayload =
|
|
|
16
21
|
| { kind: Extract<AvatarType, 'image'>; imageAsset: ImagePickerAsset; color: string }
|
|
17
22
|
| { kind: 'clear' }
|
|
18
23
|
|
|
24
|
+
const MUTATION_KEY = 'updateConversationAvatar'
|
|
25
|
+
|
|
26
|
+
export const usePendingConversationAvatarUpdate = (conversationId: number | undefined) => {
|
|
27
|
+
const newest = useMutationState({
|
|
28
|
+
filters: { mutationKey: [MUTATION_KEY, conversationId], exact: true },
|
|
29
|
+
select: mutation => mutation.state,
|
|
30
|
+
}).at(-1)
|
|
31
|
+
|
|
32
|
+
if (conversationId === undefined || newest?.status !== 'pending') return undefined
|
|
33
|
+
return newest.variables as AvatarUpdatePayload
|
|
34
|
+
}
|
|
35
|
+
|
|
19
36
|
export const useConversationAvatarUpdate = ({ conversationId }: { conversationId: number }) => {
|
|
20
37
|
const apiClient = useApiClient()
|
|
21
38
|
const uploadClient = useUploadClient()
|
|
@@ -23,11 +40,18 @@ export const useConversationAvatarUpdate = ({ conversationId }: { conversationId
|
|
|
23
40
|
const requestArgs = getConversationRequestArgs({ conversation_id: conversationId })
|
|
24
41
|
const queryKey = getRequestQueryKey(requestArgs)
|
|
25
42
|
|
|
43
|
+
const isSuperseded = (payload: AvatarUpdatePayload) =>
|
|
44
|
+
queryClient
|
|
45
|
+
.getMutationCache()
|
|
46
|
+
.findAll({ mutationKey: [MUTATION_KEY, conversationId], exact: true })
|
|
47
|
+
.at(-1)?.state.variables !== payload
|
|
48
|
+
|
|
26
49
|
return useMutation({
|
|
27
|
-
mutationKey: [
|
|
50
|
+
mutationKey: [MUTATION_KEY, conversationId],
|
|
28
51
|
mutationFn: async (payload: AvatarUpdatePayload) => {
|
|
29
52
|
const postArgs = transformGetToPost(requestArgs).data
|
|
30
53
|
const attributes = await buildAttributes(payload, uploadClient)
|
|
54
|
+
if (isSuperseded(payload)) return null
|
|
31
55
|
|
|
32
56
|
return apiClient.chat.patch<ApiResource<ConversationResource>>({
|
|
33
57
|
url: `/me/conversations/${conversationId}/`,
|
|
@@ -41,16 +65,35 @@ export const useConversationAvatarUpdate = ({ conversationId }: { conversationId
|
|
|
41
65
|
|
|
42
66
|
queryClient.setQueryData<ApiResource<ConversationResource>>(queryKey, prev => {
|
|
43
67
|
if (!prev?.data) return prev
|
|
44
|
-
return { ...prev, data:
|
|
68
|
+
return { ...prev, data: applyAvatarUpdate(prev.data, payload) }
|
|
45
69
|
})
|
|
46
70
|
|
|
47
71
|
return { previous }
|
|
48
72
|
},
|
|
49
|
-
onSuccess: (response, _payload, _context) => {
|
|
73
|
+
onSuccess: async (response, _payload, _context) => {
|
|
74
|
+
if (!response) return
|
|
75
|
+
|
|
50
76
|
queryClient.setQueryData<ApiResource<ConversationResource>>(queryKey, () => response)
|
|
77
|
+
queryClient.setQueriesData<InfiniteData<ApiCollection<ConversationResource>>>(
|
|
78
|
+
{ queryKey: ['/me/conversations'] },
|
|
79
|
+
prev => {
|
|
80
|
+
if (!prev?.pages) return prev
|
|
81
|
+
|
|
82
|
+
return updateAllRecordsInPagesData({
|
|
83
|
+
data: prev,
|
|
84
|
+
processRecord: record =>
|
|
85
|
+
record.id === conversationId ? applySavedAvatar(record, response.data) : record,
|
|
86
|
+
})
|
|
87
|
+
}
|
|
88
|
+
)
|
|
51
89
|
queryClient.invalidateQueries({ queryKey: ['/me/conversations'] })
|
|
90
|
+
|
|
91
|
+
const imageUrl = response.data.customAvatarImageUrl
|
|
92
|
+
if (imageUrl) await Image.prefetch(imageUrl).catch(() => false)
|
|
52
93
|
},
|
|
53
|
-
onError: (_error,
|
|
94
|
+
onError: (_error, payload, context) => {
|
|
95
|
+
if (isSuperseded(payload)) return
|
|
96
|
+
|
|
54
97
|
if (context?.previous) {
|
|
55
98
|
queryClient.setQueryData(queryKey, context.previous)
|
|
56
99
|
}
|
|
@@ -83,10 +126,23 @@ export async function patchConversationAvatar(
|
|
|
83
126
|
}
|
|
84
127
|
}
|
|
85
128
|
|
|
86
|
-
function
|
|
87
|
-
data:
|
|
129
|
+
function applySavedAvatar<T extends ConversationAvatarData>(
|
|
130
|
+
data: T,
|
|
131
|
+
saved: ConversationAvatarData
|
|
132
|
+
): T {
|
|
133
|
+
return {
|
|
134
|
+
...data,
|
|
135
|
+
customAvatarType: saved.customAvatarType,
|
|
136
|
+
customAvatarKey: saved.customAvatarKey,
|
|
137
|
+
customAvatarColor: saved.customAvatarColor,
|
|
138
|
+
customAvatarImageUrl: saved.customAvatarImageUrl,
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
export function applyAvatarUpdate<T extends ConversationAvatarData>(
|
|
143
|
+
data: T,
|
|
88
144
|
payload: AvatarUpdatePayload
|
|
89
|
-
):
|
|
145
|
+
): T {
|
|
90
146
|
switch (payload.kind) {
|
|
91
147
|
case 'icon':
|
|
92
148
|
return {
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
import { useSuspenseQueries } from '@tanstack/react-query'
|
|
2
|
+
import { chunk, sortBy } from 'lodash'
|
|
3
|
+
import { ApiCollection, MemberResource } from '../types'
|
|
4
|
+
import { GetRequest } from '../utils/client'
|
|
5
|
+
import { throwResponseError } from '../utils/response_error'
|
|
6
|
+
import { useApiClient } from './use_api_client'
|
|
7
|
+
import { getRequestQueryKey } from './use_suspense_api'
|
|
8
|
+
|
|
9
|
+
export const MEMBERS_PER_REQUEST = 100
|
|
10
|
+
|
|
11
|
+
type SystemMessagePeopleArgs = {
|
|
12
|
+
conversationId: number
|
|
13
|
+
personIds: number[]
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
export type SystemMessagePerson = Pick<MemberResource, 'type' | 'id' | 'name' | 'avatar'>
|
|
17
|
+
|
|
18
|
+
export const systemMessagePeopleRequest = (
|
|
19
|
+
conversationId: number,
|
|
20
|
+
personIds: number[]
|
|
21
|
+
): GetRequest => ({
|
|
22
|
+
url: `/me/conversations/${conversationId}/members`,
|
|
23
|
+
data: {
|
|
24
|
+
fields: {
|
|
25
|
+
Member: ['id', 'name', 'avatar'],
|
|
26
|
+
},
|
|
27
|
+
where: {
|
|
28
|
+
id: personIds,
|
|
29
|
+
},
|
|
30
|
+
perPage: MEMBERS_PER_REQUEST,
|
|
31
|
+
},
|
|
32
|
+
})
|
|
33
|
+
|
|
34
|
+
export const useSystemMessagePeople = ({ conversationId, personIds }: SystemMessagePeopleArgs) => {
|
|
35
|
+
const apiClient = useApiClient()
|
|
36
|
+
const requests = chunk(personIds, MEMBERS_PER_REQUEST).map(ids =>
|
|
37
|
+
systemMessagePeopleRequest(conversationId, ids)
|
|
38
|
+
)
|
|
39
|
+
|
|
40
|
+
const queries = useSuspenseQueries({
|
|
41
|
+
queries: requests.map(request => ({
|
|
42
|
+
queryKey: getRequestQueryKey(request),
|
|
43
|
+
queryFn: (): Promise<ApiCollection<SystemMessagePerson>> =>
|
|
44
|
+
apiClient.chat.get<ApiCollection<SystemMessagePerson>>(request).catch(throwResponseError),
|
|
45
|
+
})),
|
|
46
|
+
})
|
|
47
|
+
|
|
48
|
+
const orderById = Object.fromEntries(personIds.map((id, index) => [id, index]))
|
|
49
|
+
const people = sortBy(
|
|
50
|
+
queries.flatMap(query => query.data.data),
|
|
51
|
+
person => orderById[person.id] ?? personIds.length
|
|
52
|
+
)
|
|
53
|
+
|
|
54
|
+
return { data: people }
|
|
55
|
+
}
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
import { HeaderHeightContext } from '@react-navigation/elements'
|
|
2
|
+
import { DefaultTheme, ThemeProvider } from '@react-navigation/native'
|
|
3
|
+
import { QueryClientProvider } from '@tanstack/react-query'
|
|
4
|
+
import { render } from '@testing-library/react-native'
|
|
5
|
+
import React from 'react'
|
|
6
|
+
import { Image } from 'react-native'
|
|
7
|
+
import { SafeAreaProvider } from 'react-native-safe-area-context'
|
|
8
|
+
import { buildTestQueryClient } from '../../../__utils__/query_client'
|
|
9
|
+
import type { AvatarUpdatePayload } from '../../../hooks/use_conversation_avatar_update'
|
|
10
|
+
import { AvatarPickerScreen } from '../avatar_picker_screen'
|
|
11
|
+
|
|
12
|
+
jest.mock('@react-navigation/native', () => ({
|
|
13
|
+
...jest.requireActual('@react-navigation/native'),
|
|
14
|
+
useNavigation: () => ({ goBack: jest.fn(), dispatch: jest.fn() }),
|
|
15
|
+
}))
|
|
16
|
+
jest.mock('../../../hooks/use_api_client', () => ({ useApiClient: () => ({}) }))
|
|
17
|
+
jest.mock('../../../hooks/use_upload_client', () => ({ useUploadClient: () => ({}) }))
|
|
18
|
+
jest.mock('../../../hooks/use_conversation', () => ({
|
|
19
|
+
...jest.requireActual('../../../hooks/use_conversation'),
|
|
20
|
+
useConversation: () => ({
|
|
21
|
+
data: { id: 7, customAvatarType: 'icon', customAvatarKey: 'star', customAvatarColor: 'cosmic' },
|
|
22
|
+
}),
|
|
23
|
+
}))
|
|
24
|
+
|
|
25
|
+
const safeAreaMetrics = {
|
|
26
|
+
frame: { x: 0, y: 0, width: 390, height: 844 },
|
|
27
|
+
insets: { top: 0, right: 0, bottom: 0, left: 0 },
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
describe('AvatarPickerScreen', () => {
|
|
31
|
+
it('opens on a photo that is still uploading instead of the cached avatar', async () => {
|
|
32
|
+
const queryClient = buildTestQueryClient()
|
|
33
|
+
const photo: AvatarUpdatePayload = {
|
|
34
|
+
kind: 'image',
|
|
35
|
+
color: 'cosmic',
|
|
36
|
+
imageAsset: { uri: 'file:///photo.jpg', width: 100, height: 100 },
|
|
37
|
+
}
|
|
38
|
+
let finishUpload = () => {}
|
|
39
|
+
const uploading = new Promise<void>(resolve => (finishUpload = resolve))
|
|
40
|
+
const upload = queryClient
|
|
41
|
+
.getMutationCache()
|
|
42
|
+
.build(queryClient, {
|
|
43
|
+
mutationKey: ['updateConversationAvatar', 7],
|
|
44
|
+
mutationFn: () => uploading,
|
|
45
|
+
networkMode: 'always',
|
|
46
|
+
})
|
|
47
|
+
.execute(photo)
|
|
48
|
+
|
|
49
|
+
const view = render(
|
|
50
|
+
<SafeAreaProvider initialMetrics={safeAreaMetrics}>
|
|
51
|
+
<ThemeProvider value={DefaultTheme}>
|
|
52
|
+
<HeaderHeightContext.Provider value={0}>
|
|
53
|
+
<QueryClientProvider client={queryClient}>
|
|
54
|
+
<AvatarPickerScreen route={{ params: { conversation_id: 7 } } as never} />
|
|
55
|
+
</QueryClientProvider>
|
|
56
|
+
</HeaderHeightContext.Provider>
|
|
57
|
+
</ThemeProvider>
|
|
58
|
+
</SafeAreaProvider>
|
|
59
|
+
)
|
|
60
|
+
|
|
61
|
+
const sources = view.UNSAFE_getAllByType(Image).map(image => image.props.source)
|
|
62
|
+
expect(sources).toContainEqual({ uri: 'file:///photo.jpg' })
|
|
63
|
+
|
|
64
|
+
finishUpload()
|
|
65
|
+
await upload
|
|
66
|
+
})
|
|
67
|
+
})
|
|
@@ -11,6 +11,7 @@ import { useTheme } from '../../hooks'
|
|
|
11
11
|
import { useConversation } from '../../hooks/use_conversation'
|
|
12
12
|
import {
|
|
13
13
|
useConversationAvatarUpdate,
|
|
14
|
+
usePendingConversationAvatarUpdate,
|
|
14
15
|
type AvatarUpdatePayload,
|
|
15
16
|
} from '../../hooks/use_conversation_avatar_update'
|
|
16
17
|
import { useFontScale } from '../../hooks/use_font_scale'
|
|
@@ -79,9 +80,14 @@ function EditModeContent({ conversationId }: { conversationId: number }) {
|
|
|
79
80
|
const navigation = useNavigation()
|
|
80
81
|
const { data: conversation } = useConversation({ conversation_id: conversationId })
|
|
81
82
|
const mutation = useConversationAvatarUpdate({ conversationId })
|
|
83
|
+
const pendingUpdate = usePendingConversationAvatarUpdate(conversationId)
|
|
82
84
|
const previewDiameter = usePreviewAvatarDiameter()
|
|
83
85
|
|
|
84
|
-
const [state, dispatch] = useReducer(avatarPickerReducer,
|
|
86
|
+
const [state, dispatch] = useReducer(avatarPickerReducer, undefined, () =>
|
|
87
|
+
pendingUpdate
|
|
88
|
+
? initAvatarPickerStateFromPayload(pendingUpdate)
|
|
89
|
+
: initAvatarPickerState(conversation)
|
|
90
|
+
)
|
|
85
91
|
|
|
86
92
|
const hasAvatar = state.selectedType !== null
|
|
87
93
|
|
|
@@ -1,6 +1,7 @@
|
|
|
1
|
-
import { act, fireEvent
|
|
1
|
+
import { act, fireEvent } from '@testing-library/react-native'
|
|
2
2
|
import React from 'react'
|
|
3
3
|
import { Keyboard, ScrollView } from 'react-native'
|
|
4
|
+
import { renderWithQueryClient } from '../../../__utils__/render_with_query_client'
|
|
4
5
|
import type { useSearchResults } from '../../../hooks/use_search_results'
|
|
5
6
|
import type {
|
|
6
7
|
ConversationSearchResultResource,
|
|
@@ -71,7 +72,7 @@ const renderWithResults = () => {
|
|
|
71
72
|
hasNextPage: false,
|
|
72
73
|
isFetchingNextPage: false,
|
|
73
74
|
})
|
|
74
|
-
const view =
|
|
75
|
+
const view = renderWithQueryClient(<SearchScreen />)
|
|
75
76
|
const input = view.getByLabelText(inputLabel)
|
|
76
77
|
fireEvent.changeText(input, 'bud')
|
|
77
78
|
fireEvent.changeText(input, 'budget')
|
|
@@ -99,7 +100,7 @@ afterEach(() => jest.useRealTimers())
|
|
|
99
100
|
|
|
100
101
|
describe('SearchScreen', () => {
|
|
101
102
|
it('searches once with the trimmed term after typing settles', () => {
|
|
102
|
-
const view =
|
|
103
|
+
const view = renderWithQueryClient(<SearchScreen />)
|
|
103
104
|
const input = view.getByLabelText(inputLabel)
|
|
104
105
|
|
|
105
106
|
fireEvent.changeText(input, 'bud')
|
|
@@ -118,7 +119,7 @@ describe('SearchScreen', () => {
|
|
|
118
119
|
})
|
|
119
120
|
|
|
120
121
|
it('lets the prompt scroll while taps still reach the field', () => {
|
|
121
|
-
const view =
|
|
122
|
+
const view = renderWithQueryClient(<SearchScreen />)
|
|
122
123
|
|
|
123
124
|
const scrollView = view.UNSAFE_getByType(ScrollView)
|
|
124
125
|
expect(scrollView.props.keyboardShouldPersistTaps).toBe('handled')
|
|
@@ -127,7 +128,7 @@ describe('SearchScreen', () => {
|
|
|
127
128
|
})
|
|
128
129
|
|
|
129
130
|
it('returns to the prompt as soon as the term is cleared', () => {
|
|
130
|
-
const view =
|
|
131
|
+
const view = renderWithQueryClient(<SearchScreen />)
|
|
131
132
|
const input = view.getByLabelText(inputLabel)
|
|
132
133
|
|
|
133
134
|
fireEvent.changeText(input, 'budget')
|