@planningcenter/chat-react-native 4.8.0-qa-staging.10 → 4.8.0-qa-staging.12

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 (27) hide show
  1. package/build/components/conversations/conversation_actions.d.ts.map +1 -1
  2. package/build/components/conversations/conversation_actions.js +83 -47
  3. package/build/components/conversations/conversation_actions.js.map +1 -1
  4. package/build/components/conversations/swipeable_toggle_button.d.ts +5 -1
  5. package/build/components/conversations/swipeable_toggle_button.d.ts.map +1 -1
  6. package/build/components/conversations/swipeable_toggle_button.js +96 -67
  7. package/build/components/conversations/swipeable_toggle_button.js.map +1 -1
  8. package/build/contexts/chat_context.d.ts +2 -2
  9. package/build/contexts/chat_context.d.ts.map +1 -1
  10. package/build/contexts/chat_context.js.map +1 -1
  11. package/build/contexts/session_context.d.ts +1 -1
  12. package/build/contexts/session_context.d.ts.map +1 -1
  13. package/build/contexts/session_context.js +143 -338
  14. package/build/contexts/session_context.js.map +1 -1
  15. package/build/utils/client/client.d.ts +9 -5
  16. package/build/utils/client/client.d.ts.map +1 -1
  17. package/build/utils/client/client.js +95 -78
  18. package/build/utils/client/client.js.map +1 -1
  19. package/package.json +3 -3
  20. package/src/__tests__/contexts/session_context.tsx +46 -0
  21. package/src/__tests__/utils/client.ts +36 -0
  22. package/src/components/conversations/__tests__/conversation_actions.test.tsx +5 -2
  23. package/src/components/conversations/conversation_actions.tsx +47 -31
  24. package/src/components/conversations/swipeable_toggle_button.tsx +45 -16
  25. package/src/contexts/chat_context.tsx +2 -2
  26. package/src/contexts/session_context.tsx +19 -14
  27. package/src/utils/client/client.ts +95 -52
@@ -1,6 +1,12 @@
1
1
  import React from 'react'
2
- import { StyleSheet } from 'react-native'
2
+ import { StyleSheet, View } from 'react-native'
3
3
  import { Pressable, type PressableProps } from 'react-native-gesture-handler'
4
+ import Animated, {
5
+ Extrapolation,
6
+ SharedValue,
7
+ interpolate,
8
+ useAnimatedStyle,
9
+ } from 'react-native-reanimated'
4
10
  import { useCreateAndroidRippleColor, useTheme } from '../../hooks'
5
11
  import { Haptic } from '../../utils/native_adapters/configuration'
