@talqui-oss/talqui-sdk-reactnative 0.0.0-stage → 0.1.1
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/AGENT_INSTRUCTIONS.md +182 -0
- package/LICENSE.md +21 -0
- package/README.md +280 -2
- package/dist/index.d.mts +150 -0
- package/dist/index.d.ts +150 -0
- package/dist/index.js +613 -0
- package/dist/index.mjs +581 -0
- package/package.json +83 -4
- package/src/TalquiChat.tsx +40 -0
- package/src/TalquiProvider.tsx +509 -0
- package/src/TalquiWebView.tsx +153 -0
- package/src/identity.ts +40 -0
- package/src/index.ts +13 -0
- package/src/protocol.ts +101 -0
- package/src/types.ts +70 -0
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
import { useEffect, useRef } from 'react';
|
|
2
|
+
import type { StyleProp, ViewStyle } from 'react-native';
|
|
3
|
+
|
|
4
|
+
import { useTalquiContext } from './TalquiProvider';
|
|
5
|
+
|
|
6
|
+
export interface TalquiChatProps {
|
|
7
|
+
style?: StyleProp<ViewStyle>;
|
|
8
|
+
/**
|
|
9
|
+
* Whether this screen is the one on screen (unread messages are counted
|
|
10
|
+
* while it is not). With React Navigation pass `useIsFocused()`.
|
|
11
|
+
*/
|
|
12
|
+
visible?: boolean;
|
|
13
|
+
/** The user tapped close in the chat header. */
|
|
14
|
+
onCloseRequested?: () => void;
|
|
15
|
+
/**
|
|
16
|
+
* Hides the close control in the chat header, which has nothing to close in
|
|
17
|
+
* a tab. Default `false`. Only affects the chat shown here: `open()` full
|
|
18
|
+
* screen always keeps it.
|
|
19
|
+
*/
|
|
20
|
+
hideCloseButton?: boolean;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* The chat inline, filling its container — for a "Chat" tab or a screen of
|
|
25
|
+
* your own. While it is on screen `open()` does nothing; once the screen is
|
|
26
|
+
* left (a tab navigator keeps it mounted), `open()` shows the chat full screen.
|
|
27
|
+
*/
|
|
28
|
+
export function TalquiChat({ style, visible = true, onCloseRequested, hideCloseButton = false }: TalquiChatProps) {
|
|
29
|
+
const { internals } = useTalquiContext();
|
|
30
|
+
const host = useRef({ visible, onCloseRequested, hideCloseButton });
|
|
31
|
+
host.current = { visible, onCloseRequested, hideCloseButton };
|
|
32
|
+
|
|
33
|
+
useEffect(() => internals.registerInline(host.current), [internals]);
|
|
34
|
+
useEffect(
|
|
35
|
+
() => internals.updateInline({ visible, onCloseRequested, hideCloseButton }),
|
|
36
|
+
[internals, visible, onCloseRequested, hideCloseButton],
|
|
37
|
+
);
|
|
38
|
+
|
|
39
|
+
return <>{internals.renderInline(style as object | undefined)}</>;
|
|
40
|
+
}
|
|
@@ -0,0 +1,509 @@
|
|
|
1
|
+
import {
|
|
2
|
+
createContext,
|
|
3
|
+
useCallback,
|
|
4
|
+
useContext,
|
|
5
|
+
useEffect,
|
|
6
|
+
useMemo,
|
|
7
|
+
useRef,
|
|
8
|
+
useState,
|
|
9
|
+
type ReactNode,
|
|
10
|
+
} from 'react';
|
|
11
|
+
import { AppState, BackHandler, Linking, Platform, StatusBar, StyleSheet, View } from 'react-native';
|
|
12
|
+
|
|
13
|
+
import { clearIdentity, readIdentity, writeIdentity } from './identity';
|
|
14
|
+
import {
|
|
15
|
+
buildChatUrl,
|
|
16
|
+
commandScript,
|
|
17
|
+
DEFAULT_BASE_URL,
|
|
18
|
+
isUuid,
|
|
19
|
+
normalizeMeta,
|
|
20
|
+
parseEvent,
|
|
21
|
+
USER_HASH_PATTERN,
|
|
22
|
+
type Identity,
|
|
23
|
+
} from './protocol';
|
|
24
|
+
import { TalquiWebView, type TalquiWebViewHandle } from './TalquiWebView';
|
|
25
|
+
import type {
|
|
26
|
+
TalquiApi,
|
|
27
|
+
TalquiContact,
|
|
28
|
+
TalquiEventListener,
|
|
29
|
+
TalquiEventMap,
|
|
30
|
+
TalquiEventName,
|
|
31
|
+
TalquiMeta,
|
|
32
|
+
TalquiUser,
|
|
33
|
+
} from './types';
|
|
34
|
+
|
|
35
|
+
/** How long `logout()` waits for the page to confirm it dropped the conversation. */
|
|
36
|
+
const RESET_TIMEOUT_MS = 2_000;
|
|
37
|
+
|
|
38
|
+
export interface TalquiProviderProps {
|
|
39
|
+
/** Your workspace id (app.talqui.chat → Plugins → WebChat → Installation). */
|
|
40
|
+
tenantId: string;
|
|
41
|
+
/** The WebChat connection id, on the same screen. */
|
|
42
|
+
connectionId: string;
|
|
43
|
+
/** Called for every link the user taps in the chat. Default: open it with `Linking`. */
|
|
44
|
+
onOpenUrl?: (url: string) => void;
|
|
45
|
+
/** Replaces the spinner shown while the chat loads. */
|
|
46
|
+
renderLoading?: () => ReactNode;
|
|
47
|
+
/** Replaces the screen shown when the chat cannot load. Call `retry` to try again. */
|
|
48
|
+
renderError?: (retry: () => void) => ReactNode;
|
|
49
|
+
/** Logs every message exchanged with the chat page. */
|
|
50
|
+
debug?: boolean;
|
|
51
|
+
/** @internal Points the SDK at another WebChat deployment (development only). */
|
|
52
|
+
__unstableBaseUrl?: string;
|
|
53
|
+
children: ReactNode;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
interface InlineHost {
|
|
57
|
+
visible: boolean;
|
|
58
|
+
onCloseRequested?: () => void;
|
|
59
|
+
hideCloseButton?: boolean;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
interface TalquiInternals {
|
|
63
|
+
/** The chat page for <TalquiChat />, or nothing while the full-screen overlay holds it. */
|
|
64
|
+
renderInline(style: object | undefined): ReactNode;
|
|
65
|
+
registerInline(host: InlineHost): () => void;
|
|
66
|
+
updateInline(host: InlineHost): void;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
interface TalquiContextValue {
|
|
70
|
+
api: TalquiApi;
|
|
71
|
+
internals: TalquiInternals;
|
|
72
|
+
subscribe<E extends TalquiEventName>(name: E, listener: TalquiEventListener<E>): () => void;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
const TalquiContext = createContext<TalquiContextValue | null>(null);
|
|
76
|
+
|
|
77
|
+
/** What the app told the chat, replayed every time a page (re)loads so nothing is lost across reloads. */
|
|
78
|
+
interface ReplayState {
|
|
79
|
+
contact: TalquiContact | null;
|
|
80
|
+
contactMeta: Record<string, string | null>;
|
|
81
|
+
sessionMeta: Record<string, string | null>;
|
|
82
|
+
prefill: string | null;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
const emptyReplay = (): ReplayState => ({ contact: null, contactMeta: {}, sessionMeta: {}, prefill: null });
|
|
86
|
+
|
|
87
|
+
/**
|
|
88
|
+
* Puts the Talqui chat in your app. Wrap your app once, near the root:
|
|
89
|
+
*
|
|
90
|
+
* <TalquiProvider tenantId="…" connectionId="…">
|
|
91
|
+
* <App />
|
|
92
|
+
* </TalquiProvider>
|
|
93
|
+
*
|
|
94
|
+
* then call `useTalqui().open()` anywhere, or render `<TalquiChat />` in a screen.
|
|
95
|
+
*/
|
|
96
|
+
export function TalquiProvider(props: TalquiProviderProps) {
|
|
97
|
+
const { tenantId, connectionId, onOpenUrl, renderLoading, renderError, debug, children } = props;
|
|
98
|
+
const baseUrl = props.__unstableBaseUrl ?? DEFAULT_BASE_URL;
|
|
99
|
+
const supported = Platform.OS === 'ios' || Platform.OS === 'android';
|
|
100
|
+
|
|
101
|
+
const log = useCallback((...args: unknown[]) => debug && console.log('[talqui]', ...args), [debug]);
|
|
102
|
+
const warn = useCallback((message: string) => console.warn(`[talqui] ${message}`), []);
|
|
103
|
+
|
|
104
|
+
// --- identity: who the page is booted as --------------------------------------------------
|
|
105
|
+
// `bootIdentity` decides the URL. It only changes together with `pageKey`, which remounts the
|
|
106
|
+
// WebView: a running page is never switched to another person in place.
|
|
107
|
+
const [identityLoaded, setIdentityLoaded] = useState(false);
|
|
108
|
+
const [bootIdentity, setBootIdentity] = useState<Identity | null>(null);
|
|
109
|
+
const [pageKey, setPageKey] = useState(0);
|
|
110
|
+
const identity = useRef<Identity | null>(null);
|
|
111
|
+
|
|
112
|
+
useEffect(() => {
|
|
113
|
+
if (!isUuid(tenantId) || !isUuid(connectionId)) {
|
|
114
|
+
warn('tenantId and connectionId must be the UUIDs shown on the WebChat installation screen.');
|
|
115
|
+
}
|
|
116
|
+
let active = true;
|
|
117
|
+
void readIdentity(tenantId).then((stored) => {
|
|
118
|
+
if (!active) return;
|
|
119
|
+
identity.current = stored;
|
|
120
|
+
setBootIdentity(stored);
|
|
121
|
+
setIdentityLoaded(true);
|
|
122
|
+
});
|
|
123
|
+
return () => {
|
|
124
|
+
active = false;
|
|
125
|
+
};
|
|
126
|
+
}, [tenantId, connectionId, warn]);
|
|
127
|
+
|
|
128
|
+
const url = useMemo(
|
|
129
|
+
() => buildChatUrl({ baseUrl, tenantId, connectionId, identity: bootIdentity }),
|
|
130
|
+
[baseUrl, tenantId, connectionId, bootIdentity],
|
|
131
|
+
);
|
|
132
|
+
const allowedOrigin = useMemo(() => (/^https?:\/\/[^/]+/.exec(baseUrl)?.[0] ?? baseUrl), [baseUrl]);
|
|
133
|
+
|
|
134
|
+
// --- presentation -------------------------------------------------------------------------
|
|
135
|
+
const [isOpen, setIsOpen] = useState(false);
|
|
136
|
+
const [overlayMounted, setOverlayMounted] = useState(false);
|
|
137
|
+
const [inline, setInline] = useState<InlineHost | null>(null);
|
|
138
|
+
/**
|
|
139
|
+
* Where the one chat page lives. A native view cannot move between parents,
|
|
140
|
+
* so changing owner reloads the page (the conversation comes back by itself).
|
|
141
|
+
* The owner only changes when it must: `open()` takes the page to the
|
|
142
|
+
* overlay, and it goes back to <TalquiChat /> when that screen is on screen.
|
|
143
|
+
* A tab navigator keeps a visited tab mounted, so "mounted" is not enough.
|
|
144
|
+
*/
|
|
145
|
+
const [owner, setOwner] = useState<'overlay' | 'inline'>('overlay');
|
|
146
|
+
const [appActive, setAppActive] = useState(AppState.currentState === 'active');
|
|
147
|
+
|
|
148
|
+
useEffect(() => {
|
|
149
|
+
const subscription = AppState.addEventListener('change', (state) => setAppActive(state === 'active'));
|
|
150
|
+
return () => subscription.remove();
|
|
151
|
+
}, []);
|
|
152
|
+
|
|
153
|
+
// --- page state ---------------------------------------------------------------------------
|
|
154
|
+
const [isReady, setIsReady] = useState(false);
|
|
155
|
+
const [unreadCount, setUnreadCount] = useState(0);
|
|
156
|
+
const webview = useRef<TalquiWebViewHandle | null>(null);
|
|
157
|
+
const replay = useRef<ReplayState>(emptyReplay());
|
|
158
|
+
const commandSeq = useRef(0);
|
|
159
|
+
const listeners = useRef(new Map<TalquiEventName, Set<(payload: never) => void>>());
|
|
160
|
+
const readyRef = useRef(false);
|
|
161
|
+
|
|
162
|
+
const send = useCallback(
|
|
163
|
+
(name: string, payload: object) => {
|
|
164
|
+
// Before `ready` there is nothing to send to: the replay state is delivered on `ready`.
|
|
165
|
+
if (!readyRef.current || !webview.current) return;
|
|
166
|
+
const id = `c-${++commandSeq.current}`;
|
|
167
|
+
log('→', name, payload);
|
|
168
|
+
webview.current.inject(commandScript(name, payload, id));
|
|
169
|
+
},
|
|
170
|
+
[log],
|
|
171
|
+
);
|
|
172
|
+
|
|
173
|
+
useEffect(() => {
|
|
174
|
+
if (!inline) setOwner('overlay');
|
|
175
|
+
else if (inline.visible && !isOpen) setOwner('inline');
|
|
176
|
+
}, [inline, isOpen]);
|
|
177
|
+
|
|
178
|
+
const inlineOwns = owner === 'inline' && inline !== null;
|
|
179
|
+
const visible = appActive && (inlineOwns ? inline.visible : isOpen);
|
|
180
|
+
const visibleRef = useRef(visible);
|
|
181
|
+
visibleRef.current = visible;
|
|
182
|
+
|
|
183
|
+
useEffect(() => {
|
|
184
|
+
send('setVisibility', { visible });
|
|
185
|
+
}, [visible, send]);
|
|
186
|
+
|
|
187
|
+
// The header's close control follows where the chat is: full screen always
|
|
188
|
+
// shows it (on iOS it is the only way out); inline it can be turned off.
|
|
189
|
+
const closeButtonVisible = !(inlineOwns && inline.hideCloseButton);
|
|
190
|
+
const closeButtonRef = useRef(closeButtonVisible);
|
|
191
|
+
closeButtonRef.current = closeButtonVisible;
|
|
192
|
+
/** What the loaded page shows. Sent only on a change, so an app that never hides it never sends the command. */
|
|
193
|
+
const pageCloseButton = useRef(true);
|
|
194
|
+
const syncCloseButton = useCallback(() => {
|
|
195
|
+
if (!readyRef.current || pageCloseButton.current === closeButtonRef.current) return;
|
|
196
|
+
send('setCloseButton', { visible: closeButtonRef.current });
|
|
197
|
+
pageCloseButton.current = closeButtonRef.current;
|
|
198
|
+
}, [send]);
|
|
199
|
+
|
|
200
|
+
useEffect(() => {
|
|
201
|
+
syncCloseButton();
|
|
202
|
+
}, [closeButtonVisible, syncCloseButton]);
|
|
203
|
+
|
|
204
|
+
const emit = useCallback(<E extends TalquiEventName>(name: E, payload: TalquiEventMap[E]) => {
|
|
205
|
+
listeners.current.get(name)?.forEach((listener) => {
|
|
206
|
+
try {
|
|
207
|
+
(listener as TalquiEventListener<E>)(payload);
|
|
208
|
+
} catch (error) {
|
|
209
|
+
console.error('[talqui] event listener failed', error);
|
|
210
|
+
}
|
|
211
|
+
});
|
|
212
|
+
}, []);
|
|
213
|
+
|
|
214
|
+
const replayAll = useCallback(() => {
|
|
215
|
+
const state = replay.current;
|
|
216
|
+
if (state.contact) send('setContact', state.contact);
|
|
217
|
+
if (Object.keys(state.contactMeta).length) send('setContactMeta', state.contactMeta);
|
|
218
|
+
if (Object.keys(state.sessionMeta).length) send('setSessionMeta', state.sessionMeta);
|
|
219
|
+
send('setVisibility', { visible: visibleRef.current });
|
|
220
|
+
// A freshly loaded page shows the control again.
|
|
221
|
+
pageCloseButton.current = true;
|
|
222
|
+
syncCloseButton();
|
|
223
|
+
if (state.prefill) {
|
|
224
|
+
send('prefill', { text: state.prefill });
|
|
225
|
+
state.prefill = null;
|
|
226
|
+
}
|
|
227
|
+
}, [send, syncCloseButton]);
|
|
228
|
+
|
|
229
|
+
const closeOverlay = useCallback(() => setIsOpen(false), []);
|
|
230
|
+
const inlineRef = useRef(inline);
|
|
231
|
+
inlineRef.current = inline;
|
|
232
|
+
const inlineOwnsRef = useRef(inlineOwns);
|
|
233
|
+
inlineOwnsRef.current = inlineOwns;
|
|
234
|
+
|
|
235
|
+
const handleMessage = useCallback(
|
|
236
|
+
(raw: string) => {
|
|
237
|
+
const event = parseEvent(raw);
|
|
238
|
+
if (!event) return;
|
|
239
|
+
log('←', event.name, event.payload);
|
|
240
|
+
|
|
241
|
+
switch (event.name) {
|
|
242
|
+
case 'ready': {
|
|
243
|
+
readyRef.current = true;
|
|
244
|
+
setIsReady(true);
|
|
245
|
+
// The page minted an anonymous identity: keep it, so this device stays the same visitor.
|
|
246
|
+
// The URL is not touched — the running page already is that visitor.
|
|
247
|
+
const minted = event.payload.identity?.anonymousId;
|
|
248
|
+
if (minted && !identity.current) {
|
|
249
|
+
identity.current = { kind: 'anonymous', id: minted };
|
|
250
|
+
void writeIdentity(tenantId, identity.current);
|
|
251
|
+
}
|
|
252
|
+
replayAll();
|
|
253
|
+
break;
|
|
254
|
+
}
|
|
255
|
+
case 'unreadChanged':
|
|
256
|
+
setUnreadCount(event.payload.count);
|
|
257
|
+
break;
|
|
258
|
+
case 'openUrl':
|
|
259
|
+
if (onOpenUrl) onOpenUrl(event.payload.url);
|
|
260
|
+
else void Linking.openURL(event.payload.url).catch(() => undefined);
|
|
261
|
+
break;
|
|
262
|
+
case 'closeRequested':
|
|
263
|
+
if (inlineOwnsRef.current) inlineRef.current?.onCloseRequested?.();
|
|
264
|
+
else closeOverlay();
|
|
265
|
+
break;
|
|
266
|
+
case 'error':
|
|
267
|
+
warn(`${event.payload.code}: ${event.payload.message}`);
|
|
268
|
+
break;
|
|
269
|
+
default:
|
|
270
|
+
break;
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
emit(event.name, event.payload as never);
|
|
274
|
+
},
|
|
275
|
+
[log, tenantId, replayAll, onOpenUrl, closeOverlay, warn, emit],
|
|
276
|
+
);
|
|
277
|
+
|
|
278
|
+
const handleLoadStart = useCallback(() => {
|
|
279
|
+
readyRef.current = false;
|
|
280
|
+
setIsReady(false);
|
|
281
|
+
}, []);
|
|
282
|
+
|
|
283
|
+
// A new page (another user, logout) starts with nothing unread.
|
|
284
|
+
const remount = useCallback((next: Identity | null) => {
|
|
285
|
+
readyRef.current = false;
|
|
286
|
+
setIsReady(false);
|
|
287
|
+
setUnreadCount(0);
|
|
288
|
+
setBootIdentity(next);
|
|
289
|
+
setPageKey((key) => key + 1);
|
|
290
|
+
}, []);
|
|
291
|
+
|
|
292
|
+
// --- Android back button closes the full-screen chat ---------------------------------------
|
|
293
|
+
useEffect(() => {
|
|
294
|
+
if (!isOpen) return undefined;
|
|
295
|
+
const subscription = BackHandler.addEventListener('hardwareBackPress', () => {
|
|
296
|
+
closeOverlay();
|
|
297
|
+
return true;
|
|
298
|
+
});
|
|
299
|
+
return () => subscription.remove();
|
|
300
|
+
}, [isOpen, closeOverlay]);
|
|
301
|
+
|
|
302
|
+
// --- public API -----------------------------------------------------------------------------
|
|
303
|
+
const setContact = useCallback(
|
|
304
|
+
(contact: TalquiContact) => {
|
|
305
|
+
const next = { ...replay.current.contact, ...contact };
|
|
306
|
+
replay.current.contact = next;
|
|
307
|
+
send('setContact', next);
|
|
308
|
+
},
|
|
309
|
+
[send],
|
|
310
|
+
);
|
|
311
|
+
|
|
312
|
+
const setMeta = useCallback(
|
|
313
|
+
(target: 'contactMeta' | 'sessionMeta', meta: TalquiMeta) => {
|
|
314
|
+
const normalized = normalizeMeta(meta, warn);
|
|
315
|
+
if (!Object.keys(normalized).length) return;
|
|
316
|
+
replay.current[target] = { ...replay.current[target], ...normalized };
|
|
317
|
+
send(target === 'contactMeta' ? 'setContactMeta' : 'setSessionMeta', normalized);
|
|
318
|
+
},
|
|
319
|
+
[send, warn],
|
|
320
|
+
);
|
|
321
|
+
|
|
322
|
+
const logout = useCallback(async () => {
|
|
323
|
+
if (readyRef.current && webview.current) {
|
|
324
|
+
// Ask the page to drop the conversation now (socket included), but never hang on it:
|
|
325
|
+
// the remount below discards the page either way.
|
|
326
|
+
await new Promise<void>((resolve) => {
|
|
327
|
+
const timer = setTimeout(done, RESET_TIMEOUT_MS);
|
|
328
|
+
const unsubscribe = subscribeRef.current('resetDone', done);
|
|
329
|
+
function done() {
|
|
330
|
+
clearTimeout(timer);
|
|
331
|
+
unsubscribe();
|
|
332
|
+
resolve();
|
|
333
|
+
}
|
|
334
|
+
send('reset', {});
|
|
335
|
+
});
|
|
336
|
+
}
|
|
337
|
+
await clearIdentity(tenantId);
|
|
338
|
+
identity.current = null;
|
|
339
|
+
// The previous user's details must not be replayed into the next page.
|
|
340
|
+
replay.current = emptyReplay();
|
|
341
|
+
remount(null);
|
|
342
|
+
}, [send, tenantId, remount]);
|
|
343
|
+
|
|
344
|
+
const identify = useCallback(
|
|
345
|
+
async (user: TalquiUser) => {
|
|
346
|
+
const { userHash, name, email, phone } = user;
|
|
347
|
+
if (userHash !== undefined) {
|
|
348
|
+
if (!USER_HASH_PATTERN.test(userHash)) {
|
|
349
|
+
warn('identify: userHash must be 32 to 128 chars of A-Z a-z 0-9 _ - (compute it on your backend). Ignored.');
|
|
350
|
+
} else if (identity.current?.kind !== 'identified' || identity.current.id !== userHash) {
|
|
351
|
+
const next: Identity = { kind: 'identified', id: userHash };
|
|
352
|
+
identity.current = next;
|
|
353
|
+
await writeIdentity(tenantId, next);
|
|
354
|
+
// Another person: nothing from the previous one may carry over.
|
|
355
|
+
replay.current = emptyReplay();
|
|
356
|
+
remount(next);
|
|
357
|
+
}
|
|
358
|
+
}
|
|
359
|
+
const contact: TalquiContact = {};
|
|
360
|
+
if (name) contact.name = name;
|
|
361
|
+
if (email) contact.email = email;
|
|
362
|
+
if (phone) contact.phone = phone;
|
|
363
|
+
if (Object.keys(contact).length) setContact(contact);
|
|
364
|
+
},
|
|
365
|
+
[tenantId, warn, remount, setContact],
|
|
366
|
+
);
|
|
367
|
+
|
|
368
|
+
const subscribe = useCallback(<E extends TalquiEventName>(name: E, listener: TalquiEventListener<E>) => {
|
|
369
|
+
const set = listeners.current.get(name) ?? new Set();
|
|
370
|
+
set.add(listener as (payload: never) => void);
|
|
371
|
+
listeners.current.set(name, set);
|
|
372
|
+
return () => {
|
|
373
|
+
set.delete(listener as (payload: never) => void);
|
|
374
|
+
};
|
|
375
|
+
}, []);
|
|
376
|
+
const subscribeRef = useRef(subscribe);
|
|
377
|
+
subscribeRef.current = subscribe;
|
|
378
|
+
|
|
379
|
+
const api = useMemo<TalquiApi>(() => {
|
|
380
|
+
if (!supported) {
|
|
381
|
+
const unsupported = () => warn('the chat SDK runs on iOS and Android only; on the web use the WebChat snippet.');
|
|
382
|
+
return {
|
|
383
|
+
open: unsupported,
|
|
384
|
+
close: unsupported,
|
|
385
|
+
preload: unsupported,
|
|
386
|
+
identify: async () => unsupported(),
|
|
387
|
+
setContact: unsupported,
|
|
388
|
+
setContactMeta: unsupported,
|
|
389
|
+
setSessionMeta: unsupported,
|
|
390
|
+
prefill: unsupported,
|
|
391
|
+
logout: async () => unsupported(),
|
|
392
|
+
unreadCount: 0,
|
|
393
|
+
isReady: false,
|
|
394
|
+
isOpen: false,
|
|
395
|
+
};
|
|
396
|
+
}
|
|
397
|
+
return {
|
|
398
|
+
open: () => {
|
|
399
|
+
if (inlineRef.current?.visible) {
|
|
400
|
+
warn('open() ignored: <TalquiChat /> is on screen and already shows the chat.');
|
|
401
|
+
return;
|
|
402
|
+
}
|
|
403
|
+
setOwner('overlay');
|
|
404
|
+
setOverlayMounted(true);
|
|
405
|
+
setIsOpen(true);
|
|
406
|
+
},
|
|
407
|
+
close: closeOverlay,
|
|
408
|
+
preload: () => setOverlayMounted(true),
|
|
409
|
+
identify,
|
|
410
|
+
setContact,
|
|
411
|
+
setContactMeta: (meta) => setMeta('contactMeta', meta),
|
|
412
|
+
setSessionMeta: (meta) => setMeta('sessionMeta', meta),
|
|
413
|
+
prefill: (text) => {
|
|
414
|
+
const trimmed = typeof text === 'string' ? text.trim().slice(0, 1000) : '';
|
|
415
|
+
if (!trimmed) return;
|
|
416
|
+
if (readyRef.current) send('prefill', { text: trimmed });
|
|
417
|
+
else replay.current.prefill = trimmed;
|
|
418
|
+
},
|
|
419
|
+
logout,
|
|
420
|
+
unreadCount,
|
|
421
|
+
isReady,
|
|
422
|
+
isOpen,
|
|
423
|
+
};
|
|
424
|
+
}, [supported, warn, closeOverlay, identify, setContact, setMeta, send, logout, unreadCount, isReady, isOpen]);
|
|
425
|
+
|
|
426
|
+
// --- rendering --------------------------------------------------------------------------------
|
|
427
|
+
const renderWebView = useCallback(
|
|
428
|
+
(style: object | undefined) =>
|
|
429
|
+
identityLoaded ? (
|
|
430
|
+
<TalquiWebView
|
|
431
|
+
key={pageKey}
|
|
432
|
+
ref={webview}
|
|
433
|
+
url={url}
|
|
434
|
+
allowedOrigin={allowedOrigin}
|
|
435
|
+
isReady={isReady}
|
|
436
|
+
onMessage={handleMessage}
|
|
437
|
+
onLoadStart={handleLoadStart}
|
|
438
|
+
onOpenUrl={onOpenUrl}
|
|
439
|
+
renderLoading={renderLoading}
|
|
440
|
+
renderError={renderError}
|
|
441
|
+
style={style}
|
|
442
|
+
debug={debug}
|
|
443
|
+
/>
|
|
444
|
+
) : null,
|
|
445
|
+
[identityLoaded, pageKey, url, allowedOrigin, isReady, handleMessage, handleLoadStart, onOpenUrl, renderLoading, renderError, debug],
|
|
446
|
+
);
|
|
447
|
+
|
|
448
|
+
const internals = useMemo<TalquiInternals>(
|
|
449
|
+
() => ({
|
|
450
|
+
renderInline: (style) => (inlineOwns ? renderWebView(style) : null),
|
|
451
|
+
registerInline: (host) => {
|
|
452
|
+
setInline(host);
|
|
453
|
+
// A chat screen coming on screen takes over from the full-screen chat.
|
|
454
|
+
if (host.visible) setIsOpen(false);
|
|
455
|
+
return () => setInline(null);
|
|
456
|
+
},
|
|
457
|
+
updateInline: (host) => setInline(host),
|
|
458
|
+
}),
|
|
459
|
+
[renderWebView, inlineOwns],
|
|
460
|
+
);
|
|
461
|
+
|
|
462
|
+
const value = useMemo(() => ({ api, internals, subscribe }), [api, internals, subscribe]);
|
|
463
|
+
|
|
464
|
+
return (
|
|
465
|
+
<TalquiContext.Provider value={value}>
|
|
466
|
+
{children}
|
|
467
|
+
{/* One chat page at a time, held by its owner (see `owner`). */}
|
|
468
|
+
{supported && overlayMounted && !inlineOwns && (
|
|
469
|
+
<View style={[styles.overlay, !isOpen && styles.hidden]} pointerEvents={isOpen ? 'auto' : 'none'}>
|
|
470
|
+
{renderWebView(undefined)}
|
|
471
|
+
</View>
|
|
472
|
+
)}
|
|
473
|
+
</TalquiContext.Provider>
|
|
474
|
+
);
|
|
475
|
+
}
|
|
476
|
+
|
|
477
|
+
/** The Talqui chat API. Must be used under `<TalquiProvider>`. */
|
|
478
|
+
export function useTalqui(): TalquiApi {
|
|
479
|
+
return useTalquiContext().api;
|
|
480
|
+
}
|
|
481
|
+
|
|
482
|
+
/** Runs `listener` for every `name` event from the chat while the component is mounted. */
|
|
483
|
+
export function useTalquiEvent<E extends TalquiEventName>(name: E, listener: TalquiEventListener<E>): void {
|
|
484
|
+
const { subscribe } = useTalquiContext();
|
|
485
|
+
const latest = useRef(listener);
|
|
486
|
+
latest.current = listener;
|
|
487
|
+
useEffect(() => subscribe(name, (payload) => latest.current(payload)), [subscribe, name]);
|
|
488
|
+
}
|
|
489
|
+
|
|
490
|
+
export function useTalquiContext(): TalquiContextValue {
|
|
491
|
+
const context = useContext(TalquiContext);
|
|
492
|
+
if (!context) {
|
|
493
|
+
throw new Error('[talqui] useTalqui must be used inside <TalquiProvider>.');
|
|
494
|
+
}
|
|
495
|
+
return context;
|
|
496
|
+
}
|
|
497
|
+
|
|
498
|
+
const styles = StyleSheet.create({
|
|
499
|
+
overlay: {
|
|
500
|
+
position: 'absolute', top: 0, right: 0, bottom: 0, left: 0,
|
|
501
|
+
zIndex: 1000,
|
|
502
|
+
elevation: 1000,
|
|
503
|
+
backgroundColor: '#FFFFFF',
|
|
504
|
+
// Android draws the app under the status bar; the page only knows about the iOS safe areas.
|
|
505
|
+
paddingTop: Platform.OS === 'android' ? (StatusBar.currentHeight ?? 0) : 0,
|
|
506
|
+
},
|
|
507
|
+
// Hidden, not unmounted: the conversation keeps running so unread messages are counted.
|
|
508
|
+
hidden: { opacity: 0, transform: [{ translateY: 100_000 }] },
|
|
509
|
+
});
|
|
@@ -0,0 +1,153 @@
|
|
|
1
|
+
import { forwardRef, useCallback, useEffect, useImperativeHandle, useRef, useState, type ReactNode } from 'react';
|
|
2
|
+
import { ActivityIndicator, Linking, Platform, Pressable, StyleSheet, Text, View, type StyleProp, type ViewStyle } from 'react-native';
|
|
3
|
+
import { WebView, type WebViewMessageEvent } from 'react-native-webview';
|
|
4
|
+
import type { ShouldStartLoadRequest } from 'react-native-webview/lib/WebViewTypes';
|
|
5
|
+
|
|
6
|
+
/** How long the page may take to say it is ready before it is reloaded once, then shown as failed. */
|
|
7
|
+
const READY_TIMEOUT_MS = 15_000;
|
|
8
|
+
const BACKGROUND = '#FFFFFF';
|
|
9
|
+
|
|
10
|
+
export interface TalquiWebViewHandle {
|
|
11
|
+
inject(script: string): void;
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
interface Props {
|
|
15
|
+
url: string;
|
|
16
|
+
/** Origin the WebView may navigate to; every other link goes to the system. */
|
|
17
|
+
allowedOrigin: string;
|
|
18
|
+
isReady: boolean;
|
|
19
|
+
onMessage(raw: string): void;
|
|
20
|
+
onLoadStart(): void;
|
|
21
|
+
onOpenUrl?: (url: string) => void;
|
|
22
|
+
renderLoading?: () => ReactNode;
|
|
23
|
+
renderError?: (retry: () => void) => ReactNode;
|
|
24
|
+
style?: StyleProp<ViewStyle>;
|
|
25
|
+
debug?: boolean;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* The WebView that runs the chat page, with everything that tends to go wrong
|
|
30
|
+
* in a chat WebView handled here once:
|
|
31
|
+
*
|
|
32
|
+
* - links never navigate inside it (they would replace the chat with no way back);
|
|
33
|
+
* - camera, microphone, inline media and file pickers are allowed;
|
|
34
|
+
* - a page killed by the OS in the background (blank white screen) is reloaded;
|
|
35
|
+
* - a page that never becomes ready is reloaded once, then shown as failed with a retry.
|
|
36
|
+
*/
|
|
37
|
+
export const TalquiWebView = forwardRef<TalquiWebViewHandle, Props>(function TalquiWebView(props, ref) {
|
|
38
|
+
const { url, allowedOrigin, isReady, onMessage, onLoadStart, onOpenUrl, renderLoading, renderError, style, debug } = props;
|
|
39
|
+
const webview = useRef<WebView>(null);
|
|
40
|
+
const [attempt, setAttempt] = useState(0);
|
|
41
|
+
const [failed, setFailed] = useState(false);
|
|
42
|
+
|
|
43
|
+
useImperativeHandle(ref, () => ({ inject: (script) => webview.current?.injectJavaScript(script) }), []);
|
|
44
|
+
|
|
45
|
+
// Watchdog: restarted on every new page (url) and every reload attempt.
|
|
46
|
+
useEffect(() => {
|
|
47
|
+
if (isReady || failed) return undefined;
|
|
48
|
+
const timer = setTimeout(() => {
|
|
49
|
+
if (attempt === 0) {
|
|
50
|
+
if (debug) console.log('[talqui] chat did not become ready, reloading once');
|
|
51
|
+
setAttempt(1);
|
|
52
|
+
webview.current?.reload();
|
|
53
|
+
} else {
|
|
54
|
+
setFailed(true);
|
|
55
|
+
}
|
|
56
|
+
}, READY_TIMEOUT_MS);
|
|
57
|
+
return () => clearTimeout(timer);
|
|
58
|
+
}, [isReady, failed, attempt, url, debug]);
|
|
59
|
+
|
|
60
|
+
useEffect(() => {
|
|
61
|
+
setAttempt(0);
|
|
62
|
+
setFailed(false);
|
|
63
|
+
}, [url]);
|
|
64
|
+
|
|
65
|
+
const retry = useCallback(() => {
|
|
66
|
+
setAttempt(0);
|
|
67
|
+
setFailed(false);
|
|
68
|
+
webview.current?.reload();
|
|
69
|
+
}, []);
|
|
70
|
+
|
|
71
|
+
const openOutside = useCallback(
|
|
72
|
+
(target: string) => {
|
|
73
|
+
if (onOpenUrl) onOpenUrl(target);
|
|
74
|
+
else void Linking.openURL(target).catch(() => undefined);
|
|
75
|
+
},
|
|
76
|
+
[onOpenUrl],
|
|
77
|
+
);
|
|
78
|
+
|
|
79
|
+
const shouldStart = useCallback(
|
|
80
|
+
(request: ShouldStartLoadRequest) => {
|
|
81
|
+
// Sub-frames (embedded media) load freely; only the page itself is guarded.
|
|
82
|
+
if (request.isTopFrame === false) return true;
|
|
83
|
+
if (request.url === 'about:blank' || request.url.startsWith(allowedOrigin)) return true;
|
|
84
|
+
openOutside(request.url);
|
|
85
|
+
return false;
|
|
86
|
+
},
|
|
87
|
+
[allowedOrigin, openOutside],
|
|
88
|
+
);
|
|
89
|
+
|
|
90
|
+
const reloadAfterCrash = useCallback(() => webview.current?.reload(), []);
|
|
91
|
+
|
|
92
|
+
return (
|
|
93
|
+
<View style={[styles.root, style]}>
|
|
94
|
+
<WebView
|
|
95
|
+
ref={webview}
|
|
96
|
+
source={{ uri: url }}
|
|
97
|
+
originWhitelist={['*']}
|
|
98
|
+
onShouldStartLoadWithRequest={shouldStart}
|
|
99
|
+
onMessage={(event: WebViewMessageEvent) => onMessage(event.nativeEvent.data)}
|
|
100
|
+
onLoadStart={onLoadStart}
|
|
101
|
+
onContentProcessDidTerminate={reloadAfterCrash}
|
|
102
|
+
onRenderProcessGone={() => {
|
|
103
|
+
reloadAfterCrash();
|
|
104
|
+
return true;
|
|
105
|
+
}}
|
|
106
|
+
javaScriptEnabled
|
|
107
|
+
domStorageEnabled
|
|
108
|
+
allowsInlineMediaPlayback
|
|
109
|
+
mediaPlaybackRequiresUserAction={false}
|
|
110
|
+
mediaCapturePermissionGrantType="grantIfSameHostElsePrompt"
|
|
111
|
+
allowFileAccess
|
|
112
|
+
setSupportMultipleWindows={false}
|
|
113
|
+
keyboardDisplayRequiresUserAction={false}
|
|
114
|
+
// The page draws its own safe areas (viewport-fit=cover).
|
|
115
|
+
contentInsetAdjustmentBehavior="never"
|
|
116
|
+
automaticallyAdjustContentInsets={false}
|
|
117
|
+
bounces={false}
|
|
118
|
+
overScrollMode="never"
|
|
119
|
+
style={styles.webview}
|
|
120
|
+
webviewDebuggingEnabled={debug === true}
|
|
121
|
+
/>
|
|
122
|
+
{!isReady && !failed && (
|
|
123
|
+
<View style={styles.cover} pointerEvents="none">
|
|
124
|
+
{renderLoading ? renderLoading() : <ActivityIndicator />}
|
|
125
|
+
</View>
|
|
126
|
+
)}
|
|
127
|
+
{failed && (
|
|
128
|
+
<View style={styles.cover}>
|
|
129
|
+
{renderError ? (
|
|
130
|
+
renderError(retry)
|
|
131
|
+
) : (
|
|
132
|
+
<View style={styles.error}>
|
|
133
|
+
<Text style={styles.errorText}>Não foi possível carregar o chat.</Text>
|
|
134
|
+
<Pressable accessibilityRole="button" onPress={retry} style={styles.retry} hitSlop={8}>
|
|
135
|
+
<Text style={styles.retryText}>Tentar de novo</Text>
|
|
136
|
+
</Pressable>
|
|
137
|
+
</View>
|
|
138
|
+
)}
|
|
139
|
+
</View>
|
|
140
|
+
)}
|
|
141
|
+
</View>
|
|
142
|
+
);
|
|
143
|
+
});
|
|
144
|
+
|
|
145
|
+
const styles = StyleSheet.create({
|
|
146
|
+
root: { flex: 1, backgroundColor: BACKGROUND },
|
|
147
|
+
webview: { flex: 1, backgroundColor: BACKGROUND },
|
|
148
|
+
cover: { position: 'absolute', top: 0, right: 0, bottom: 0, left: 0, alignItems: 'center', justifyContent: 'center', backgroundColor: BACKGROUND },
|
|
149
|
+
error: { alignItems: 'center', gap: 12, padding: 24 },
|
|
150
|
+
errorText: { fontSize: 15, color: '#353849', textAlign: 'center' },
|
|
151
|
+
retry: { paddingHorizontal: 16, paddingVertical: 10, borderRadius: 8, backgroundColor: '#1A66FF', minHeight: 44, justifyContent: 'center' },
|
|
152
|
+
retryText: { color: '#FFFFFF', fontSize: 15, fontWeight: Platform.OS === 'ios' ? '600' : 'bold' },
|
|
153
|
+
});
|