@cobbai/react-native-sdk 1.0.0-beta.0

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 (143) hide show
  1. package/CobbaiMobileRnSdk.podspec +22 -0
  2. package/LICENSE +32 -0
  3. package/README.md +386 -0
  4. package/dist/ChatPlaceholder.d.ts +13 -0
  5. package/dist/ChatPlaceholder.d.ts.map +1 -0
  6. package/dist/ChatPlaceholder.js +87 -0
  7. package/dist/CobbaiChatScreen.d.ts +4 -0
  8. package/dist/CobbaiChatScreen.d.ts.map +1 -0
  9. package/dist/CobbaiChatScreen.js +196 -0
  10. package/dist/CobbaiInAppBanner.d.ts +15 -0
  11. package/dist/CobbaiInAppBanner.d.ts.map +1 -0
  12. package/dist/CobbaiInAppBanner.js +159 -0
  13. package/dist/CobbaiLauncher.d.ts +19 -0
  14. package/dist/CobbaiLauncher.d.ts.map +1 -0
  15. package/dist/CobbaiLauncher.js +149 -0
  16. package/dist/CobbaiWebView.d.ts +28 -0
  17. package/dist/CobbaiWebView.d.ts.map +1 -0
  18. package/dist/CobbaiWebView.js +141 -0
  19. package/dist/adapters/expoAdapter.d.ts +85 -0
  20. package/dist/adapters/expoAdapter.d.ts.map +1 -0
  21. package/dist/adapters/expoAdapter.js +152 -0
  22. package/dist/adapters/firebaseAdapter.d.ts +41 -0
  23. package/dist/adapters/firebaseAdapter.d.ts.map +1 -0
  24. package/dist/adapters/firebaseAdapter.js +139 -0
  25. package/dist/adapters/iosRelayAdapter.d.ts +26 -0
  26. package/dist/adapters/iosRelayAdapter.d.ts.map +1 -0
  27. package/dist/adapters/iosRelayAdapter.js +101 -0
  28. package/dist/androidKeyboardFrame.d.ts +16 -0
  29. package/dist/androidKeyboardFrame.d.ts.map +1 -0
  30. package/dist/androidKeyboardFrame.js +34 -0
  31. package/dist/bridge/messages.d.ts +20 -0
  32. package/dist/bridge/messages.d.ts.map +1 -0
  33. package/dist/bridge/messages.js +20 -0
  34. package/dist/bridge/nativeEvent.d.ts +10 -0
  35. package/dist/bridge/nativeEvent.d.ts.map +1 -0
  36. package/dist/bridge/nativeEvent.js +15 -0
  37. package/dist/bridge/parser.d.ts +29 -0
  38. package/dist/bridge/parser.d.ts.map +1 -0
  39. package/dist/bridge/parser.js +109 -0
  40. package/dist/chatPresentation.d.ts +19 -0
  41. package/dist/chatPresentation.d.ts.map +1 -0
  42. package/dist/chatPresentation.js +51 -0
  43. package/dist/chatScreen/useInAppBannerQueue.d.ts +22 -0
  44. package/dist/chatScreen/useInAppBannerQueue.d.ts.map +1 -0
  45. package/dist/chatScreen/useInAppBannerQueue.js +60 -0
  46. package/dist/chatScreen/useKeyboardFrame.d.ts +14 -0
  47. package/dist/chatScreen/useKeyboardFrame.d.ts.map +1 -0
  48. package/dist/chatScreen/useKeyboardFrame.js +63 -0
  49. package/dist/chatScreen/useLauncherPresentation.d.ts +20 -0
  50. package/dist/chatScreen/useLauncherPresentation.d.ts.map +1 -0
  51. package/dist/chatScreen/useLauncherPresentation.js +76 -0
  52. package/dist/chatScreen/useNativeToWebSync.d.ts +17 -0
  53. package/dist/chatScreen/useNativeToWebSync.d.ts.map +1 -0
  54. package/dist/chatScreen/useNativeToWebSync.js +36 -0
  55. package/dist/chatScreen/usePushIntegration.d.ts +19 -0
  56. package/dist/chatScreen/usePushIntegration.d.ts.map +1 -0
  57. package/dist/chatScreen/usePushIntegration.js +129 -0
  58. package/dist/chatScreen/useReadyLifecycle.d.ts +33 -0
  59. package/dist/chatScreen/useReadyLifecycle.d.ts.map +1 -0
  60. package/dist/chatScreen/useReadyLifecycle.js +138 -0
  61. package/dist/chatScreen/useSheetPresentation.d.ts +25 -0
  62. package/dist/chatScreen/useSheetPresentation.d.ts.map +1 -0
  63. package/dist/chatScreen/useSheetPresentation.js +98 -0
  64. package/dist/chatUnavailable.d.ts +23 -0
  65. package/dist/chatUnavailable.d.ts.map +1 -0
  66. package/dist/chatUnavailable.js +36 -0
  67. package/dist/externalLinks.d.ts +4 -0
  68. package/dist/externalLinks.d.ts.map +1 -0
  69. package/dist/externalLinks.js +48 -0
  70. package/dist/host/buildHostHtml.d.ts +7 -0
  71. package/dist/host/buildHostHtml.d.ts.map +1 -0
  72. package/dist/host/buildHostHtml.js +101 -0
  73. package/dist/host/hostPageKey.d.ts +7 -0
  74. package/dist/host/hostPageKey.d.ts.map +1 -0
  75. package/dist/host/hostPageKey.js +18 -0
  76. package/dist/inAppBanner.d.ts +19 -0
  77. package/dist/inAppBanner.d.ts.map +1 -0
  78. package/dist/inAppBanner.js +42 -0
  79. package/dist/index.d.ts +10 -0
  80. package/dist/index.d.ts.map +1 -0
  81. package/dist/index.js +32 -0
  82. package/dist/launcher.d.ts +25 -0
  83. package/dist/launcher.d.ts.map +1 -0
  84. package/dist/launcher.js +55 -0
  85. package/dist/launcherGlyph.d.ts +2 -0
  86. package/dist/launcherGlyph.d.ts.map +1 -0
  87. package/dist/launcherGlyph.js +5 -0
  88. package/dist/openChatScreen.d.ts +13 -0
  89. package/dist/openChatScreen.d.ts.map +1 -0
  90. package/dist/openChatScreen.js +63 -0
  91. package/dist/push.d.ts +59 -0
  92. package/dist/push.d.ts.map +1 -0
  93. package/dist/push.js +309 -0
  94. package/dist/pushIntegration.d.ts +76 -0
  95. package/dist/pushIntegration.d.ts.map +1 -0
  96. package/dist/pushIntegration.js +244 -0
  97. package/dist/pushLogout.d.ts +57 -0
  98. package/dist/pushLogout.d.ts.map +1 -0
  99. package/dist/pushLogout.js +225 -0
  100. package/dist/types.d.ts +42 -0
  101. package/dist/types.d.ts.map +1 -0
  102. package/dist/types.js +2 -0
  103. package/dist/version.d.ts +8 -0
  104. package/dist/version.d.ts.map +1 -0
  105. package/dist/version.js +10 -0
  106. package/ios/CobbaiPush.m +96 -0
  107. package/ios/CobbaiPushRelay.h +59 -0
  108. package/ios/CobbaiPushRelay.m +364 -0
  109. package/package.json +69 -0
  110. package/src/ChatPlaceholder.tsx +132 -0
  111. package/src/CobbaiChatScreen.tsx +348 -0
  112. package/src/CobbaiInAppBanner.tsx +237 -0
  113. package/src/CobbaiLauncher.tsx +223 -0
  114. package/src/CobbaiWebView.tsx +242 -0
  115. package/src/adapters/expoAdapter.ts +227 -0
  116. package/src/adapters/firebaseAdapter.ts +201 -0
  117. package/src/adapters/iosRelayAdapter.ts +137 -0
  118. package/src/androidKeyboardFrame.ts +56 -0
  119. package/src/bridge/messages.ts +24 -0
  120. package/src/bridge/nativeEvent.ts +12 -0
  121. package/src/bridge/parser.ts +159 -0
  122. package/src/chatPresentation.ts +73 -0
  123. package/src/chatScreen/useInAppBannerQueue.ts +91 -0
  124. package/src/chatScreen/useKeyboardFrame.ts +89 -0
  125. package/src/chatScreen/useLauncherPresentation.ts +121 -0
  126. package/src/chatScreen/useNativeToWebSync.ts +54 -0
  127. package/src/chatScreen/usePushIntegration.ts +191 -0
  128. package/src/chatScreen/useReadyLifecycle.ts +186 -0
  129. package/src/chatScreen/useSheetPresentation.ts +147 -0
  130. package/src/chatUnavailable.ts +58 -0
  131. package/src/externalLinks.ts +56 -0
  132. package/src/host/buildHostHtml.ts +117 -0
  133. package/src/host/hostPageKey.ts +17 -0
  134. package/src/inAppBanner.ts +58 -0
  135. package/src/index.ts +53 -0
  136. package/src/launcher.ts +79 -0
  137. package/src/launcherGlyph.ts +3 -0
  138. package/src/openChatScreen.ts +78 -0
  139. package/src/push.ts +424 -0
  140. package/src/pushIntegration.ts +338 -0
  141. package/src/pushLogout.ts +277 -0
  142. package/src/types.ts +46 -0
  143. package/src/version.ts +8 -0
