@planningcenter/chat-react-native 4.7.1-qa-staging.8 → 4.7.1-qa-staging.9

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 (56) hide show
  1. package/build/contexts/api_provider.d.ts.map +1 -1
  2. package/build/contexts/api_provider.js +2 -0
  3. package/build/contexts/api_provider.js.map +1 -1
  4. package/build/contexts/session_context.d.ts.map +1 -1
  5. package/build/contexts/session_context.js +3 -0
  6. package/build/contexts/session_context.js.map +1 -1
  7. package/build/hooks/use_conversation_jolt_events.d.ts.map +1 -1
  8. package/build/hooks/use_conversation_jolt_events.js +3 -2
  9. package/build/hooks/use_conversation_jolt_events.js.map +1 -1
  10. package/build/hooks/use_conversations_actions.d.ts +9 -9
  11. package/build/hooks/use_conversations_actions.d.ts.map +1 -1
  12. package/build/hooks/use_conversations_actions.js +12 -7
  13. package/build/hooks/use_conversations_actions.js.map +1 -1
  14. package/build/hooks/use_conversations_cache.d.ts +1 -3
  15. package/build/hooks/use_conversations_cache.d.ts.map +1 -1
  16. package/build/hooks/use_conversations_cache.js +79 -124
  17. package/build/hooks/use_conversations_cache.js.map +1 -1
  18. package/build/hooks/use_conversations_jolt_events.d.ts.map +1 -1
  19. package/build/hooks/use_conversations_jolt_events.js +47 -20
  20. package/build/hooks/use_conversations_jolt_events.js.map +1 -1
  21. package/build/hooks/use_mark_latest_message_read.d.ts.map +1 -1
  22. package/build/hooks/use_mark_latest_message_read.js +5 -4
  23. package/build/hooks/use_mark_latest_message_read.js.map +1 -1
  24. package/build/types/jolt_events/index.d.ts +2 -0
  25. package/build/types/jolt_events/index.d.ts.map +1 -1
  26. package/build/types/jolt_events/index.js.map +1 -1
  27. package/build/types/jolt_events/person_events.d.ts +9 -0
  28. package/build/types/jolt_events/person_events.d.ts.map +1 -0
  29. package/build/types/jolt_events/person_events.js +2 -0
  30. package/build/types/jolt_events/person_events.js.map +1 -0
  31. package/build/utils/jolt/parse_stream_user_event_type.d.ts +3 -0
  32. package/build/utils/jolt/parse_stream_user_event_type.d.ts.map +1 -0
  33. package/build/utils/jolt/parse_stream_user_event_type.js +9 -0
  34. package/build/utils/jolt/parse_stream_user_event_type.js.map +1 -0
  35. package/build/utils/throttled_refresh.d.ts +7 -0
  36. package/build/utils/throttled_refresh.d.ts.map +1 -0
  37. package/build/utils/throttled_refresh.js +42 -0
  38. package/build/utils/throttled_refresh.js.map +1 -0
  39. package/package.json +3 -3
  40. package/src/contexts/api_provider.tsx +2 -0
  41. package/src/contexts/session_context.tsx +3 -0
  42. package/src/hooks/__tests__/jolt_refresh_throttling.test.tsx +229 -0
  43. package/src/hooks/__tests__/use_conversations_jolt_events.test.tsx +1 -0
  44. package/src/hooks/__tests__/use_conversations_mark_read.test.tsx +38 -12
  45. package/src/hooks/__tests__/use_mark_latest_message_read.test.tsx +23 -2
  46. package/src/hooks/use_conversation_jolt_events.ts +2 -1
  47. package/src/hooks/use_conversations_actions.ts +7 -4
  48. package/src/hooks/use_conversations_cache.ts +1 -23
  49. package/src/hooks/use_conversations_jolt_events.ts +24 -10
  50. package/src/hooks/use_mark_latest_message_read.ts +6 -5
  51. package/src/types/jolt_events/index.ts +2 -0
  52. package/src/types/jolt_events/person_events.ts +16 -0
  53. package/src/utils/__tests__/throttled_refresh.test.ts +101 -0
  54. package/src/utils/jolt/__tests__/parse_stream_user_event_type.test.ts +27 -0
  55. package/src/utils/jolt/parse_stream_user_event_type.ts +16 -0
  56. package/src/utils/throttled_refresh.ts +62 -0