6
12
  import {
@@ -11,8 +17,12 @@ import {
11
17
  import { tokens } from '../../vendor/tapestry/tokens'
12
18
  import { Icon, IconString, Spinner, Text } from '../display'
13
19
 
20
+ export const SWIPEABLE_TOGGLE_BUTTON_WIDTH = 120
21
+
14
22
  interface SwipeableToggleButtonProps extends PressableProps {
15
23
  backgroundColor: string
24
+ /** How far the swipe is open, 0 (closed) to 1 (fully open). */
25
+ progress: SharedValue<number>
16
26
  toggled: boolean
17
27
  toggleContent: {
18
28
  true: { iconName: IconString; label: string }
@@ -24,6 +34,7 @@ interface SwipeableToggleButtonProps extends PressableProps {
24
34
  export function SwipeableToggleButton({
25
35
  backgroundColor,
26
36
  onPress,
37
+ progress,
27
38
  toggleContent,
28
39
  disabled = false,
29
40
  toggled,
@@ -37,6 +48,13 @@ export function SwipeableToggleButton({
37
48
 
38
49
  const { iconName, label } = toggleContent[toggled ? 'true' : 'false']
39
50
 
51
+ const iconStyle = useAnimatedStyle(() => ({
52
+ transform: [{ scale: interpolate(progress.value, [0, 1], [0.7, 1], Extrapolation.CLAMP) }],
53
+ }))
54
+ const labelStyle = useAnimatedStyle(() => ({
55
+ opacity: interpolate(progress.value, [0.5, 1], [0, 1], Extrapolation.CLAMP),
56
+ }))
57
+
40
58
  return (
41
59
  <Pressable
42
60
  onPress={event => {
@@ -53,20 +71,24 @@ export function SwipeableToggleButton({
53
71
  {loading ? (
54
72
  <Spinner size={20} />
55
73
  ) : (
56
- <>
57
- <Icon
58
- name={iconName}
59
- style={styles.icon}
60
- maxFontSizeMultiplier={MAX_FONT_SIZE_MULTIPLIER}
61
- />
62
- <Text
63
- variant="footnote"
64
- style={styles.text}
65
- maxFontSizeMultiplier={MAX_FONT_SIZE_MULTIPLIER}
66
- >
67
- {label}
68
- </Text>
69
- </>
74
+ <View style={styles.content}>
75
+ <Animated.View style={iconStyle}>
76
+ <Icon
77
+ name={iconName}
78
+ style={styles.icon}
79
+ maxFontSizeMultiplier={MAX_FONT_SIZE_MULTIPLIER}
80
+ />
81
+ </Animated.View>
82
+ <Animated.View style={labelStyle}>
83
+ <Text
84
+ variant="footnote"
85
+ style={styles.text}
86
+ maxFontSizeMultiplier={MAX_FONT_SIZE_MULTIPLIER}
87
+ >
88
+ {label}
89
+ </Text>
90
+ </Animated.View>
91
+ </View>
70
92
  )}
71
93
  </Pressable>
72
94
  )
@@ -85,10 +107,17 @@ const useStyles = ({ backgroundColor, disabled }: Partial<SwipeableToggleButtonP
85
107
  flexDirection: 'column',
86
108
  alignItems: 'center',
87
109
  justifyContent: 'center',
88
- gap: 4,
89
110
  height: '100%',
111
+ overflow: 'hidden',
90
112
  backgroundColor: buttonBackgroundColor,
91
113
  },
114
+ // Laid out at the fully open width and clipped by the button, so the icon and label stay
115
+ // centered and never reflow while the button is narrower than that.
116
+ content: {
117
+ width: SWIPEABLE_TOGGLE_BUTTON_WIDTH,
118
+ alignItems: 'center',
119
+ gap: 4,
120
+ },
92
121
  icon: {
93
122
  fontSize: 20,
94
123
  color: fillColor,
@@ -3,8 +3,8 @@ import React, { createContext, useMemo } from 'react'
3
3
  import { ColorSchemeName, useColorScheme } from 'react-native'
4
4
  import { AgeCheckContactInfo } from '../screens/age_check/screen_props'
5
5
  import { DeepPartial } from '../types'
6
- import { FailedResponse } from '../types'
7
6
  import { ENV, OauthType, PartialToken, Session } from '../utils'
7
+ import { OnUnauthorizedResponse } from '../utils/client/client'
8
8
  import { setLiquidGlassCapability } from '../utils/liquid_glass'
9
9
  import { ChatTheme, defaultTheme, DefaultTheme } from '../utils/theme'
10
10
 
@@ -13,7 +13,7 @@ export interface ChatProviderProps {
13
13
  prototypeName?: string
14
14
  giphyApiKey?: string
15
15
  onAgeDisqualification?: (params: AgeCheckContactInfo) => void
16
- onUnauthorizedResponse: (_response: FailedResponse) => void
16
+ onUnauthorizedResponse: OnUnauthorizedResponse
17
17
  token?: PartialToken
18
18
  tokenType?: OauthType
19
19
  theme: CreateChatThemeProps
@@ -5,6 +5,7 @@ import React, {
5
5
  useCallback,
6
6
  useEffect,
7
7
  useMemo,
8
+ useRef,
8
9
  useState,
9
10
  } from 'react'
10
11
  import { Alert } from 'react-native'
@@ -28,7 +29,7 @@ export type SessionContextValue = {
28
29
  session: Session
29
30
  sessions: Sessions
30
31
  token: OAuthToken | undefined
31
- handleUnauthorizedResponse: (_response: FailedResponse) => void
32
+ handleUnauthorizedResponse: (_response: FailedResponse) => Promise<OAuthToken | undefined>
32
33
  logout: () => void
33
34
  setToken: (_token: OAuthToken) => void
34
35
  switchSession: (_sessionId: string) => void
@@ -41,7 +42,7 @@ export const SessionContext = createContext<SessionContextValue>({
41
42
  session: new Session(),
42
43
  sessions: {},
43
44
  token: undefined,
44
- handleUnauthorizedResponse: () => null,
45
+ handleUnauthorizedResponse: () => Promise.resolve(undefined),
45
46
  logout: () => null,
46
47
  setToken: () => null,
47
48
  switchSession: () => null,
@@ -123,7 +124,7 @@ export function SessionContextProvider({
123
124
 
124
125
  const {
125
126
  mutate: refreshToken,
126
- isPending: isRefreshingToken,
127
+ mutateAsync: refreshTokenAsync,
127
128
  isError: isRefreshError,
128
129
  } = useMutation({
129
130
  mutationKey: ['refresh-token', token?.refresh_token],
@@ -135,7 +136,10 @@ export function SessionContextProvider({
135
136
  refresh_token: token.refresh_token,
136
137
  env: currentSession.env,
137
138
  prototypeName: currentSession.prototypeName,
138
- }).then(handleTokenUpdate)
139
+ }).then(async refreshedToken => {
140
+ await handleTokenUpdate(refreshedToken)
141
+ return refreshedToken
142
+ })
139
143
  },
140
144
  onError: (t: Partial<FailedResponse>) => {
141
145
  handleRefreshFailed(t)
@@ -239,26 +243,27 @@ export function SessionContextProvider({
239
243
  [handleLogout]
240
244
  )
241
245
 
246
+ const refreshInFlight = useRef<Promise<OAuthToken | undefined> | undefined>(undefined)
247
+
242
248
  const handleUnauthorizedResponse = useCallback(
243
- async (response: FailedResponse) => {
249
+ (response: FailedResponse) => {
244
250
  const { errors = [] } = response
245
251
 
246
252
  const isUnauthorized = errors.some((e: { detail?: string }) =>
247
253
  /TRASH_PANDA/i.test(e.detail || '')
248
254
  )
249
255
 
250
- if (isUnauthorized) return
256
+ if (isUnauthorized) return Promise.resolve(undefined)
251
257
 
252
- const isForcedLogout = errors.some((e: { detail?: string }) =>
253
- /capuchin/i.test(e.detail || '')
254
- )
255
- const isExpiredToken = errors.some((e: { detail?: string }) => /baboon/i.test(e.detail || ''))
258
+ refreshInFlight.current ??= refreshTokenAsync()
259
+ .catch(() => undefined)
260
+ .finally(() => {
261
+ refreshInFlight.current = undefined
262
+ })
256
263
 
257
- if (!isRefreshingToken || isExpiredToken || isForcedLogout) {
258
- refreshToken()
259
- }
264
+ return refreshInFlight.current
260
265
  },
261
- [refreshToken, isRefreshingToken]
266
+ [refreshTokenAsync]
262
267
  )
263
268
 
264
269
  const sessionContextValue: SessionContextValue = {
@@ -1,4 +1,4 @@
1
- import { ApiCollection, ApiResource, FailedResponse } from '../../types'
1
+ import { ApiCollection, ApiResource, FailedResponse, OAuthToken } from '../../types'
2
2
  import { isResponseLike } from '../response_error'
3
3
  import {
4
4
  concatRecords,
@@ -10,18 +10,23 @@ import {
10
10
  } from './request_helpers'
11
11
  import { DeleteRequest, GetRequest, PatchRequest, PostRequest, WalkRequest } from './types'
12
12
 
13
- export type OnUnauthorizedResponse = (_response: FailedResponse) => void
13
+ type RefreshedToken = Pick<OAuthToken, 'access_token'>
14
+ type Headers = Record<string, string>
15
+
16
+ export type OnUnauthorizedResponse = (
17
+ _response: FailedResponse
18
+ ) => void | Promise<RefreshedToken | void>
14
19
 
15
20
  type ClientArgs = {
16
21
  version: string
17
- defaultHeaders?: Record<string, string>
22
+ defaultHeaders?: Headers
18
23
  onUnauthorizedResponse?: OnUnauthorizedResponse
19
24
  root?: string
20
25
  }
21
26
 
22
27
  export class Client {
23
28
  version: string = ''
24
- defaultHeaders: Record<string, string> = {}
29
+ defaultHeaders: Headers = {}
25
30
  onUnauthorizedResponse?: OnUnauthorizedResponse
26
31
  root?: string
27
32
 
@@ -35,91 +40,129 @@ export class Client {
35
40
  async get<T extends ApiCollection | ApiResource>(args: GetRequest): Promise<T> {
36
41
  const { walk, ...data } = args.data
37
42
  const isWalking = Boolean(walk)
38
- const headers = { ...this.headers, ...args.headers }
39
43
  const url = this.appUrl(args.url)
40
44
 
41
45
  await throwErrorIfQueryParams(url)
42
46
 
43
- const requestArgs: MakeRequestArgs = { data, url, action: 'GET', headers }
44
-
45
- const walkRequest = ({
46
- url: requestUrl,
47
- data: d = { fields: {} },
48
- acc = { data: [], included: [], meta: {}, links: {} },
49
- ...options
50
- }: WalkRequest): Promise<T> => {
51
- return makeRequest({
52
- action: 'GET',
53
- data: d,
54
- url: requestUrl,
55
- ...options,
56
- headers,
57
- }).then(({ links, ...rest }) => {
58
- const records = Array.isArray(rest.data) ? concatRecords(acc, rest) : rest
59
-
60
- // `next` will have our params in the link so we do not want to pass them back in
61
- if (links?.next) {
62
- return walkRequest({ ...options, data: d, url: links.next, acc: records })
63
- } else {
64
- return records
47
+ return this.send(
48
+ headers => {
49
+ const requestArgs: MakeRequestArgs = { data, url, action: 'GET', headers }
50
+
51
+ const walkRequest = ({
52
+ url: requestUrl,
53
+ data: d = { fields: {} },
54
+ acc = { data: [], included: [], meta: {}, links: {} },
55
+ ...options
56
+ }: WalkRequest): Promise<T> => {
57
+ return makeRequest({
58
+ action: 'GET',
59
+ data: d,
60
+ url: requestUrl,
61
+ ...options,
62
+ headers,
63
+ }).then(({ links, ...rest }) => {
64
+ const records = Array.isArray(rest.data) ? concatRecords(acc, rest) : rest
65
+
66
+ // `next` will have our params in the link so we do not want to pass them back in
67
+ if (links?.next) {
68
+ return walkRequest({ ...options, data: d, url: links.next, acc: records })
69
+ } else {
70
+ return records
71
+ }
72
+ })
65
73
  }
66
- })
67
- }
68
74
 
69
- const handler = isWalking
70
- ? (a: MakeRequestArgs | WalkRequest) => walkRequest(a as WalkRequest)
71
- : (a: MakeRequestArgs | WalkRequest) => makeRequest(a as MakeRequestArgs)
75
+ const handler = isWalking
76
+ ? (a: MakeRequestArgs | WalkRequest) => walkRequest(a as WalkRequest)
77
+ : (a: MakeRequestArgs | WalkRequest) => makeRequest(a as MakeRequestArgs)
72
78
 
73
- return throwErrorIfFieldsMissing(handler, requestArgs)
74
- .then(response => response as T)
75
- .catch(this.handleNotOk)
79
+ return throwErrorIfFieldsMissing(handler, requestArgs).then(response => response as T)
80
+ },
81
+ { ...this.headers, ...args.headers }
82
+ )
76
83
  }
77
84
 
78
85
  async patch<T extends ApiCollection | ApiResource>(args: PatchRequest): Promise<T> {
79
- const headers = { ...this.headers, ...args.headers }
80
86
  const url = this.appUrl(args.url)
81
87
 
82
- const requestArgs: MakeRequestArgs = { data: args.data, url, action: 'PATCH', headers }
88
+ return this.send(
89
+ headers => {
90
+ const requestArgs: MakeRequestArgs = { data: args.data, url, action: 'PATCH', headers }
83
91
 
84
- return ensureNoQueryParamsInDev(makeRequest, requestArgs)
85
- .then(response => response as T)
86
- .catch(this.handleNotOk)
92
+ return ensureNoQueryParamsInDev(makeRequest, requestArgs).then(response => response as T)
93
+ },
94
+ { ...this.headers, ...args.headers }
95
+ )
87
96
  }
88
97
 
89
98
  async post<T extends ApiCollection | ApiResource>(args: PostRequest): Promise<T> {
90
- const headers = { ...this.headers, ...args.headers }
91
99
  const url = this.appUrl(args.url)
92
100
 
93
- const requestArgs: MakeRequestArgs = { ...args, data: args.data, url, action: 'POST', headers }
101
+ return this.send(
102
+ headers => {
103
+ const requestArgs: MakeRequestArgs = {
104
+ ...args,
105
+ data: args.data,
106
+ url,
107
+ action: 'POST',
108
+ headers,
109
+ }
94
110
 
95
- return ensureNoQueryParamsInDev(makeRequest, requestArgs)
96
- .then(response => response as T)
97
- .catch(this.handleNotOk)
111
+ return ensureNoQueryParamsInDev(makeRequest, requestArgs).then(response => response as T)
112
+ },
113
+ { ...this.headers, ...args.headers }
114
+ )
98
115
  }
99
116
 
100
117
  async delete(args: DeleteRequest) {
101
- const headers = { ...this.headers, ...args.headers }
102
118
  const url = this.appUrl(args.url)
103
119
 
104
- const requestArgs: MakeRequestArgs = { url, action: 'DELETE', headers }
120
+ return this.send(headers => makeRequest({ url, action: 'DELETE', headers }), {
121
+ ...this.headers,
122
+ ...args.headers,
123
+ })
124
+ }
105
125
 
106
- return makeRequest(requestArgs).catch(this.handleNotOk)
126
+ private send<T>(request: (_headers: Headers) => Promise<T>, headers: Headers): Promise<T> {
127
+ return request(headers).catch((error: Response | Error) =>
128
+ this.handleNotOk(error, ({ access_token }) =>
129
+ request({ ...headers, Authorization: `Bearer ${access_token}` }).catch(
130
+ (retryError: Response | Error) => this.handleNotOk(retryError)
131
+ )
132
+ )
133
+ )
107
134
  }
108
135
 
109
- handleNotOk = async (response: Response | Error) => {
136
+ handleNotOk = async <T = never>(
137
+ response: Response | Error,
138
+ retry?: (_token: RefreshedToken) => Promise<T>
139
+ ): Promise<T> => {
110
140
  if (!isResponseLike(response)) return Promise.reject(response)
111
141
 
112
142
  const errorData = await this.parseErrorResponse(response)
113
143
  const notOkResponse = response.clone() as FailedResponse
114
144
  notOkResponse.errors = errorData.errors || []
115
145
 
116
- if (response.status === 401) {
117
- this.onUnauthorizedResponse?.(notOkResponse)
118
- }
146
+ if (response.status !== 401) return Promise.reject(notOkResponse)
147
+
148
+ const refreshedToken = await this.refreshedTokenFor(notOkResponse)
149
+
150
+ if (refreshedToken && retry) return retry(refreshedToken)
119
151
 
120
152
  return Promise.reject(notOkResponse)
121
153
  }
122
154
 
155
+ private refreshedTokenFor = async (
156
+ response: FailedResponse
157
+ ): Promise<RefreshedToken | undefined> => {
158
+ try {
159
+ const token = await this.onUnauthorizedResponse?.(response)
160
+ return token && token.access_token ? token : undefined
161
+ } catch {
162
+ return undefined
163
+ }
164
+ }
165
+
123
166
  parseErrorResponse = async (response: Response): Promise<Partial<FailedResponse>> => {
124
167
  try {
125
168
  return (await response.clone().json()) as FailedResponse