@@ -0,0 +1,223 @@
1
+ import React, { useEffect, useMemo, useRef } from 'react';
2
+ import { Animated, Easing, Image, Pressable, StyleSheet, Text } from 'react-native';
3
+ import {
4
+ formatUnreadBadge,
5
+ LAUNCHER_BADGE_APPEAR_DURATION_MS,
6
+ LAUNCHER_BADGE_PULSE_DURATION_MS,
7
+ LAUNCHER_GLYPH_SIZE,
8
+ LAUNCHER_SHADOW_COLOR,
9
+ LAUNCHER_WRAPPER_SIZE,
10
+ type LauncherAppearance,
11
+ } from './launcher';
12
+ import { CHAT_BUTTON_GLYPH_URI } from './launcherGlyph';
13
+
14
+ type CobbaiLauncherProps = {
15
+ appearance: LauncherAppearance;
16
+ unreadTotal: number | null;
17
+ isVisible: boolean;
18
+ right: number;
19
+ bottom: number;
20
+ opacity: Animated.Value;
21
+ accessibilityLabel: string;
22
+ accessibilityValue?: { text: string };
23
+ onPress: () => void;
24
+ };
25
+
26
+ export function CobbaiLauncher(props: CobbaiLauncherProps): React.JSX.Element {
27
+ const {
28
+ appearance,
29
+ unreadTotal,
30
+ isVisible,
31
+ right,
32
+ bottom,
33
+ opacity,
34
+ accessibilityLabel,
35
+ accessibilityValue,
36
+ onPress,
37
+ } = props;
38
+
39
+ const badgeScale = useRef(new Animated.Value(1)).current;
40
+ const badgeOpacity = useRef(new Animated.Value(0)).current;
41
+ const previousUnreadTotalRef = useRef(0);
42
+ const badgeWasVisibleRef = useRef(false);
43
+
44
+ const badgeText = useMemo(() => formatUnreadBadge(unreadTotal), [unreadTotal]);
45
+ const badgeIsVisible = badgeText.length > 0;
46
+
47
+ useEffect(() => {
48
+ const currentTotal = typeof unreadTotal === 'number' ? unreadTotal : 0;
49
+
50
+ if (!badgeIsVisible) {
51
+ badgeScale.stopAnimation();
52
+ badgeOpacity.stopAnimation();
53
+ badgeScale.setValue(1);
54
+ badgeOpacity.setValue(0);
55
+ badgeWasVisibleRef.current = false;
56
+ previousUnreadTotalRef.current = currentTotal;
57
+ return;
58
+ }
59
+
60
+ if (!badgeWasVisibleRef.current) {
61
+ badgeScale.stopAnimation();
62
+ badgeOpacity.stopAnimation();
63
+ badgeScale.setValue(0.6);
64
+ badgeOpacity.setValue(0);
65
+
66
+ Animated.parallel([
67
+ Animated.timing(badgeScale, {
68
+ toValue: 1,
69
+ duration: LAUNCHER_BADGE_APPEAR_DURATION_MS,
70
+ easing: Easing.out(Easing.cubic),
71
+ useNativeDriver: true,
72
+ }),
73
+ Animated.timing(badgeOpacity, {
74
+ toValue: 1,
75
+ duration: LAUNCHER_BADGE_APPEAR_DURATION_MS,
76
+ easing: Easing.out(Easing.cubic),
77
+ useNativeDriver: true,
78
+ }),
79
+ ]).start();
80
+ } else if (currentTotal > previousUnreadTotalRef.current) {
81
+ badgeScale.stopAnimation();
82
+ badgeScale.setValue(1);
83
+ badgeOpacity.stopAnimation();
84
+ badgeOpacity.setValue(1);
85
+
86
+ const pulseHalfDuration = Math.round(LAUNCHER_BADGE_PULSE_DURATION_MS / 2);
87
+ Animated.sequence([
88
+ Animated.timing(badgeScale, {
89
+ toValue: 1.14,
90
+ duration: pulseHalfDuration,
91
+ easing: Easing.out(Easing.cubic),
92
+ useNativeDriver: true,
93
+ }),
94
+ Animated.timing(badgeScale, {
95
+ toValue: 1,
96
+ duration: LAUNCHER_BADGE_PULSE_DURATION_MS - pulseHalfDuration,
97
+ easing: Easing.in(Easing.cubic),
98
+ useNativeDriver: true,
99
+ }),
100
+ ]).start();
101
+ } else {
102
+ badgeOpacity.stopAnimation();
103
+ badgeOpacity.setValue(1);
104
+ badgeScale.stopAnimation();
105
+ badgeScale.setValue(1);
106
+ }
107
+
108
+ badgeWasVisibleRef.current = true;
109
+ previousUnreadTotalRef.current = currentTotal;
110
+ }, [badgeIsVisible, badgeOpacity, badgeScale, unreadTotal]);
111
+
112
+ return (
113
+ <Animated.View
114
+ style={[
115
+ styles.container,
116
+ {
117
+ right,
118
+ bottom,
119
+ opacity,
120
+ },
121
+ ]}
122
+ pointerEvents={isVisible ? 'box-none' : 'none'}
123
+ accessibilityElementsHidden={!isVisible}
124
+ importantForAccessibility={isVisible ? 'auto' : 'no-hide-descendants'}
125
+ >
126
+ <Pressable
127
+ testID="cobbai-launcher"
128
+ disabled={!isVisible}
129
+ accessibilityRole="button"
130
+ accessibilityLabel={accessibilityLabel}
131
+ accessibilityValue={accessibilityValue}
132
+ accessibilityElementsHidden={!isVisible}
133
+ importantForAccessibility={isVisible ? 'auto' : 'no-hide-descendants'}
134
+ onPress={onPress}
135
+ style={({ pressed }) => [
136
+ styles.button,
137
+ {
138
+ backgroundColor: appearance.backgroundColor,
139
+ opacity: pressed ? 0.85 : 1,
140
+ },
141
+ ]}
142
+ >
143
+ <Image
144
+ source={{ uri: CHAT_BUTTON_GLYPH_URI }}
145
+ resizeMode="contain"
146
+ accessible={false}
147
+ importantForAccessibility="no"
148
+ style={[styles.glyph, { tintColor: appearance.textColor }]}
149
+ />
150
+ </Pressable>
151
+
152
+ {badgeIsVisible ? (
153
+ <Animated.View
154
+ testID="cobbai-launcher-badge"
155
+ pointerEvents="none"
156
+ accessible={false}
157
+ importantForAccessibility="no"
158
+ style={[
159
+ styles.badge,
160
+ {
161
+ opacity: badgeOpacity,
162
+ transform: [{ scale: badgeScale }],
163
+ },
164
+ ]}
165
+ >
166
+ <Text style={styles.badgeText}>{badgeText}</Text>
167
+ </Animated.View>
168
+ ) : null}
169
+ </Animated.View>
170
+ );
171
+ }
172
+
173
+ const styles = StyleSheet.create({
174
+ container: {
175
+ position: 'absolute',
176
+ width: LAUNCHER_WRAPPER_SIZE,
177
+ height: LAUNCHER_WRAPPER_SIZE,
178
+ overflow: 'visible',
179
+ zIndex: 2147483645,
180
+ },
181
+ button: {
182
+ width: LAUNCHER_WRAPPER_SIZE,
183
+ height: LAUNCHER_WRAPPER_SIZE,
184
+ borderTopLeftRadius: 16,
185
+ borderTopRightRadius: 16,
186
+ borderBottomRightRadius: 16,
187
+ borderBottomLeftRadius: 0,
188
+ alignItems: 'center',
189
+ justifyContent: 'center',
190
+ shadowColor: LAUNCHER_SHADOW_COLOR,
191
+ shadowOpacity: 0.9,
192
+ shadowRadius: 4,
193
+ shadowOffset: {
194
+ width: 0,
195
+ height: 0,
196
+ },
197
+ elevation: 6,
198
+ },
199
+ glyph: {
200
+ width: LAUNCHER_GLYPH_SIZE,
201
+ height: LAUNCHER_GLYPH_SIZE,
202
+ },
203
+ badge: {
204
+ position: 'absolute',
205
+ top: -4,
206
+ right: -4,
207
+ minWidth: 18,
208
+ height: 18,
209
+ paddingHorizontal: 4,
210
+ borderRadius: 999,
211
+ alignItems: 'center',
212
+ justifyContent: 'center',
213
+ backgroundColor: '#E25959',
214
+ },
215
+ badgeText: {
216
+ color: '#FFFFFF',
217
+ fontSize: 10,
218
+ fontWeight: '700',
219
+ includeFontPadding: false,
220
+ textAlign: 'center',
221
+ textAlignVertical: 'center',
222
+ },
223
+ });
@@ -0,0 +1,242 @@
1
+ import React, { useMemo } from 'react';
2
+ import { ActivityIndicator, Linking, StyleSheet, View } from 'react-native';
3
+ import WebView, { type WebViewMessageEvent } from 'react-native-webview';
4
+ import {
5
+ parseBridgeMessage,
6
+ validatePushTokenRegisteredPayload,
7
+ type ValidatedPushTokenRegisteredPayload,
8
+ validateLauncherPayload,
9
+ validateNewMessagePayload,
10
+ validateUnreadPayload,
11
+ type ValidatedNewMessagePayload,
12
+ } from './bridge/parser';
13
+ import { WEB_TO_NATIVE_MESSAGES } from './bridge/messages';
14
+ import { isExternalOpenableUrl, isFromHostOrigin, isHostDocumentUrl } from './externalLinks';
15
+ import { buildHostHtml, normalizeBaseUrl } from './host/buildHostHtml';
16
+ import type { LauncherAppearance } from './launcher';
17
+ import type { CobbaiChatConfig, CobbaiError, CobbaiSafeAreaInsets } from './types';
18
+
19
+ // react-native-webview declares `class WebView<P = undefined>`, and `WebViewProps & undefined`
20
+ // collapses to `never`. Pinning P to `unknown` restores the real prop types.
21
+ export type CobbaiWebViewRef = WebView<unknown>;
22
+
23
+ export type ProcessGoneEvent = {
24
+ platform: 'android' | 'ios';
25
+ didCrash?: boolean;
26
+ };
27
+
28
+ type CobbaiWebViewProps = {
29
+ config: CobbaiChatConfig;
30
+ generation: number;
31
+ /** Captured once for first paint; later changes travel over the bridge, not through the HTML. */
32
+ initialSafeArea?: CobbaiSafeAreaInsets;
33
+ onReady: () => void;
34
+ onClose: () => void;
35
+ onError: (error: CobbaiError) => void;
36
+ onNewMessage: (message: ValidatedNewMessagePayload) => void;
37
+ onUnread: (total: number) => void;
38
+ onPushTokenRegistered: (registration: ValidatedPushTokenRegisteredPayload) => void;
39
+ onLauncherAppearance: (appearance: LauncherAppearance) => void;
40
+ onProcessGone: (event: ProcessGoneEvent) => void;
41
+ onWebViewRef: (ref: CobbaiWebViewRef | null) => void;
42
+ };
43
+
44
+ type OpenWindowEvent = {
45
+ nativeEvent: {
46
+ targetUrl: string;
47
+ };
48
+ };
49
+
50
+ type ShouldStartRequest = {
51
+ isTopFrame: boolean;
52
+ url: string;
53
+ };
54
+
55
+ export function CobbaiWebView(props: CobbaiWebViewProps): React.JSX.Element {
56
+ const {
57
+ config,
58
+ generation,
59
+ initialSafeArea,
60
+ onReady,
61
+ onClose,
62
+ onError,
63
+ onNewMessage,
64
+ onUnread,
65
+ onPushTokenRegistered,
66
+ onLauncherAppearance,
67
+ onProcessGone,
68
+ onWebViewRef,
69
+ } = props;
70
+
71
+ const { baseUrl, chatId, authToken, userId, locale, metadata } = config;
72
+ const metadataKey = JSON.stringify(metadata ?? null);
73
+ const normalizedBaseUrl = useMemo(() => normalizeBaseUrl(baseUrl), [baseUrl]);
74
+
75
+ // Keyed on the values the page is built from, never on the `config` object: a new reference
76
+ // (inline literal, new callback, metadata rebuilt with the same values) must not rebuild the
77
+ // host page. A real change (token, user, locale, metadata content) still does.
78
+ const source = useMemo(
79
+ () => ({
80
+ html: buildHostHtml(
81
+ { baseUrl, chatId, authToken, userId, locale, metadata },
82
+ initialSafeArea,
83
+ ),
84
+ baseUrl: normalizedBaseUrl,
85
+ }),
86
+ // eslint-disable-next-line react-hooks/exhaustive-deps -- metadata is compared by content (metadataKey).
87
+ [baseUrl, chatId, authToken, userId, locale, metadataKey, initialSafeArea, normalizedBaseUrl],
88
+ );
89
+
90
+ const openExternalUrl = (url: string): void => {
91
+ void Linking.openURL(url).catch((error: unknown) => {
92
+ if (__DEV__) {
93
+ console.warn('[cobbai] Failed to open external URL', url, error);
94
+ }
95
+ });
96
+ };
97
+
98
+ const handleOpenWindow = (event: OpenWindowEvent): void => {
99
+ const { targetUrl } = event.nativeEvent;
100
+
101
+ if (!isExternalOpenableUrl(targetUrl)) {
102
+ return;
103
+ }
104
+
105
+ openExternalUrl(targetUrl);
106
+ };
107
+
108
+ const handleShouldStartLoadWithRequest = (request: ShouldStartRequest): boolean => {
109
+ if (request.isTopFrame === false) {
110
+ return true;
111
+ }
112
+
113
+ if (isHostDocumentUrl(request.url, normalizedBaseUrl)) {
114
+ return true;
115
+ }
116
+
117
+ if (isExternalOpenableUrl(request.url)) {
118
+ openExternalUrl(request.url);
119
+ }
120
+
121
+ return false;
122
+ };
123
+
124
+ const handleMessage = (event: WebViewMessageEvent): void => {
125
+ if (!isFromHostOrigin(event.nativeEvent.url, normalizedBaseUrl)) {
126
+ return;
127
+ }
128
+
129
+ const parsed = parseBridgeMessage(event.nativeEvent.data);
130
+ if (!parsed) return;
131
+
132
+ switch (parsed.type) {
133
+ case WEB_TO_NATIVE_MESSAGES.READY:
134
+ onReady();
135
+ return;
136
+ case WEB_TO_NATIVE_MESSAGES.CLOSE:
137
+ onClose();
138
+ return;
139
+ case WEB_TO_NATIVE_MESSAGES.ERROR: {
140
+ const code = typeof parsed.payload.code === 'string' ? parsed.payload.code : 'chat_error';
141
+ const message =
142
+ typeof parsed.payload.message === 'string'
143
+ ? parsed.payload.message
144
+ : 'Chat failed to initialize';
145
+ onError({ code, message });
146
+ return;
147
+ }
148
+ case WEB_TO_NATIVE_MESSAGES.NEW_MESSAGE: {
149
+ const nextMessage = validateNewMessagePayload(parsed.payload);
150
+ if (!nextMessage) {
151
+ return;
152
+ }
153
+
154
+ onNewMessage(nextMessage);
155
+ return;
156
+ }
157
+ case WEB_TO_NATIVE_MESSAGES.UNREAD: {
158
+ const unreadPayload = validateUnreadPayload(parsed.payload);
159
+ if (!unreadPayload) {
160
+ return;
161
+ }
162
+
163
+ onUnread(unreadPayload.total);
164
+ return;
165
+ }
166
+ case WEB_TO_NATIVE_MESSAGES.PUSH_TOKEN_REGISTERED: {
167
+ const registration = validatePushTokenRegisteredPayload(parsed.payload);
168
+ if (registration) {
169
+ onPushTokenRegistered(registration);
170
+ }
171
+ return;
172
+ }
173
+ case WEB_TO_NATIVE_MESSAGES.LAUNCHER: {
174
+ const launcherAppearance = validateLauncherPayload(parsed.payload);
175
+ if (!launcherAppearance) {
176
+ return;
177
+ }
178
+
179
+ onLauncherAppearance(launcherAppearance);
180
+ return;
181
+ }
182
+ default:
183
+ return;
184
+ }
185
+ };
186
+
187
+ return (
188
+ <View style={styles.container}>
189
+ <WebView<unknown>
190
+ key={generation}
191
+ ref={onWebViewRef}
192
+ source={source}
193
+ style={styles.webView}
194
+ originWhitelist={['*']}
195
+ webviewDebuggingEnabled={__DEV__}
196
+ onMessage={handleMessage}
197
+ onOpenWindow={handleOpenWindow}
198
+ onShouldStartLoadWithRequest={handleShouldStartLoadWithRequest}
199
+ onRenderProcessGone={(event) => {
200
+ const didCrash = event.nativeEvent?.didCrash;
201
+ onProcessGone({
202
+ platform: 'android',
203
+ didCrash: typeof didCrash === 'boolean' ? didCrash : undefined,
204
+ });
205
+ }}
206
+ onContentProcessDidTerminate={() => {
207
+ onProcessGone({ platform: 'ios' });
208
+ }}
209
+ keyboardDisplayRequiresUserAction={false}
210
+ automaticallyAdjustContentInsets={false}
211
+ hideKeyboardAccessoryView
212
+ scrollEnabled={false}
213
+ startInLoadingState
214
+ renderLoading={() => (
215
+ <View style={styles.loaderContainer}>
216
+ <ActivityIndicator size="large" />
217
+ </View>
218
+ )}
219
+ />
220
+ </View>
221
+ );
222
+ }
223
+
224
+ const styles = StyleSheet.create({
225
+ container: {
226
+ position: 'absolute',
227
+ top: 0,
228
+ right: 0,
229
+ bottom: 0,
230
+ left: 0,
231
+ backgroundColor: 'transparent',
232
+ },
233
+ webView: {
234
+ flex: 1,
235
+ backgroundColor: 'transparent',
236
+ },
237
+ loaderContainer: {
238
+ flex: 1,
239
+ alignItems: 'center',
240
+ justifyContent: 'center',
241
+ },
242
+ });
@@ -0,0 +1,227 @@
1
+ import { Platform } from 'react-native';
2
+ import { getForegroundPresentationState, isCobbaiPush } from '../push';
3
+ import type {
4
+ CobbaiPushAdapter,
5
+ CobbaiPushAdapterHandlers,
6
+ CobbaiPushStatus,
7
+ } from '../pushIntegration';
8
+
9
+ /** The fields of an `expo-notifications` notification the SDK reads. */
10
+ export type ExpoNotification = {
11
+ request: {
12
+ content: { title?: string | null; body?: string | null; data?: unknown };
13
+ trigger?: unknown;
14
+ };
15
+ };
16
+
17
+ export type ExpoNotificationResponse = { notification: ExpoNotification };
18
+
19
+ export type ExpoNotificationBehavior = {
20
+ shouldShowBanner: boolean;
21
+ shouldShowList: boolean;
22
+ shouldPlaySound: boolean;
23
+ shouldSetBadge: boolean;
24
+ };
25
+
26
+ /** An `expo-notifications` handler (`setNotificationHandler`). */
27
+ export type ExpoNotificationHandler = {
28
+ handleNotification: (notification: ExpoNotification) => Promise<ExpoNotificationBehavior>;
29
+ handleSuccess?: (notificationId: string) => void;
30
+ handleError?: (notificationId: string, error: Error) => void;
31
+ };
32
+
33
+ type ExpoSubscription = { remove(): void };
34
+ type ExpoPermissions = { status: string; granted: boolean };
35
+
36
+ /**
37
+ * The part of `expo-notifications` the adapter uses. The app passes the module itself, so the SDK
38
+ * does not depend on Expo:
39
+ *
40
+ * ```ts
41
+ * import * as Notifications from 'expo-notifications';
42
+ * configureCobbaiPush({ adapter: expoAdapter(Notifications) });
43
+ * ```
44
+ *
45
+ * Methods, not function properties: Expo's own signatures must stay assignable.
46
+ */
47
+ export type ExpoNotificationsModule = {
48
+ getDevicePushTokenAsync(): Promise<{ type: string; data: unknown }>;
49
+ addPushTokenListener(
50
+ listener: (token: { type: string; data: unknown }) => void,
51
+ ): ExpoSubscription;
52
+ addNotificationReceivedListener(
53
+ listener: (notification: ExpoNotification) => void,
54
+ ): ExpoSubscription;
55
+ addNotificationResponseReceivedListener(
56
+ listener: (response: ExpoNotificationResponse) => void,
57
+ ): ExpoSubscription;
58
+ getLastNotificationResponseAsync(): Promise<ExpoNotificationResponse | null>;
59
+ getPermissionsAsync(): Promise<ExpoPermissions>;
60
+ requestPermissionsAsync(): Promise<ExpoPermissions>;
61
+ };
62
+
63
+ /**
64
+ * The push data of a notification. For a push that does not come from Expo's push service, Expo
65
+ * puts the payload's own keys in the trigger, not in `content.data` (which holds Expo's `body`):
66
+ * Android `trigger.remoteMessage.data`, iPhone `trigger.payload`.
67
+ */
68
+ export function expoNotificationData(notification: ExpoNotification): unknown {
69
+ const trigger = notification.request.trigger as
70
+ { remoteMessage?: { data?: unknown }; payload?: unknown } | null | undefined;
71
+
72
+ const candidates = [
73
+ trigger?.remoteMessage?.data,
74
+ trigger?.payload,
75
+ notification.request.content.data,
76
+ ];
77
+ return (
78
+ candidates.find((candidate) => isCobbaiPush(candidate)) ?? notification.request.content.data
79
+ );
80
+ }
81
+
82
+ function toStatus(permissions: ExpoPermissions): CobbaiPushStatus {
83
+ if (permissions.granted) return 'granted';
84
+ return permissions.status === 'denied' ? 'denied' : 'not-asked';
85
+ }
86
+
87
+ function errorMessage(error: unknown): string {
88
+ return error instanceof Error ? error.message : String(error);
89
+ }
90
+
91
+ function warn(message: string): void {
92
+ if (__DEV__) {
93
+ console.warn(`[cobbai][push][expo] ${message}`);
94
+ }
95
+ }
96
+
97
+ /**
98
+ * Push adapter for `expo-notifications` (Expo SDK 53+ development or production builds, not Expo
99
+ * Go), **Android only**: on iPhone the SDK's native relay handles Cobbai pushes.
100
+ * On both platforms, also wrap your notification handler with `withCobbaiHandler`.
101
+ */
102
+ export function expoAdapter(notifications: ExpoNotificationsModule): CobbaiPushAdapter {
103
+ let handlers: CobbaiPushAdapterHandlers | null = null;
104
+
105
+ const reportToken = async (): Promise<void> => {
106
+ try {
107
+ const token = await notifications.getDevicePushTokenAsync();
108
+ if (typeof token.data === 'string' && token.data) {
109
+ handlers?.token({ token: token.data, provider: 'fcm' });
110
+ }
111
+ } catch (error) {
112
+ warn(`token request failed: ${errorMessage(error)}`);
113
+ }
114
+ };
115
+
116
+ return {
117
+ name: 'expo',
118
+
119
+ start(nextHandlers) {
120
+ if (Platform.OS !== 'android') {
121
+ return () => {};
122
+ }
123
+
124
+ handlers = nextHandlers;
125
+ const subscriptions = [
126
+ notifications.addPushTokenListener((token) => {
127
+ if (typeof token.data === 'string' && token.data) {
128
+ handlers?.token({ token: token.data, provider: 'fcm' });
129
+ }
130
+ }),
131
+ notifications.addNotificationReceivedListener((notification) => {
132
+ handlers?.foreground({
133
+ data: expoNotificationData(notification),
134
+ title: notification.request.content.title ?? undefined,
135
+ body: notification.request.content.body ?? undefined,
136
+ });
137
+ }),
138
+ notifications.addNotificationResponseReceivedListener((response) => {
139
+ handlers?.tap(expoNotificationData(response.notification));
140
+ }),
141
+ ];
142
+
143
+ notifications
144
+ .getLastNotificationResponseAsync()
145
+ .then((response) => {
146
+ if (response) handlers?.tap(expoNotificationData(response.notification));
147
+ })
148
+ .catch((error: unknown) =>
149
+ warn(`last notification response failed: ${errorMessage(error)}`),
150
+ );
151
+
152
+ notifications
153
+ .getPermissionsAsync()
154
+ .then((permissions) => {
155
+ const status = toStatus(permissions);
156
+ handlers?.status(status);
157
+ if (status === 'granted') return reportToken();
158
+ return undefined;
159
+ })
160
+ .catch((error: unknown) => warn(`permission check failed: ${errorMessage(error)}`));
161
+
162
+ return () => {
163
+ subscriptions.forEach((subscription) => subscription.remove());
164
+ handlers = null;
165
+ };
166
+ },
167
+
168
+ async requestPermission() {
169
+ if (Platform.OS !== 'android') {
170
+ return 'unavailable';
171
+ }
172
+
173
+ const status = toStatus(await notifications.requestPermissionsAsync());
174
+ if (status === 'granted') {
175
+ await reportToken();
176
+ }
177
+ return status;
178
+ },
179
+ };
180
+ }
181
+
182
+ const HIDDEN: ExpoNotificationBehavior = {
183
+ shouldShowBanner: false,
184
+ shouldShowList: false,
185
+ shouldPlaySound: false,
186
+ shouldSetBadge: false,
187
+ };
188
+
189
+ const SHOWN: ExpoNotificationBehavior = {
190
+ shouldShowBanner: true,
191
+ shouldShowList: true,
192
+ shouldPlaySound: true,
193
+ shouldSetBadge: false,
194
+ };
195
+
196
+ /**
197
+ * Wraps the app's `expo-notifications` handler: Expo keeps a single one, so the SDK must not replace
198
+ * it. Cobbai pushes get the SDK's decision: hidden while the chat shows them
199
+ * (connected, or its in-app banner), else the system notification. Everything else goes to the app's
200
+ * handler, or is not shown in the foreground when there is none (Expo's default).
201
+ *
202
+ * ```ts
203
+ * Notifications.setNotificationHandler(withCobbaiHandler({ handleNotification: async () => ({ ... }) }));
204
+ * ```
205
+ */
206
+ export function withCobbaiHandler(appHandler?: ExpoNotificationHandler): ExpoNotificationHandler {
207
+ return {
208
+ handleNotification: async (notification) => {
209
+ const data = expoNotificationData(notification);
210
+
211
+ if (!isCobbaiPush(data)) {
212
+ return appHandler ? appHandler.handleNotification(notification) : HIDDEN;
213
+ }
214
+
215
+ const chatId = (data as { cobbai_chat_id?: unknown }).cobbai_chat_id;
216
+ const state = getForegroundPresentationState();
217
+ const chatShowsIt =
218
+ state.mountedChatId !== null &&
219
+ state.mountedChatId === chatId &&
220
+ (state.connected || state.bannerEnabled);
221
+
222
+ return chatShowsIt ? HIDDEN : SHOWN;
223
+ },
224
+ handleSuccess: (notificationId) => appHandler?.handleSuccess?.(notificationId),
225
+ handleError: (notificationId, error) => appHandler?.handleError?.(notificationId, error),
226
+ };
227
+ }