@@ -0,0 +1 @@
1
+ {"version":3,"file":"throttled_refresh.d.ts","sourceRoot":"","sources":["../../src/utils/throttled_refresh.ts"],"names":[],"mappings":"AAAA,OAAO,EAAW,WAAW,EAAE,QAAQ,EAAE,MAAM,uBAAuB,CAAA;AAGtE,eAAO,MAAM,mBAAmB,OAAO,CAAA;AAEvC,KAAK,OAAO,GAAG,MAAM,OAAO,CAAA;AAqC5B,eAAO,MAAM,gBAAgB,GAC3B,aAAa,WAAW,EACxB,KAAK,QAAQ,EACb,OAAO,MAAM,EACb,SAAS,OAAO,SAOjB,CAAA;AAED,eAAO,MAAM,wBAAwB,GAAI,aAAa,WAAW,SAMhE,CAAA"}
@@ -0,0 +1,42 @@
1
+ import { hashKey } from '@tanstack/react-query';
2
+ import { throttle } from 'lodash';
3
+ export const REFRESH_THROTTLE_MS = 3000;
4
+ const refreshesByClient = new WeakMap();
5
+ const refreshesFor = queryClient => {
6
+ const existing = refreshesByClient.get(queryClient);
7
+ if (existing) return existing;
8
+ const refreshes = new Map();
9
+ refreshesByClient.set(queryClient, refreshes);
10
+ return refreshes;
11
+ };
12
+ const throttledRefreshFor = (queryClient, key) => {
13
+ const refreshes = refreshesFor(queryClient);
14
+ const hashedKey = hashKey(key);
15
+ const existing = refreshes.get(hashedKey);
16
+ if (existing) return existing;
17
+ const created = {
18
+ run: throttle(refresh => {
19
+ refresh();
20
+ }, REFRESH_THROTTLE_MS, {
21
+ leading: true,
22
+ trailing: true
23
+ })
24
+ };
25
+ refreshes.set(hashedKey, created);
26
+ return created;
27
+ };
28
+ export const throttledRefresh = (queryClient, key, event, refresh) => {
29
+ const throttled = throttledRefreshFor(queryClient, key);
30
+ if (throttled.lastEvent === event) return;
31
+ throttled.lastEvent = event;
32
+ throttled.run(refresh);
33
+ };
34
+ export const cancelThrottledRefreshes = queryClient => {
35
+ const refreshes = refreshesByClient.get(queryClient);
36
+ if (!refreshes) return;
37
+ refreshes.forEach(({
38
+ run
39
+ }) => run.cancel());
40
+ refreshesByClient.delete(queryClient);
41
+ };
42
+ //# sourceMappingURL=throttled_refresh.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"throttled_refresh.js","names":["hashKey","throttle","REFRESH_THROTTLE_MS","refreshesByClient","WeakMap","refreshesFor","queryClient","existing","get","refreshes","Map","set","throttledRefreshFor","key","hashedKey","created","run","refresh","leading","trailing","throttledRefresh","event","throttled","lastEvent","cancelThrottledRefreshes","forEach","cancel","delete"],"sources":["../../src/utils/throttled_refresh.ts"],"sourcesContent":["import { hashKey, QueryClient, QueryKey } from '@tanstack/react-query'\nimport { DebouncedFuncLeading, throttle } from 'lodash'\n\nexport const REFRESH_THROTTLE_MS = 3000\n\ntype Refresh = () => unknown\n\ninterface ThrottledRefresh {\n run: DebouncedFuncLeading<(refresh: Refresh) => void>\n lastEvent?: object\n}\n\nconst refreshesByClient = new WeakMap<QueryClient, Map<string, ThrottledRefresh>>()\n\nconst refreshesFor = (queryClient: QueryClient) => {\n const existing = refreshesByClient.get(queryClient)\n if (existing) return existing\n\n const refreshes = new Map<string, ThrottledRefresh>()\n refreshesByClient.set(queryClient, refreshes)\n return refreshes\n}\n\nconst throttledRefreshFor = (queryClient: QueryClient, key: QueryKey) => {\n const refreshes = refreshesFor(queryClient)\n const hashedKey = hashKey(key)\n const existing = refreshes.get(hashedKey)\n if (existing) return existing\n\n const created: ThrottledRefresh = {\n run: throttle(\n (refresh: Refresh) => {\n refresh()\n },\n REFRESH_THROTTLE_MS,\n { leading: true, trailing: true }\n ),\n }\n refreshes.set(hashedKey, created)\n return created\n}\n\nexport const throttledRefresh = (\n queryClient: QueryClient,\n key: QueryKey,\n event: object,\n refresh: Refresh\n) => {\n const throttled = throttledRefreshFor(queryClient, key)\n if (throttled.lastEvent === event) return\n\n throttled.lastEvent = event\n throttled.run(refresh)\n}\n\nexport const cancelThrottledRefreshes = (queryClient: QueryClient) => {\n const refreshes = refreshesByClient.get(queryClient)\n if (!refreshes) return\n\n refreshes.forEach(({ run }) => run.cancel())\n refreshesByClient.delete(queryClient)\n}\n"],"mappings":"AAAA,SAASA,OAAO,QAA+B,uBAAuB;AACtE,SAA+BC,QAAQ,QAAQ,QAAQ;AAEvD,OAAO,MAAMC,mBAAmB,GAAG,IAAI;AASvC,MAAMC,iBAAiB,GAAG,IAAIC,OAAO,CAA6C,CAAC;AAEnF,MAAMC,YAAY,GAAIC,WAAwB,IAAK;EACjD,MAAMC,QAAQ,GAAGJ,iBAAiB,CAACK,GAAG,CAACF,WAAW,CAAC;EACnD,IAAIC,QAAQ,EAAE,OAAOA,QAAQ;EAE7B,MAAME,SAAS,GAAG,IAAIC,GAAG,CAA2B,CAAC;EACrDP,iBAAiB,CAACQ,GAAG,CAACL,WAAW,EAAEG,SAAS,CAAC;EAC7C,OAAOA,SAAS;AAClB,CAAC;AAED,MAAMG,mBAAmB,GAAGA,CAACN,WAAwB,EAAEO,GAAa,KAAK;EACvE,MAAMJ,SAAS,GAAGJ,YAAY,CAACC,WAAW,CAAC;EAC3C,MAAMQ,SAAS,GAAGd,OAAO,CAACa,GAAG,CAAC;EAC9B,MAAMN,QAAQ,GAAGE,SAAS,CAACD,GAAG,CAACM,SAAS,CAAC;EACzC,IAAIP,QAAQ,EAAE,OAAOA,QAAQ;EAE7B,MAAMQ,OAAyB,GAAG;IAChCC,GAAG,EAAEf,QAAQ,CACVgB,OAAgB,IAAK;MACpBA,OAAO,CAAC,CAAC;IACX,CAAC,EACDf,mBAAmB,EACnB;MAAEgB,OAAO,EAAE,IAAI;MAAEC,QAAQ,EAAE;IAAK,CAClC;EACF,CAAC;EACDV,SAAS,CAACE,GAAG,CAACG,SAAS,EAAEC,OAAO,CAAC;EACjC,OAAOA,OAAO;AAChB,CAAC;AAED,OAAO,MAAMK,gBAAgB,GAAGA,CAC9Bd,WAAwB,EACxBO,GAAa,EACbQ,KAAa,EACbJ,OAAgB,KACb;EACH,MAAMK,SAAS,GAAGV,mBAAmB,CAACN,WAAW,EAAEO,GAAG,CAAC;EACvD,IAAIS,SAAS,CAACC,SAAS,KAAKF,KAAK,EAAE;EAEnCC,SAAS,CAACC,SAAS,GAAGF,KAAK;EAC3BC,SAAS,CAACN,GAAG,CAACC,OAAO,CAAC;AACxB,CAAC;AAED,OAAO,MAAMO,wBAAwB,GAAIlB,WAAwB,IAAK;EACpE,MAAMG,SAAS,GAAGN,iBAAiB,CAACK,GAAG,CAACF,WAAW,CAAC;EACpD,IAAI,CAACG,SAAS,EAAE;EAEhBA,SAAS,CAACgB,OAAO,CAAC,CAAC;IAAET;EAAI,CAAC,KAAKA,GAAG,CAACU,MAAM,CAAC,CAAC,CAAC;EAC5CvB,iBAAiB,CAACwB,MAAM,CAACrB,WAAW,CAAC;AACvC,CAAC","ignoreList":[]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@planningcenter/chat-react-native",
3
- "version": "4.7.1-qa-staging.8",
3
+ "version": "4.7.1-qa-staging.9",
4
4
  "description": "",
