@planningcenter/chat-react-native 4.8.0-rc.0 → 4.8.0-rc.2
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/contexts/api_provider.d.ts.map +1 -1
- package/build/contexts/api_provider.js +2 -0
- package/build/contexts/api_provider.js.map +1 -1
- package/build/contexts/chat_context.d.ts +0 -2
- package/build/contexts/chat_context.d.ts.map +1 -1
- package/build/contexts/chat_context.js +16 -93
- package/build/contexts/chat_context.js.map +1 -1
- package/build/contexts/session_context.d.ts.map +1 -1
- package/build/contexts/session_context.js +3 -0
- package/build/contexts/session_context.js.map +1 -1
- package/build/hooks/groups/use_group_chat_conversation_payload.d.ts +11 -1
- package/build/hooks/groups/use_group_chat_conversation_payload.d.ts.map +1 -1
- package/build/hooks/groups/use_group_chat_conversation_payload.js +92 -47
- package/build/hooks/groups/use_group_chat_conversation_payload.js.map +1 -1
- package/build/hooks/groups/use_group_members_for_new_conversation.d.ts +27 -25
- package/build/hooks/groups/use_group_members_for_new_conversation.d.ts.map +1 -1
- package/build/hooks/groups/use_group_members_for_new_conversation.js +125 -110
- package/build/hooks/groups/use_group_members_for_new_conversation.js.map +1 -1
- package/build/hooks/groups/use_groups_conversation_create.d.ts.map +1 -1
- package/build/hooks/groups/use_groups_conversation_create.js +39 -31
- package/build/hooks/groups/use_groups_conversation_create.js.map +1 -1
- package/build/hooks/groups/use_groups_proxy.d.ts +2 -0
- package/build/hooks/groups/use_groups_proxy.d.ts.map +1 -0
- package/build/hooks/groups/use_groups_proxy.js +18 -0
- package/build/hooks/groups/use_groups_proxy.js.map +1 -0
- package/build/hooks/use_conversation_jolt_events.d.ts.map +1 -1
- package/build/hooks/use_conversation_jolt_events.js +3 -2
- package/build/hooks/use_conversation_jolt_events.js.map +1 -1
- package/build/hooks/use_conversations_actions.d.ts +9 -9
- package/build/hooks/use_conversations_actions.d.ts.map +1 -1
- package/build/hooks/use_conversations_actions.js +12 -7
- package/build/hooks/use_conversations_actions.js.map +1 -1
- package/build/hooks/use_conversations_cache.d.ts +1 -3
- package/build/hooks/use_conversations_cache.d.ts.map +1 -1
- package/build/hooks/use_conversations_cache.js +79 -124
- package/build/hooks/use_conversations_cache.js.map +1 -1
- package/build/hooks/use_conversations_jolt_events.d.ts.map +1 -1
- package/build/hooks/use_conversations_jolt_events.js +47 -20
- package/build/hooks/use_conversations_jolt_events.js.map +1 -1
- package/build/hooks/use_features.d.ts +1 -0
- package/build/hooks/use_features.d.ts.map +1 -1
- package/build/hooks/use_features.js +1 -0
- package/build/hooks/use_features.js.map +1 -1
- package/build/hooks/use_groups_groups.d.ts.map +1 -1
- package/build/hooks/use_groups_groups.js +25 -9
- package/build/hooks/use_groups_groups.js.map +1 -1
- package/build/hooks/use_mark_latest_message_read.d.ts.map +1 -1
- package/build/hooks/use_mark_latest_message_read.js +5 -4
- package/build/hooks/use_mark_latest_message_read.js.map +1 -1
- package/build/hooks/use_new_conversation_from_filter.d.ts.map +1 -1
- package/build/hooks/use_new_conversation_from_filter.js +11 -1
- package/build/hooks/use_new_conversation_from_filter.js.map +1 -1
- package/build/hooks/use_product_analytics.d.ts.map +1 -1
- package/build/hooks/use_product_analytics.js +93 -75
- package/build/hooks/use_product_analytics.js.map +1 -1
- package/build/screens/conversation_new/components/groups_form.d.ts.map +1 -1
- package/build/screens/conversation_new/components/groups_form.js +96 -93
- package/build/screens/conversation_new/components/groups_form.js.map +1 -1
- package/build/screens/get_help_screen.d.ts.map +1 -1
- package/build/screens/get_help_screen.js +4 -20
- package/build/screens/get_help_screen.js.map +1 -1
- package/build/types/jolt_events/index.d.ts +2 -0
- package/build/types/jolt_events/index.d.ts.map +1 -1
- package/build/types/jolt_events/index.js.map +1 -1
- package/build/types/jolt_events/person_events.d.ts +9 -0
- package/build/types/jolt_events/person_events.d.ts.map +1 -0
- package/build/types/jolt_events/person_events.js +2 -0
- package/build/types/jolt_events/person_events.js.map +1 -0
- package/build/types/resources/groups/groups_group_resource.d.ts +1 -1
- package/build/types/resources/groups/groups_group_resource.d.ts.map +1 -1
- package/build/types/resources/groups/groups_group_resource.js.map +1 -1
- package/build/types/resources/groups/groups_membership_resource.d.ts +11 -0
- package/build/types/resources/groups/groups_membership_resource.d.ts.map +1 -0
- package/build/types/resources/groups/groups_membership_resource.js +2 -0
- package/build/types/resources/groups/groups_membership_resource.js.map +1 -0
- package/build/types/resources/groups/index.d.ts +1 -0
- package/build/types/resources/groups/index.d.ts.map +1 -1
- package/build/types/resources/groups/index.js +1 -0
- package/build/types/resources/groups/index.js.map +1 -1
- package/build/utils/jolt/parse_stream_user_event_type.d.ts +3 -0
- package/build/utils/jolt/parse_stream_user_event_type.d.ts.map +1 -0
- package/build/utils/jolt/parse_stream_user_event_type.js +9 -0
- package/build/utils/jolt/parse_stream_user_event_type.js.map +1 -0
- package/build/utils/native_adapters/linking.d.ts.map +1 -1
- package/build/utils/native_adapters/linking.js +48 -2
- package/build/utils/native_adapters/linking.js.map +1 -1
- package/build/utils/product_analytics_token.d.ts +12 -0
- package/build/utils/product_analytics_token.d.ts.map +1 -0
- package/build/utils/product_analytics_token.js +84 -0
- package/build/utils/product_analytics_token.js.map +1 -0
- package/build/utils/throttled_refresh.d.ts +7 -0
- package/build/utils/throttled_refresh.d.ts.map +1 -0
- package/build/utils/throttled_refresh.js +42 -0
- package/build/utils/throttled_refresh.js.map +1 -0
- package/package.json +2 -2
- package/src/__tests__/hooks/use_group_chat_conversation_payload.test.tsx +31 -0
- package/src/contexts/api_provider.tsx +2 -0
- package/src/contexts/chat_context.tsx +2 -58
- package/src/contexts/session_context.tsx +3 -0
- package/src/hooks/__tests__/jolt_refresh_throttling.test.tsx +229 -0
- package/src/hooks/__tests__/use_conversations_jolt_events.test.tsx +1 -0
- package/src/hooks/__tests__/use_conversations_mark_read.test.tsx +38 -12
- package/src/hooks/__tests__/use_mark_latest_message_read.test.tsx +23 -2
- package/src/hooks/__tests__/use_product_analytics.test.tsx +304 -0
- package/src/hooks/groups/use_group_chat_conversation_payload.ts +30 -12
- package/src/hooks/groups/use_group_members_for_new_conversation.ts +49 -18
- package/src/hooks/groups/use_groups_conversation_create.ts +10 -14
- package/src/hooks/groups/use_groups_proxy.ts +6 -0
- package/src/hooks/use_conversation_jolt_events.ts +2 -1
- package/src/hooks/use_conversations_actions.ts +7 -4
- package/src/hooks/use_conversations_cache.ts +1 -23
- package/src/hooks/use_conversations_jolt_events.ts +24 -10
- package/src/hooks/use_features.ts +1 -0
- package/src/hooks/use_groups_groups.ts +21 -16
- package/src/hooks/use_mark_latest_message_read.ts +6 -5
- package/src/hooks/use_new_conversation_from_filter.ts +13 -5
- package/src/hooks/use_product_analytics.ts +74 -41
- package/src/screens/conversation_new/components/groups_form.tsx +11 -9
- package/src/screens/get_help_screen.tsx +4 -18
- package/src/types/jolt_events/index.ts +2 -0
- package/src/types/jolt_events/person_events.ts +16 -0
- package/src/types/resources/groups/groups_group_resource.ts +1 -1
- package/src/types/resources/groups/groups_membership_resource.ts +10 -0
- package/src/types/resources/groups/index.ts +1 -0
- package/src/utils/__tests__/throttled_refresh.test.ts +101 -0
- package/src/utils/jolt/__tests__/parse_stream_user_event_type.test.ts +27 -0
- package/src/utils/jolt/parse_stream_user_event_type.ts +16 -0
- package/src/utils/native_adapters/__tests__/linking.test.ts +60 -4
- package/src/utils/native_adapters/linking.ts +50 -2
- package/src/utils/product_analytics_token.ts +120 -0
- package/src/utils/throttled_refresh.ts +62 -0
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
import { currentPersonQueryKey } from '../hooks/use_current_person';
|
|
2
|
+
import { Client } from './client';
|
|
3
|
+
import { Storage } from './native_adapters';
|
|
4
|
+
import { ONE_HOUR, toMs } from './time';
|
|
5
|
+
import { Uri } from './uri';
|
|
6
|
+
export const TOKEN_EXPIRY_TIME = toMs(7 * 24, 'hours');
|
|
7
|
+
const EXPIRY_MARGIN = ONE_HOUR;
|
|
8
|
+
|
|
9
|
+
// One slot per environment, tagged with the person it belongs to. Keying on
|
|
10
|
+
// session.id would miss on every access-token refresh and leave orphaned entries.
|
|
11
|
+
export const productAnalyticsStorageKey = session => `product-analytics-token:${session.env}`;
|
|
12
|
+
export const productAnalyticsQueryKey = session => ['product-analytics-token', session.env, session.id];
|
|
13
|
+
const renewalTime = config => config.expiresAt - EXPIRY_MARGIN;
|
|
14
|
+
const isStoredConfig = value => typeof value === 'object' && value !== null && typeof value.token === 'string' && typeof value.endpoint === 'string' && typeof value.expiresAt === 'number' && typeof value.personId === 'string';
|
|
15
|
+
async function readStoredConfig(key) {
|
|
16
|
+
try {
|
|
17
|
+
const raw = await Storage.getItem(key);
|
|
18
|
+
if (!raw) return undefined;
|
|
19
|
+
const parsed = JSON.parse(raw);
|
|
20
|
+
return isStoredConfig(parsed) ? parsed : undefined;
|
|
21
|
+
} catch {
|
|
22
|
+
return undefined;
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
function writeStoredConfig(key, config) {
|
|
26
|
+
return Storage.setItem(key, JSON.stringify(config)).catch(() => {});
|
|
27
|
+
}
|
|
28
|
+
function requestConfig(session, personId) {
|
|
29
|
+
const uri = new Uri({
|
|
30
|
+
session
|
|
31
|
+
});
|
|
32
|
+
const client = new Client({
|
|
33
|
+
root: uri.api('/chat/v2'),
|
|
34
|
+
defaultHeaders: uri.headers,
|
|
35
|
+
version: '2018-11-01'
|
|
36
|
+
});
|
|
37
|
+
return client.post({
|
|
38
|
+
url: '/me/product_analytics_authorize',
|
|
39
|
+
data: {
|
|
40
|
+
data: {
|
|
41
|
+
type: 'ProductAnalyticsToken',
|
|
42
|
+
attributes: {}
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
}).then(res => ({
|
|
46
|
+
token: res.data.id,
|
|
47
|
+
endpoint: res.data.url,
|
|
48
|
+
metadata: res.data.metadata,
|
|
49
|
+
expiresAt: Date.now() + TOKEN_EXPIRY_TIME,
|
|
50
|
+
personId
|
|
51
|
+
}));
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
// The chat screens that publish events already load /me, and the package's query
|
|
55
|
+
// client is cleared whenever the access token changes, so this is normally a cache hit.
|
|
56
|
+
async function currentPersonId(queryClient) {
|
|
57
|
+
const {
|
|
58
|
+
data
|
|
59
|
+
} = await queryClient.ensureQueryData({
|
|
60
|
+
queryKey: currentPersonQueryKey
|
|
61
|
+
});
|
|
62
|
+
return String(data.id);
|
|
63
|
+
}
|
|
64
|
+
async function loadConfig(queryClient, session) {
|
|
65
|
+
const personId = await currentPersonId(queryClient);
|
|
66
|
+
const key = productAnalyticsStorageKey(session);
|
|
67
|
+
const stored = await readStoredConfig(key);
|
|
68
|
+
if (stored && stored.personId === personId && renewalTime(stored) > Date.now()) return stored;
|
|
69
|
+
const config = await requestConfig(session, personId);
|
|
70
|
+
await writeStoredConfig(key, config);
|
|
71
|
+
return config;
|
|
72
|
+
}
|
|
73
|
+
export function fetchProductAnalyticsConfig(queryClient, session) {
|
|
74
|
+
return queryClient.fetchQuery({
|
|
75
|
+
queryKey: productAnalyticsQueryKey(session),
|
|
76
|
+
queryFn: () => loadConfig(queryClient, session),
|
|
77
|
+
staleTime: ({
|
|
78
|
+
state
|
|
79
|
+
}) => state.data ? Math.max(0, renewalTime(state.data) - state.dataUpdatedAt) : 0,
|
|
80
|
+
gcTime: TOKEN_EXPIRY_TIME,
|
|
81
|
+
retry: false
|
|
82
|
+
});
|
|
83
|
+
}
|
|
84
|
+
//# sourceMappingURL=product_analytics_token.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"product_analytics_token.js","names":["currentPersonQueryKey","Client","Storage","ONE_HOUR","toMs","Uri","TOKEN_EXPIRY_TIME","EXPIRY_MARGIN","productAnalyticsStorageKey","session","env","productAnalyticsQueryKey","id","renewalTime","config","expiresAt","isStoredConfig","value","token","endpoint","personId","readStoredConfig","key","raw","getItem","undefined","parsed","JSON","parse","writeStoredConfig","setItem","stringify","catch","requestConfig","uri","client","root","api","defaultHeaders","headers","version","post","url","data","type","attributes","then","res","metadata","Date","now","currentPersonId","queryClient","ensureQueryData","queryKey","String","loadConfig","stored","fetchProductAnalyticsConfig","fetchQuery","queryFn","staleTime","state","Math","max","dataUpdatedAt","gcTime","retry"],"sources":["../../src/utils/product_analytics_token.ts"],"sourcesContent":["import { QueryClient } from '@tanstack/react-query'\nimport { currentPersonQueryKey } from '../hooks/use_current_person'\nimport { ApiResource, CurrentPersonResource } from '../types'\nimport { ProductAnalyticsConfig } from '../types/product_analytics'\nimport { Client } from './client'\nimport { Storage } from './native_adapters'\nimport { Session } from './session'\nimport { ONE_HOUR, toMs } from './time'\nimport { Uri } from './uri'\n\ninterface ProductAnalyticsTokenResponse {\n type: 'ProductAnalyticsToken'\n id: string\n url: string\n metadata: Record<string, unknown>\n}\n\nexport interface StoredProductAnalyticsConfig extends ProductAnalyticsConfig {\n expiresAt: number\n personId: string\n}\n\nexport const TOKEN_EXPIRY_TIME = toMs(7 * 24, 'hours')\nconst EXPIRY_MARGIN = ONE_HOUR\n\n// One slot per environment, tagged with the person it belongs to. Keying on\n// session.id would miss on every access-token refresh and leave orphaned entries.\nexport const productAnalyticsStorageKey = (session: Session) =>\n `product-analytics-token:${session.env}`\n\nexport const productAnalyticsQueryKey = (session: Session) => [\n 'product-analytics-token',\n session.env,\n session.id,\n]\n\nconst renewalTime = (config: StoredProductAnalyticsConfig) => config.expiresAt - EXPIRY_MARGIN\n\nconst isStoredConfig = (value: unknown): value is StoredProductAnalyticsConfig =>\n typeof value === 'object' &&\n value !== null &&\n typeof (value as StoredProductAnalyticsConfig).token === 'string' &&\n typeof (value as StoredProductAnalyticsConfig).endpoint === 'string' &&\n typeof (value as StoredProductAnalyticsConfig).expiresAt === 'number' &&\n typeof (value as StoredProductAnalyticsConfig).personId === 'string'\n\nasync function readStoredConfig(key: string): Promise<StoredProductAnalyticsConfig | undefined> {\n try {\n const raw = await Storage.getItem(key)\n if (!raw) return undefined\n\n const parsed: unknown = JSON.parse(raw)\n return isStoredConfig(parsed) ? parsed : undefined\n } catch {\n return undefined\n }\n}\n\nfunction writeStoredConfig(key: string, config: StoredProductAnalyticsConfig): Promise<void> {\n return Storage.setItem(key, JSON.stringify(config)).catch(() => {})\n}\n\nfunction requestConfig(session: Session, personId: string): Promise<StoredProductAnalyticsConfig> {\n const uri = new Uri({ session })\n const client = new Client({\n root: uri.api('/chat/v2'),\n defaultHeaders: uri.headers,\n version: '2018-11-01',\n })\n\n return client\n .post<ApiResource<ProductAnalyticsTokenResponse>>({\n url: '/me/product_analytics_authorize',\n data: { data: { type: 'ProductAnalyticsToken', attributes: {} } },\n })\n .then(res => ({\n token: res.data.id,\n endpoint: res.data.url,\n metadata: res.data.metadata,\n expiresAt: Date.now() + TOKEN_EXPIRY_TIME,\n personId,\n }))\n}\n\n// The chat screens that publish events already load /me, and the package's query\n// client is cleared whenever the access token changes, so this is normally a cache hit.\nasync function currentPersonId(queryClient: QueryClient): Promise<string> {\n const { data } = await queryClient.ensureQueryData<ApiResource<CurrentPersonResource>>({\n queryKey: currentPersonQueryKey,\n })\n return String(data.id)\n}\n\nasync function loadConfig(\n queryClient: QueryClient,\n session: Session\n): Promise<StoredProductAnalyticsConfig> {\n const personId = await currentPersonId(queryClient)\n const key = productAnalyticsStorageKey(session)\n const stored = await readStoredConfig(key)\n if (stored && stored.personId === personId && renewalTime(stored) > Date.now()) return stored\n\n const config = await requestConfig(session, personId)\n await writeStoredConfig(key, config)\n return config\n}\n\nexport function fetchProductAnalyticsConfig(\n queryClient: QueryClient,\n session: Session\n): Promise<StoredProductAnalyticsConfig> {\n return queryClient.fetchQuery({\n queryKey: productAnalyticsQueryKey(session),\n queryFn: () => loadConfig(queryClient, session),\n staleTime: ({ state }) =>\n state.data ? Math.max(0, renewalTime(state.data) - state.dataUpdatedAt) : 0,\n gcTime: TOKEN_EXPIRY_TIME,\n retry: false,\n })\n}\n"],"mappings":"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","ignoreList":[]}
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import { QueryClient, QueryKey } from '@tanstack/react-query';
|
|
2
|
+
export declare const REFRESH_THROTTLE_MS = 3000;
|
|
3
|
+
type Refresh = () => unknown;
|
|
4
|
+
export declare const throttledRefresh: (queryClient: QueryClient, key: QueryKey, event: object, refresh: Refresh) => void;
|
|
5
|
+
export declare const cancelThrottledRefreshes: (queryClient: QueryClient) => void;
|
|
6
|
+
export {};
|
|
7
|
+
//# sourceMappingURL=throttled_refresh.d.ts.map
|
|
@@ -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.8.0-rc.
|
|
3
|
+
"version": "4.8.0-rc.2",
|
|
4
4
|
"description": "",
|
|
5
5
|
"repository": {
|
|
6
6
|
"type": "git",
|
|
@@ -84,5 +84,5 @@
|
|
|
84
84
|
"sf-symbols-typescript": "^2.2.0",
|
|
85
85
|
"typescript": "~6.0.3"
|
|
86
86
|
},
|
|
87
|
-
"gitHead": "
|
|
87
|
+
"gitHead": "4330cc04c3056e5b57682030b8d0ef7e7926b1de"
|
|
88
88
|
}
|
|
@@ -5,6 +5,11 @@ import { buildTestQueryClient } from '../../__utils__/query_client'
|
|
|
5
5
|
import { useGroupChatConversationPayload } from '../../hooks/groups/use_group_chat_conversation_payload'
|
|
6
6
|
import * as useApiClientModule from '../../hooks/use_api_client'
|
|
7
7
|
|
|
8
|
+
const mockGroupsProxy = jest.fn(() => false)
|
|
9
|
+
jest.mock('../../hooks/groups/use_groups_proxy', () => ({
|
|
10
|
+
useGroupsProxy: () => mockGroupsProxy(),
|
|
11
|
+
}))
|
|
12
|
+
|
|
8
13
|
const mockGroupsPost = (impl: jest.Mock) => {
|
|
9
14
|
jest.spyOn(useApiClientModule, 'useApiClient').mockReturnValue({
|
|
10
15
|
groups: { post: impl },
|
|
@@ -22,6 +27,7 @@ const resolveWith = (value: string) =>
|
|
|
22
27
|
describe('useGroupChatConversationPayload', () => {
|
|
23
28
|
afterEach(() => {
|
|
24
29
|
jest.restoreAllMocks()
|
|
30
|
+
mockGroupsProxy.mockReturnValue(false)
|
|
25
31
|
})
|
|
26
32
|
|
|
27
33
|
it('refetches on mount even when a fresh payload is already cached', async () => {
|
|
@@ -47,4 +53,29 @@ describe('useGroupChatConversationPayload', () => {
|
|
|
47
53
|
await waitFor(() => expect(post).toHaveBeenCalledTimes(1))
|
|
48
54
|
await waitFor(() => expect(result.current.payload).toBe('fresh'))
|
|
49
55
|
})
|
|
56
|
+
|
|
57
|
+
it('asks Chat for the payload when Groups loads through Chat', async () => {
|
|
58
|
+
mockGroupsProxy.mockReturnValue(true)
|
|
59
|
+
const post = resolveWith('proxied')
|
|
60
|
+
const groupsPost = jest.fn()
|
|
61
|
+
jest.spyOn(useApiClientModule, 'useApiClient').mockReturnValue({
|
|
62
|
+
chat: { post },
|
|
63
|
+
groups: { post: groupsPost },
|
|
64
|
+
} as unknown as ReturnType<typeof useApiClientModule.useApiClient>)
|
|
65
|
+
const queryClient = buildTestQueryClient()
|
|
66
|
+
const wrapper = ({ children }: { children: React.ReactNode }) => (
|
|
67
|
+
<QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
|
|
68
|
+
)
|
|
69
|
+
|
|
70
|
+
const { result } = renderHook(() => useGroupChatConversationPayload({ groupId: 1 }), {
|
|
71
|
+
wrapper,
|
|
72
|
+
})
|
|
73
|
+
|
|
74
|
+
await waitFor(() => expect(result.current.payload).toBe('proxied'))
|
|
75
|
+
expect(post).toHaveBeenCalledWith({
|
|
76
|
+
url: '/me/groups_groups/1/chat_conversation_payload',
|
|
77
|
+
data: { data: { type: 'GroupsChatConversationPayload', attributes: { title: '' } } },
|
|
78
|
+
})
|
|
79
|
+
expect(groupsPost).not.toHaveBeenCalled()
|
|
80
|
+
})
|
|
50
81
|
})
|
|
@@ -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())
|
|
@@ -1,12 +1,10 @@
|
|
|
1
|
-
import { useQuery } from '@tanstack/react-query'
|
|
2
1
|
import { merge } from 'lodash'
|
|
3
2
|
import React, { createContext, useMemo } from 'react'
|
|
4
3
|
import { ColorSchemeName, useColorScheme } from 'react-native'
|
|
5
4
|
import { AgeCheckContactInfo } from '../screens/age_check/screen_props'
|
|
6
|
-
import {
|
|
5
|
+
import { DeepPartial } from '../types'
|
|
7
6
|
import { FailedResponse } from '../types'
|
|
8
|
-
import {
|
|
9
|
-
import { Client, ENV, OauthType, PartialToken, Session, Uri } from '../utils'
|
|
7
|
+
import { ENV, OauthType, PartialToken, Session } from '../utils'
|
|
10
8
|
import { setLiquidGlassCapability } from '../utils/liquid_glass'
|
|
11
9
|
import { ChatTheme, defaultTheme, DefaultTheme } from '../utils/theme'
|
|
12
10
|
|
|
@@ -27,7 +25,6 @@ export interface ChatContextValue extends Omit<ChatProviderProps, 'theme'> {
|
|
|
27
25
|
session: Session
|
|
28
26
|
theme: ChatTheme
|
|
29
27
|
onAgeDisqualification: (params: AgeCheckContactInfo) => void
|
|
30
|
-
productAnalyticsConfig: ProductAnalyticsConfig | undefined
|
|
31
28
|
}
|
|
32
29
|
|
|
33
30
|
export const ChatContext = createContext<ChatContextValue>({
|
|
@@ -40,7 +37,6 @@ export const ChatContext = createContext<ChatContextValue>({
|
|
|
40
37
|
token: undefined,
|
|
41
38
|
edgeToEdge: true,
|
|
42
39
|
liquidGlassEnabled: false,
|
|
43
|
-
productAnalyticsConfig: undefined,
|
|
44
40
|
})
|
|
45
41
|
|
|
46
42
|
export function ChatProvider({ children, value }: { children: any; value: ChatProviderProps }) {
|
|
@@ -64,7 +60,6 @@ export function ChatProvider({ children, value }: { children: any; value: ChatPr
|
|
|
64
60
|
[env, prototypeName, token, tokenType]
|
|
65
61
|
)
|
|
66
62
|
|
|
67
|
-
const productAnalyticsConfig = useProductAnalyticsConfig(session)
|
|
68
63
|
const contextValue: ChatContextValue = {
|
|
69
64
|
...value,
|
|
70
65
|
edgeToEdge,
|
|
@@ -76,7 +71,6 @@ export function ChatProvider({ children, value }: { children: any; value: ChatPr
|
|
|
76
71
|
session,
|
|
77
72
|
theme,
|
|
78
73
|
token,
|
|
79
|
-
productAnalyticsConfig,
|
|
80
74
|
}
|
|
81
75
|
|
|
82
76
|
return <ChatContext.Provider value={contextValue}>{children}</ChatContext.Provider>
|
|
@@ -107,53 +101,3 @@ export const useCreateChatTheme = ({
|
|
|
107
101
|
|
|
108
102
|
return theme
|
|
109
103
|
}
|
|
110
|
-
|
|
111
|
-
interface ProductAnalyticsTokenResponse {
|
|
112
|
-
type: 'ProductAnalyticsToken'
|
|
113
|
-
id: string
|
|
114
|
-
url: string
|
|
115
|
-
metadata: Record<string, unknown>
|
|
116
|
-
}
|
|
117
|
-
|
|
118
|
-
// expiry time comes from here:
|
|
119
|
-
// https://github.com/planningcenter/pco-product-analytics/blob/e5bbc4c31b715b3c329c06a162829ee6967d3094/lib/pco/product/analytics/client_token_provider.rb#L24
|
|
120
|
-
const TOKEN_EXPIRY_TIME = 604800 * 1000 // 7 days in milliseconds
|
|
121
|
-
|
|
122
|
-
const useProductAnalyticsConfig = (session: Session): ProductAnalyticsConfig | undefined => {
|
|
123
|
-
const uri = useMemo(() => new Uri({ session }), [session])
|
|
124
|
-
const apiClient = useMemo(
|
|
125
|
-
() =>
|
|
126
|
-
new Client({
|
|
127
|
-
root: uri.api(`/chat/v2`),
|
|
128
|
-
defaultHeaders: uri.headers,
|
|
129
|
-
version: '2018-11-01',
|
|
130
|
-
}),
|
|
131
|
-
[uri]
|
|
132
|
-
)
|
|
133
|
-
|
|
134
|
-
const { data: config } = useQuery<ProductAnalyticsConfig>({
|
|
135
|
-
queryKey: ['product-analytics-token'],
|
|
136
|
-
queryFn: () =>
|
|
137
|
-
apiClient
|
|
138
|
-
.post<ApiResource<ProductAnalyticsTokenResponse>>({
|
|
139
|
-
url: '/me/product_analytics_authorize',
|
|
140
|
-
data: {
|
|
141
|
-
data: {
|
|
142
|
-
type: 'ProductAnalyticsToken',
|
|
143
|
-
attributes: {},
|
|
144
|
-
},
|
|
145
|
-
},
|
|
146
|
-
})
|
|
147
|
-
.then(res => ({
|
|
148
|
-
token: res.data.id,
|
|
149
|
-
endpoint: res.data.url,
|
|
150
|
-
metadata: res.data.metadata,
|
|
151
|
-
})),
|
|
152
|
-
staleTime: TOKEN_EXPIRY_TIME,
|
|
153
|
-
gcTime: TOKEN_EXPIRY_TIME,
|
|
154
|
-
refetchInterval: TOKEN_EXPIRY_TIME,
|
|
155
|
-
enabled: process.env.NODE_ENV !== 'test',
|
|
156
|
-
})
|
|
157
|
-
|
|
158
|
-
return config
|
|
159
|
-
}
|
|
@@ -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
|
|