5
5
  "repository": {
6
6
  "type": "git",
@@ -33,7 +33,7 @@
33
33
  "dependencies": {
34
34
  "@fortawesome/fontawesome-svg-core": "^7.2.0",
35
35
  "@fortawesome/react-native-fontawesome": "^0.3.2",
36
- "@planningcenter/emoji-keyboard": "4.7.1-qa-staging.8",
36
+ "@planningcenter/emoji-keyboard": "4.7.1-qa-staging.9",
37
37
  "lodash-inflection": "^1.5.0"
38
38
  },
39
39
  "peerDependencies": {
@@ -84,5 +84,5 @@
84
84
  "sf-symbols-typescript": "^2.2.0",
85
85
  "typescript": "~6.0.3"
86
86
  },
87
- "gitHead": "943fb630f81d1960d40c333a9933e25f9fea7535"
87
+ "gitHead": "47aa10d415508bd5afbeaaf09a4876ee24702049"
88
88
  }
@@ -15,6 +15,7 @@ import { useJoltForegroundPing } from '../hooks/use_jolt'
15
15
  import { RequestQueryKey } from '../hooks/use_suspense_api'
16
16
  import { emitAuthRefresh } from '../utils/auth_events'
17
17
  import { isResponseLike, ResponseError } from '../utils/response_error'
18
+ import { cancelThrottledRefreshes } from '../utils/throttled_refresh'
18
19
  import { ChatContext, ChatContextValue } from './chat_context'
19
20
 
20
21
  let apiClient: ApiClient | undefined
@@ -65,6 +66,7 @@ export function ApiProvider({ children }: ViewProps) {
65
66
  if (!sessionChanged) return
66
67
 
67
68
  emitAuthRefresh()
69
+ cancelThrottledRefreshes(chatQueryClient)
68
70
 
69
71
  if (chatQueryClient.isFetching()) {
70
72
  chatQueryClient.cancelQueries().then(() => chatQueryClient.invalidateQueries())
@@ -17,6 +17,7 @@ import { ApiResource } from '../types/api_primitives'
17
17
  import { ENV, PartialToken, Session, UNAUTHENTICATED_SESSION_ID } from '../utils'
18
18
  import { StorageAdapter } from '../utils/native_adapters/storage_adapter'
19
19
  import { SessionManager } from '../utils/session_manager'
20
+ import { cancelThrottledRefreshes } from '../utils/throttled_refresh'
20
21
  import { chatQueryClient } from './api_provider'
21
22
 
22
23
  type Sessions = Record<string, string> // Key is session ID
@@ -143,6 +144,8 @@ export function SessionContextProvider({
143
144
  })
144
145
 
145
146
  const handleClearQueryClient = useCallback(() => {
147
+ cancelThrottledRefreshes(chatQueryClient)
148
+ cancelThrottledRefreshes(queryClient)
146
149
  chatQueryClient.clear()
147
150
  queryClient.clear()
148
151
  }, [queryClient])
@@ -0,0 +1,229 @@
1
+ import { QueryClient, QueryClientProvider, useQuery } from '@tanstack/react-query'
2
+ import { act, render } from '@testing-library/react-native'
3
+ import React, { Suspense } from 'react'
4
+ import { buildTestQueryClient } from '../../__utils__/query_client'
5
+ import type { ApiResource, ConversationResource, CurrentPersonResource } from '../../types'
6
+ import { getConversationsRequestArgs } from '../../utils/request/conversation'
7
+ import { cancelThrottledRefreshes, REFRESH_THROTTLE_MS } from '../../utils/throttled_refresh'
8
+ import { getConversationRequestArgs } from '../use_conversation'
9
+ import { useConversationJoltEvents } from '../use_conversation_jolt_events'
10
+ import { useConversationsJoltEvents } from '../use_conversations_jolt_events'
11
+ import { currentPersonQueryKey } from '../use_current_person'
12
+ import { getRequestQueryKey } from '../use_suspense_api'
13
+
14
+ type Handler = (event: unknown) => void
15
+ const mockHandlers = new Map<string, Set<Handler>>()
16
+
17
+ jest.mock('../use_jolt', () => {
18
+ const { useEffect } = jest.requireActual<typeof import('react')>('react')
19
+ return {
20
+ useJoltChannel: (channelName: string) => channelName,
21
+ useJoltEvent: (channel: string, eventName: string, handler: Handler) => {
22
+ useEffect(() => {
23
+ const key = `${channel}:${eventName}`
24
+ const bound = mockHandlers.get(key) ?? new Set<Handler>()
25
+ mockHandlers.set(key, bound)
26
+ bound.add(handler)
27
+ return () => {
28
+ bound.delete(handler)
29
+ }
30
+ }, [channel, eventName, handler])
31
+ },
32
+ }
33
+ })
34
+ jest.mock('../use_api', () => ({ useApiGet: () => ({ data: { id: 1 } }) }))
35
+ jest.mock('../../contexts/conversations_context', () => ({
36
+ useConversationsContext: () => ({ args: {} }),
37
+ }))
38
+
39
+ const mockGet = jest.fn()
40
+ jest.mock('../use_api_client', () => ({ useApiClient: () => ({ chat: { get: mockGet } }) }))
41
+
42
+ const personId = 1
43
+ const conversationId = 7
44
+ const peopleChannel = `chat.people.${personId}`
45
+ const conversationChannel = `chat.conversations.${conversationId}`
46
+ const listQueryKey = getRequestQueryKey(getConversationsRequestArgs({}))
47
+ const conversationQueryKey = getRequestQueryKey(
48
+ getConversationRequestArgs({ conversation_id: conversationId })
49
+ )
50
+ const listUrl = listQueryKey[0]
51
+ const conversationUrl = conversationQueryKey[0]
52
+ const meUrl = currentPersonQueryKey[0]
53
+
54
+ let queryClient: QueryClient
55
+
56
+ const ConversationsList = () => {
57
+ useConversationsJoltEvents()
58
+ return null
59
+ }
60
+
61
+ const ConversationScreen = () => {
62
+ useConversationJoltEvents({ conversationId })
63
+ useQuery({
64
+ queryKey: conversationQueryKey,
65
+ queryFn: () => mockGet({ url: conversationUrl }),
66
+ staleTime: Infinity,
67
+ })
68
+ return null
69
+ }
70
+
71
+ const fire = (channel: string, eventName: string, payload: Record<string, unknown>) => {
72
+ const message = { event: eventName, channel, ...payload }
73
+ mockHandlers.get(`${channel}:${eventName}`)?.forEach(handler => handler(message))
74
+ }
75
+
76
+ const conversationUpdated = () => {
77
+ const data = { data: { id: conversationId, last_message_author_id: 2 } }
78
+ fire(peopleChannel, 'conversation.updated', { data })
79
+ fire(conversationChannel, 'conversation.updated', { data })
80
+ }
81
+
82
+ const conversationRead = () => {
83
+ const data = { data: { id: conversationId, latest_read_message_sort_key: 'z' } }
84
+ fire(peopleChannel, 'conversation.read', { data })
85
+ fire(conversationChannel, 'conversation.read', { data })
86
+ }
87
+
88
+ const streamUserUpdated = (payload: Record<string, unknown>) =>
89
+ fire(peopleChannel, 'STREAM_USER_UPDATED', { data: { data: JSON.stringify(payload) } })
90
+
91
+ const requestsFor = (url: string) =>
92
+ mockGet.mock.calls.filter(([request]) => request.url === url).length
93
+
94
+ const advance = (ms: number) => act(async () => jest.advanceTimersByTime(ms))
95
+
96
+ const seed = () => {
97
+ queryClient.setQueryData<ApiResource<CurrentPersonResource>>(currentPersonQueryKey, {
98
+ data: { type: 'Person', id: personId },
99
+ } as ApiResource<CurrentPersonResource>)
100
+ queryClient.setQueryData<ApiResource<ConversationResource>>(conversationQueryKey, {
101
+ data: { type: 'Conversation', id: conversationId },
102
+ } as ApiResource<ConversationResource>)
103
+ queryClient.setQueryData(listQueryKey, {
104
+ pages: [{ data: [{ type: 'Conversation', id: conversationId }], links: {}, meta: {} }],
105
+ pageParams: [undefined],
106
+ })
107
+ }
108
+
109
+ const mountTwoListsAndTwoScreens = async () => {
110
+ seed()
111
+ render(
112
+ <QueryClientProvider client={queryClient}>
113
+ <Suspense fallback={null}>
114
+ <ConversationsList />
115
+ <ConversationsList />
116
+ <ConversationScreen />
117
+ <ConversationScreen />
118
+ </Suspense>
119
+ </QueryClientProvider>
120
+ )
121
+ await advance(1)
122
+ mockGet.mockClear()
123
+ }
124
+
125
+ beforeEach(async () => {
126
+ jest.useFakeTimers()
127
+ mockHandlers.clear()
128
+ mockGet.mockReset()
129
+ mockGet.mockImplementation(({ url }: { url: string }) => {
130
+ if (url === meUrl) return Promise.resolve({ data: { type: 'Person', id: personId } })
131
+ if (url === conversationUrl) {
132
+ return Promise.resolve({ data: { type: 'Conversation', id: conversationId } })
133
+ }
134
+ return Promise.resolve({ data: [{ type: 'Conversation', id: conversationId }] })
135
+ })
136
+ queryClient = buildTestQueryClient({ defaultOptions: { queries: { gcTime: Infinity } } })
137
+ await mountTwoListsAndTwoScreens()
138
+ })
139
+
140
+ afterEach(() => {
141
+ cancelThrottledRefreshes(queryClient)
142
+ jest.useRealTimers()
143
+ })
144
+
145
+ describe('conversation.updated across two lists and two screens', () => {
146
+ it('collapses 50 events into one request now and one when the window ends', async () => {
147
+ for (let i = 0; i < 50; i++) conversationUpdated()
148
+ await advance(1)
149
+
150
+ expect(requestsFor(listUrl)).toBe(1)
151
+ expect(requestsFor(conversationUrl)).toBe(1)
152
+
153
+ await advance(REFRESH_THROTTLE_MS)
154
+
155
+ expect(requestsFor(listUrl)).toBe(2)
156
+ expect(requestsFor(conversationUrl)).toBe(2)
157
+ })
158
+
159
+ it('refreshes immediately for a lone event and makes no second request', async () => {
160
+ conversationUpdated()
161
+ await advance(1)
162
+
163
+ expect(requestsFor(listUrl)).toBe(1)
164
+ expect(requestsFor(conversationUrl)).toBe(1)
165
+
166
+ await advance(REFRESH_THROTTLE_MS * 2)
167
+
168
+ expect(requestsFor(listUrl)).toBe(1)
169
+ expect(requestsFor(conversationUrl)).toBe(1)
170
+ })
171
+
172
+ it('gives an event inside the window a trailing refresh opened its own trailing refresh', async () => {
173
+ conversationUpdated()
174
+ await advance(1000)
175
+ conversationUpdated()
176
+ await advance(REFRESH_THROTTLE_MS - 1000)
177
+
178
+ expect(requestsFor(listUrl)).toBe(2)
179
+ expect(requestsFor(conversationUrl)).toBe(2)
180
+
181
+ await advance(500)
182
+ conversationUpdated()
183
+ await advance(1)
184
+
185
+ expect(requestsFor(listUrl)).toBe(2)
186
+ expect(requestsFor(conversationUrl)).toBe(2)
187
+
188
+ await advance(REFRESH_THROTTLE_MS)
189
+
190
+ expect(requestsFor(listUrl)).toBe(3)
191
+ expect(requestsFor(conversationUrl)).toBe(3)
192
+ })
193
+ })
194
+
195
+ describe('/me refreshes', () => {
196
+ it('makes no /me request for message.created stream events or conversation.read events', async () => {
197
+ for (let i = 0; i < 50; i++) {
198
+ streamUserUpdated({ event_type: 'message.created' })
199
+ conversationRead()
200
+ }
201
+ await advance(REFRESH_THROTTLE_MS * 2)
202
+
203
+ expect(requestsFor(meUrl)).toBe(0)
204
+ })
205
+
206
+ it('ignores the other read-state event types', async () => {
207
+ streamUserUpdated({ event_type: 'conversation.mark_read' })
208
+ streamUserUpdated({ event_type: 'conversation.mark_unread' })
209
+ streamUserUpdated({ event_type: 'person.mark_all_read' })
210
+ streamUserUpdated({ event_type: 'conversation.destroy' })
211
+ await advance(REFRESH_THROTTLE_MS * 2)
212
+
213
+ expect(requestsFor(meUrl)).toBe(0)
214
+ })
215
+
216
+ it('refetches /me once for app_grant.synced', async () => {
217
+ streamUserUpdated({ event_type: 'app_grant.synced' })
218
+ await advance(REFRESH_THROTTLE_MS * 2)
219
+
220
+ expect(requestsFor(meUrl)).toBe(1)
221
+ })
222
+
223
+ it('refetches /me once for an event with no event_type', async () => {
224
+ streamUserUpdated({})
225
+ await advance(REFRESH_THROTTLE_MS * 2)
226
+
227
+ expect(requestsFor(meUrl)).toBe(1)
228
+ })
229
+ })
@@ -18,6 +18,7 @@ jest.mock('../use_jolt', () => ({
18
18
  jest.mock('../use_api', () => ({ useApiGet: () => ({ data: { id: 1 } }) }))
19
19
  jest.mock('../use_current_person', () => ({
20
20
  currentPersonRequestArgs: {},
21
+ currentPersonQueryKey: ['/me'],
21
22
  useCurrentPersonCache: () => ({ invalidate: jest.fn() }),
22
23
  }))
23
24
 
@@ -1,4 +1,4 @@
1
- import { QueryClientProvider } from '@tanstack/react-query'
1
+ import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
2
2
  import { act, renderHook } from '@testing-library/react-native'
3
3
  import React from 'react'
4
4
  import { buildTestQueryClient } from '../../__utils__/query_client'
@@ -7,27 +7,53 @@ import { getConversationsRequestArgs } from '../../utils/request/conversation'
7
7
  import { useConversationsMarkRead } from '../use_conversations_actions'
8
8
  import { getRequestQueryKey } from '../use_suspense_api'
9
9
 
10
+ const mockPost = jest.fn()
11
+ const mockGet = jest.fn()
10
12
  jest.mock('../use_api_client', () => ({
11
- useApiClient: () => ({
12
- chat: { post: jest.fn().mockResolvedValue({}), get: jest.fn().mockResolvedValue({ data: [] }) },
13
- }),
13
+ useApiClient: () => ({ chat: { post: mockPost, get: mockGet } }),
14
14
  }))
15
15
 
16
+ const conversation = { id: 7, unreadCount: 8 } as ConversationResource
17
+ const listKey = getRequestQueryKey(getConversationsRequestArgs())
18
+ const archivedListKey = getRequestQueryKey(getConversationsRequestArgs({ show_archived: true }))
19
+ let queryClient: QueryClient
20
+
21
+ const wrapper = ({ children }: { children: React.ReactNode }) => (
22
+ <QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
23
+ )
24
+
25
+ const listShows = (key: typeof listKey) => queryClient.getQueryData(key)
26
+
27
+ beforeEach(() => {
28
+ mockPost.mockReset()
29
+ mockGet.mockReset()
30
+ queryClient = buildTestQueryClient({ defaultOptions: { queries: { gcTime: Infinity } } })
31
+ queryClient.setQueryData(listKey, { pages: [{ data: [conversation] }], pageParams: [] })
32
+ queryClient.setQueryData(archivedListKey, { pages: [{ data: [conversation] }], pageParams: [] })
33
+ })
34
+
16
35
  describe('useConversationsMarkRead', () => {
17
36
  it('marks the conversation read in a list outside the current conversations context', async () => {
18
- const conversation = { id: 7, unreadCount: 8 } as ConversationResource
19
- const archivedListKey = getRequestQueryKey(getConversationsRequestArgs({ show_archived: true }))
20
- const queryClient = buildTestQueryClient({ defaultOptions: { queries: { gcTime: Infinity } } })
21
- queryClient.setQueryData(archivedListKey, { pages: [{ data: [conversation] }], pageParams: [] })
22
- const wrapper = ({ children }: { children: React.ReactNode }) => (
23
- <QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
24
- )
37
+ mockPost.mockResolvedValue({ data: { type: 'Conversation', id: 7, unreadCount: 0 } })
25
38
  const { result } = renderHook(() => useConversationsMarkRead({ conversation }), { wrapper })
26
39
 
27
40
  await act(async () => result.current.markRead(true))
28
41
 
29
- expect(queryClient.getQueryData(archivedListKey)).toMatchObject({
42
+ expect(listShows(archivedListKey)).toMatchObject({
30
43
  pages: [{ data: [{ id: 7, unreadCount: 0 }] }],
31
44
  })
32
45
  })
46
+
47
+ it('shows the unread count from the response without refetching the conversation', async () => {
48
+ mockPost.mockResolvedValue({ data: { type: 'Conversation', id: 7, unreadCount: 3 } })
49
+ const { result } = renderHook(() => useConversationsMarkRead({ conversation }), { wrapper })
50
+
51
+ await act(async () => result.current.markRead(false))
52
+
53
+ expect(mockGet).not.toHaveBeenCalled()
54
+ expect(listShows(listKey)).toMatchObject({ pages: [{ data: [{ id: 7, unreadCount: 3 }] }] })
55
+ expect(listShows(archivedListKey)).toMatchObject({
56
+ pages: [{ data: [{ id: 7, unreadCount: 3 }] }],
57
+ })
58
+ })
33
59
  })
@@ -34,12 +34,33 @@ describe('useMarkLatestMessageRead', () => {
34
34
  expect(mockMarkRead).toHaveBeenCalledTimes(1)
35
35
 
36
36
  rerender({ conversation: { ...conversation, unreadCount: 2 }, enabled: false })
37
- act(() => jest.advanceTimersByTime(1000))
37
+ act(() => jest.advanceTimersByTime(3000))
38
38
 
39
39
  expect(mockMarkRead).toHaveBeenCalledTimes(1)
40
40
 
41
41
  rerender({ conversation: { ...conversation, unreadCount: 2 }, enabled: true })
42
- act(() => jest.advanceTimersByTime(1000))
42
+ act(() => jest.advanceTimersByTime(3000))
43
+
44
+ expect(mockMarkRead).toHaveBeenCalledTimes(2)
45
+ jest.useRealTimers()
46
+ })
47
+
48
+ it('collapses unread bumps inside three seconds into one trailing mark-read', () => {
49
+ jest.useFakeTimers()
50
+ const { rerender } = renderHook<void, { conversation: ConversationResource }>(
51
+ props => useMarkLatestMessageRead({ ...props, messages: [] }),
52
+ { initialProps: { conversation } }
53
+ )
54
+ expect(mockMarkRead).toHaveBeenCalledTimes(1)
55
+
56
+ for (let i = 0; i < 3; i++) {
57
+ rerender({ conversation: { ...conversation, unreadCount: 0 } })
58
+ act(() => jest.advanceTimersByTime(500))
59
+ rerender({ conversation: { ...conversation, unreadCount: 1 } })
60
+ }
61
+ expect(mockMarkRead).toHaveBeenCalledTimes(1)
62
+
63
+ act(() => jest.advanceTimersByTime(3000))
43
64
 
44
65
  expect(mockMarkRead).toHaveBeenCalledTimes(2)
45
66
  jest.useRealTimers()
@@ -3,6 +3,7 @@ import { useCallback, useMemo } from 'react'
3
3
  import { ApiResource, ConversationResource } from '../types'
4
4
  import { JoltConversationEvent, JoltReactionEvent } from '../types/jolt_events'
5
5
  import { completeMessageCreationConversationTracking } from '../utils/performance_tracking'
6
+ import { throttledRefresh } from '../utils/throttled_refresh'
6
7
  import { useApiClient } from './use_api_client'
7
8
  import { getConversationRequestArgs } from './use_conversation'
8
9
  import { useCurrentPerson } from './use_current_person'
@@ -54,7 +55,7 @@ export function useConversationJoltEvents({ conversationId }: Props) {
54
55
  }
55
56
  })
56
57
 
57
- queryClient.invalidateQueries({ queryKey })
58
+ throttledRefresh(queryClient, queryKey, e, () => queryClient.invalidateQueries({ queryKey }))
58
59
  },
59
60
  [queryClient, queryKey, currentPersonId, apiClient]
60
61
  )
@@ -17,7 +17,7 @@ export const useConversationsMarkRead = ({
17
17
  const queryClient = useQueryClient()
18
18
  const { args } = useConversationsContext()
19
19
  const currentPersonCache = useCurrentPersonCache()
20
- const { updateInAllLists, invalidateAllLists, fetchUpdate } = useConversationsCache(args)
20
+ const { updateInAllLists, invalidateAllLists } = useConversationsCache(args)
21
21
  const conversationQueryKey = getRequestQueryKey(
22
22
  getConversationRequestArgs({ conversation_id: conversation.id })
23
23
  )
@@ -48,13 +48,16 @@ export const useConversationsMarkRead = ({
48
48
  mutationFn: async (read: boolean) => {
49
49
  const action = read ? 'mark_read' : 'mark_unread'
50
50
 
51
- return apiClient.chat.post({
51
+ return apiClient.chat.post<ApiResource<ConversationResource>>({
52
52
  url: `/me/conversations/${conversation.id}/${action}`,
53
53
  data: { data: { type: '', attributes: {} }, fields: { Conversation: 'unread_count,id' } },
54
54
  })
55
55
  },
56
- onSuccess: () => {
57
- fetchUpdate(conversation)
56
+ onSuccess: response => {
57
+ const unreadCount = response.data?.unreadCount
58
+ if (unreadCount === undefined) return
59
+
60
+ updateInAllLists(conversation.id, { unreadCount })
58
61
  },
59
62
  onError: () => {
60
63
  Alert.alert('Oops', 'Something went wrong updating this conversation, please try again')
@@ -2,7 +2,6 @@ import { InfiniteData, useQueryClient } from '@tanstack/react-query'
2
2
  import { ApiCollection, ConversationResource } from '../types'
3
3
  import {
4
4
  deleteRecordInPagesData,
5
- updateRecordInPagesData,
6
5
  updateAllRecordsInPagesData,
7
6
  updateOrCreateRecordInPagesData,
8
7
  } from '../utils'
@@ -44,20 +43,6 @@ export function useConversationsCache(args?: Partial<ConversationRequestArgs>) {
44
43
  )
45
44
  }
46
45
 
47
- const updateOnly = async (conversation: ConversationResource) => {
48
- if (!conversation.id) return
49
-
50
- queryClient.setQueryData<QueryData>(conversationQueryKey, prev =>
51
- updateRecordInPagesData({
52
- data: prev,
53
- record: conversation,
54
- processRecord: (record, current) => {
55
- return { ...current, ...record }
56
- },
57
- })
58
- )
59
- }
60
-
61
46
  const updateAll = async (update: Partial<ConversationResource>) => {
62
47
  queryClient.setQueryData<QueryData>(conversationQueryKey, prev =>
63
48
  updateAllRecordsInPagesData({
@@ -92,13 +77,6 @@ export function useConversationsCache(args?: Partial<ConversationRequestArgs>) {
92
77
  )
93
78
  }
94
79
 
95
- const fetchAndUpdate = async ({ id }: { id: number }) => {
96
- const conversation = await fetchConversation(id).catch(() => undefined)
97
- if (!conversation) return
98
-
99
- updateOnly(conversation)
100
- }
101
-
102
80
  const fetchAndSync = async ({ id }: { id: number }) => {
103
81
  let conversation: ConversationResource | undefined
104
82
  try {
@@ -115,10 +93,10 @@ export function useConversationsCache(args?: Partial<ConversationRequestArgs>) {
115
93
  }
116
94
 
117
95
  return {
96
+ queryKey: conversationQueryKey,
118
97
  create: updateOrCreate,
119
98
  destroy: handleConversationDestroy,
120
99
  fetchSync: fetchAndSync,
121
- fetchUpdate: fetchAndUpdate,
122
100
  invalidate: () => queryClient.invalidateQueries({ queryKey: conversationQueryKey }),
123
101
  invalidateAllLists,
124
102
  update: updateOrCreate,
@@ -1,37 +1,48 @@
1
+ import { useQueryClient } from '@tanstack/react-query'
1
2
  import { useConversationsContext } from '../contexts/conversations_context'
2
3
  import { CurrentPersonResource } from '../types'
3
- import { JoltConversationEvent } from '../types/jolt_events'
4
+ import { JoltConversationEvent, StreamUserUpdatedEvent } from '../types/jolt_events'
5
+ import { parseStreamUserEventType } from '../utils/jolt/parse_stream_user_event_type'
4
6
  import { completeMessageCreationConversationTracking } from '../utils/performance_tracking'
7
+ import { throttledRefresh } from '../utils/throttled_refresh'
5
8
  import { useApiGet } from './use_api'
6
9
  import { useApiClient } from './use_api_client'
7
10
  import { useConversationsCache } from './use_conversations_cache'
8
- import { currentPersonRequestArgs, useCurrentPersonCache } from './use_current_person'
11
+ import {
12
+ currentPersonQueryKey,
13
+ currentPersonRequestArgs,
14
+ useCurrentPersonCache,
15
+ } from './use_current_person'
9
16
  import { useJoltChannel, useJoltEvent } from './use_jolt'
10
17
 
11
18
  const useCurrentPerson = () => {
12
19
  return useApiGet<CurrentPersonResource>(currentPersonRequestArgs)
13
20
  }
14
21
 
22
+ const refreshesCurrentPerson = (event: StreamUserUpdatedEvent) => {
23
+ const eventType = parseStreamUserEventType(event)
24
+ return eventType === undefined || eventType === 'app_grant.synced'
25
+ }
26
+
15
27
  export function useConversationsJoltEvents() {
16
28
  const { data: currentPerson } = useCurrentPerson()
17
29
  const { args } = useConversationsContext()
18
30
  const cache = useConversationsCache(args)
19
31
  const currentPersonCache = useCurrentPersonCache()
20
32
  const apiClient = useApiClient()
33
+ const queryClient = useQueryClient()
21
34
  const enabled = currentPerson?.id ? true : false
22
35
  const joltChannel = useJoltChannel(`chat.people.${currentPerson?.id}`, enabled)
23
36
 
24
37
  useJoltEvent(joltChannel, 'conversation.updated', (e: JoltConversationEvent) => {
25
- if (
26
- e.data.data.last_message_idempotent_key &&
27
- e.data.data.last_message_author_id === currentPerson?.id
28
- ) {
38
+ const { id, last_message_idempotent_key, last_message_author_id } = e.data.data
39
+ if (last_message_idempotent_key && last_message_author_id === currentPerson?.id) {
29
40
  completeMessageCreationConversationTracking({
30
41
  apiClient,
31
- idempotentKey: e.data.data.last_message_idempotent_key,
42
+ idempotentKey: last_message_idempotent_key,
32
43
  })
33
44
  }
34
- cache.fetchSync({ id: e.data.data.id })
45
+ throttledRefresh(queryClient, [...cache.queryKey, id], e, () => cache.fetchSync({ id }))
35
46
  })
36
47
  useJoltEvent(joltChannel, 'conversation.created', (e: JoltConversationEvent) =>
37
48
  cache.fetchSync({ id: e.data.data.id })
@@ -40,6 +51,9 @@ export function useConversationsJoltEvents() {
40
51
  cache.destroy({ id: e.data.data.id })
41
52
  )
42
53
 
43
- useJoltEvent(joltChannel, 'STREAM_USER_UPDATED', currentPersonCache.invalidate) // Would be nice to have a non-stream chat event
44
- useJoltEvent(joltChannel, 'conversation.read', currentPersonCache.invalidate)
54
+ useJoltEvent(joltChannel, 'STREAM_USER_UPDATED', (e: StreamUserUpdatedEvent) => {
55
+ if (!refreshesCurrentPerson(e)) return
56
+
57
+ throttledRefresh(queryClient, currentPersonQueryKey, e, currentPersonCache.invalidate)
58
+ })
45
59
  }
@@ -1,6 +1,7 @@
1
- import { debounce } from 'lodash'
1
+ import { throttle } from 'lodash'
2
2
  import { useEffect, useMemo, useRef } from 'react'
3
3
  import { ConversationResource, MessageResource } from '../types'
4
+ import { REFRESH_THROTTLE_MS } from '../utils/throttled_refresh'
4
5
  import { useAppState } from './use_app_state'
5
6
  import { useConversationsMarkRead } from './use_conversations_actions'
6
7
 
@@ -13,8 +14,8 @@ interface Props {
13
14
  export function useMarkLatestMessageRead({ conversation, enabled = true }: Props) {
14
15
  const firedOnce = useRef<boolean>(false)
15
16
  const { markRead } = useConversationsMarkRead({ conversation })
16
- const debouncedMarkRead = useMemo(
17
- () => debounce(markRead, 1000, { leading: true, trailing: true }),
17
+ const throttledMarkRead = useMemo(
18
+ () => throttle(markRead, REFRESH_THROTTLE_MS, { leading: true, trailing: true }),
18
19
  [markRead]
19
20
  )
20
21
  const unreadCount = conversation.unreadCount
@@ -30,6 +31,6 @@ export function useMarkLatestMessageRead({ conversation, enabled = true }: Props
30
31
 
31
32
  firedOnce.current = true
32
33
 
33
- debouncedMarkRead(true)
34
- }, [debouncedMarkRead, isActive, shouldMarkRead, unreadReaction])
34
+ throttledMarkRead(true)
35
+ }, [throttledMarkRead, isActive, shouldMarkRead, unreadReaction])
35
36
  }