@talqui-oss/talqui-sdk-reactnative 0.0.0-stage → 0.1.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.
- package/LICENSE.md +21 -0
- package/README.md +274 -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 +82 -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
package/dist/index.mjs
ADDED
|
@@ -0,0 +1,581 @@
|
|
|
1
|
+
// src/TalquiProvider.tsx
|
|
2
|
+
import {
|
|
3
|
+
createContext,
|
|
4
|
+
useCallback as useCallback2,
|
|
5
|
+
useContext,
|
|
6
|
+
useEffect as useEffect2,
|
|
7
|
+
useMemo,
|
|
8
|
+
useRef as useRef2,
|
|
9
|
+
useState as useState2
|
|
10
|
+
} from "react";
|
|
11
|
+
import { AppState, BackHandler, Linking as Linking2, Platform as Platform2, StatusBar, StyleSheet as StyleSheet2, View as View2 } from "react-native";
|
|
12
|
+
|
|
13
|
+
// src/identity.ts
|
|
14
|
+
import AsyncStorage from "@react-native-async-storage/async-storage";
|
|
15
|
+
|
|
16
|
+
// src/protocol.ts
|
|
17
|
+
var PROTOCOL = 1;
|
|
18
|
+
var DEFAULT_BASE_URL = "https://webchat.talqui.chat";
|
|
19
|
+
var SDK_LABEL = "react-native@0.1.0";
|
|
20
|
+
var UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
|
|
21
|
+
var IDENTITY_PATTERN = /^[A-Za-z0-9_-]{8,128}$/;
|
|
22
|
+
var USER_HASH_PATTERN = /^[A-Za-z0-9_-]{32,128}$/;
|
|
23
|
+
var META_KEY = /^[a-z0-9_-]{1,60}$/;
|
|
24
|
+
var UNSAFE_KEYS = ["__proto__", "constructor", "prototype"];
|
|
25
|
+
function isUuid(value) {
|
|
26
|
+
return UUID.test(value);
|
|
27
|
+
}
|
|
28
|
+
function buildChatUrl(options) {
|
|
29
|
+
const query = new URLSearchParams({
|
|
30
|
+
T_ID: options.tenantId,
|
|
31
|
+
PC_ID: options.connectionId,
|
|
32
|
+
EMBED: "1",
|
|
33
|
+
SDK: SDK_LABEL
|
|
34
|
+
});
|
|
35
|
+
if (options.identity) {
|
|
36
|
+
query.set(options.identity.kind === "identified" ? "S_ID" : "A_ID", options.identity.id);
|
|
37
|
+
}
|
|
38
|
+
return `${options.baseUrl.replace(/\/+$/, "")}/#/chat?${query.toString()}`;
|
|
39
|
+
}
|
|
40
|
+
function commandScript(name, payload, id) {
|
|
41
|
+
const json = JSON.stringify({ talqui: PROTOCOL, kind: "command", name, id, payload });
|
|
42
|
+
return `window.TalquiBridge&&window.TalquiBridge.receive(${JSON.stringify(json)});true;`;
|
|
43
|
+
}
|
|
44
|
+
function parseEvent(raw) {
|
|
45
|
+
let message;
|
|
46
|
+
try {
|
|
47
|
+
message = JSON.parse(raw);
|
|
48
|
+
} catch {
|
|
49
|
+
return null;
|
|
50
|
+
}
|
|
51
|
+
if (typeof message !== "object" || message === null) return null;
|
|
52
|
+
const { talqui, kind, name, payload } = message;
|
|
53
|
+
if (talqui !== PROTOCOL || kind !== "event" || typeof name !== "string") return null;
|
|
54
|
+
return { name, payload: typeof payload === "object" && payload !== null ? payload : {} };
|
|
55
|
+
}
|
|
56
|
+
function normalizeMeta(meta, warn) {
|
|
57
|
+
const out = {};
|
|
58
|
+
if (typeof meta !== "object" || meta === null || Array.isArray(meta)) {
|
|
59
|
+
warn("metadata must be an object of key/value pairs; ignored.");
|
|
60
|
+
return out;
|
|
61
|
+
}
|
|
62
|
+
for (const rawKey of Object.getOwnPropertyNames(meta)) {
|
|
63
|
+
const key2 = rawKey.trim().toLowerCase().replace(/\s+/g, "_");
|
|
64
|
+
if (key2 !== rawKey) warn(`metadata key "${rawKey}" was sent as "${key2}".`);
|
|
65
|
+
if (!META_KEY.test(key2) || UNSAFE_KEYS.includes(key2)) {
|
|
66
|
+
warn(`metadata key "${rawKey}" ignored: use lowercase letters, digits, "_" and "-" (max 60 chars).`);
|
|
67
|
+
continue;
|
|
68
|
+
}
|
|
69
|
+
const value = meta[rawKey];
|
|
70
|
+
if (value === null) {
|
|
71
|
+
out[key2] = null;
|
|
72
|
+
} else if (typeof value === "string") {
|
|
73
|
+
out[key2] = value.trim().slice(0, 255);
|
|
74
|
+
} else if (typeof value === "number" && Number.isFinite(value)) {
|
|
75
|
+
out[key2] = String(value);
|
|
76
|
+
} else if (typeof value === "boolean") {
|
|
77
|
+
out[key2] = String(value);
|
|
78
|
+
} else {
|
|
79
|
+
warn(`metadata "${rawKey}" ignored: values are strings, numbers, booleans or null.`);
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
return out;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
// src/identity.ts
|
|
86
|
+
var key = (tenantId) => `talqui:identity:${tenantId}`;
|
|
87
|
+
async function readIdentity(tenantId) {
|
|
88
|
+
try {
|
|
89
|
+
const raw = await AsyncStorage.getItem(key(tenantId));
|
|
90
|
+
const parsed = raw ? JSON.parse(raw) : null;
|
|
91
|
+
if (parsed && (parsed.kind === "anonymous" || parsed.kind === "identified") && IDENTITY_PATTERN.test(parsed.id)) {
|
|
92
|
+
return parsed;
|
|
93
|
+
}
|
|
94
|
+
} catch {
|
|
95
|
+
}
|
|
96
|
+
return null;
|
|
97
|
+
}
|
|
98
|
+
async function writeIdentity(tenantId, identity) {
|
|
99
|
+
try {
|
|
100
|
+
await AsyncStorage.setItem(key(tenantId), JSON.stringify(identity));
|
|
101
|
+
} catch {
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
async function clearIdentity(tenantId) {
|
|
105
|
+
try {
|
|
106
|
+
await AsyncStorage.removeItem(key(tenantId));
|
|
107
|
+
} catch {
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
// src/TalquiWebView.tsx
|
|
112
|
+
import { forwardRef, useCallback, useEffect, useImperativeHandle, useRef, useState } from "react";
|
|
113
|
+
import { ActivityIndicator, Linking, Platform, Pressable, StyleSheet, Text, View } from "react-native";
|
|
114
|
+
import { WebView } from "react-native-webview";
|
|
115
|
+
import { jsx, jsxs } from "react/jsx-runtime";
|
|
116
|
+
var READY_TIMEOUT_MS = 15e3;
|
|
117
|
+
var BACKGROUND = "#FFFFFF";
|
|
118
|
+
var TalquiWebView = forwardRef(function TalquiWebView2(props, ref) {
|
|
119
|
+
const { url, allowedOrigin, isReady, onMessage, onLoadStart, onOpenUrl, renderLoading, renderError, style, debug } = props;
|
|
120
|
+
const webview = useRef(null);
|
|
121
|
+
const [attempt, setAttempt] = useState(0);
|
|
122
|
+
const [failed, setFailed] = useState(false);
|
|
123
|
+
useImperativeHandle(ref, () => ({ inject: (script) => webview.current?.injectJavaScript(script) }), []);
|
|
124
|
+
useEffect(() => {
|
|
125
|
+
if (isReady || failed) return void 0;
|
|
126
|
+
const timer = setTimeout(() => {
|
|
127
|
+
if (attempt === 0) {
|
|
128
|
+
if (debug) console.log("[talqui] chat did not become ready, reloading once");
|
|
129
|
+
setAttempt(1);
|
|
130
|
+
webview.current?.reload();
|
|
131
|
+
} else {
|
|
132
|
+
setFailed(true);
|
|
133
|
+
}
|
|
134
|
+
}, READY_TIMEOUT_MS);
|
|
135
|
+
return () => clearTimeout(timer);
|
|
136
|
+
}, [isReady, failed, attempt, url, debug]);
|
|
137
|
+
useEffect(() => {
|
|
138
|
+
setAttempt(0);
|
|
139
|
+
setFailed(false);
|
|
140
|
+
}, [url]);
|
|
141
|
+
const retry = useCallback(() => {
|
|
142
|
+
setAttempt(0);
|
|
143
|
+
setFailed(false);
|
|
144
|
+
webview.current?.reload();
|
|
145
|
+
}, []);
|
|
146
|
+
const openOutside = useCallback(
|
|
147
|
+
(target) => {
|
|
148
|
+
if (onOpenUrl) onOpenUrl(target);
|
|
149
|
+
else void Linking.openURL(target).catch(() => void 0);
|
|
150
|
+
},
|
|
151
|
+
[onOpenUrl]
|
|
152
|
+
);
|
|
153
|
+
const shouldStart = useCallback(
|
|
154
|
+
(request) => {
|
|
155
|
+
if (request.isTopFrame === false) return true;
|
|
156
|
+
if (request.url === "about:blank" || request.url.startsWith(allowedOrigin)) return true;
|
|
157
|
+
openOutside(request.url);
|
|
158
|
+
return false;
|
|
159
|
+
},
|
|
160
|
+
[allowedOrigin, openOutside]
|
|
161
|
+
);
|
|
162
|
+
const reloadAfterCrash = useCallback(() => webview.current?.reload(), []);
|
|
163
|
+
return /* @__PURE__ */ jsxs(View, { style: [styles.root, style], children: [
|
|
164
|
+
/* @__PURE__ */ jsx(
|
|
165
|
+
WebView,
|
|
166
|
+
{
|
|
167
|
+
ref: webview,
|
|
168
|
+
source: { uri: url },
|
|
169
|
+
originWhitelist: ["*"],
|
|
170
|
+
onShouldStartLoadWithRequest: shouldStart,
|
|
171
|
+
onMessage: (event) => onMessage(event.nativeEvent.data),
|
|
172
|
+
onLoadStart,
|
|
173
|
+
onContentProcessDidTerminate: reloadAfterCrash,
|
|
174
|
+
onRenderProcessGone: () => {
|
|
175
|
+
reloadAfterCrash();
|
|
176
|
+
return true;
|
|
177
|
+
},
|
|
178
|
+
javaScriptEnabled: true,
|
|
179
|
+
domStorageEnabled: true,
|
|
180
|
+
allowsInlineMediaPlayback: true,
|
|
181
|
+
mediaPlaybackRequiresUserAction: false,
|
|
182
|
+
mediaCapturePermissionGrantType: "grantIfSameHostElsePrompt",
|
|
183
|
+
allowFileAccess: true,
|
|
184
|
+
setSupportMultipleWindows: false,
|
|
185
|
+
keyboardDisplayRequiresUserAction: false,
|
|
186
|
+
contentInsetAdjustmentBehavior: "never",
|
|
187
|
+
automaticallyAdjustContentInsets: false,
|
|
188
|
+
bounces: false,
|
|
189
|
+
overScrollMode: "never",
|
|
190
|
+
style: styles.webview,
|
|
191
|
+
webviewDebuggingEnabled: debug === true
|
|
192
|
+
}
|
|
193
|
+
),
|
|
194
|
+
!isReady && !failed && /* @__PURE__ */ jsx(View, { style: styles.cover, pointerEvents: "none", children: renderLoading ? renderLoading() : /* @__PURE__ */ jsx(ActivityIndicator, {}) }),
|
|
195
|
+
failed && /* @__PURE__ */ jsx(View, { style: styles.cover, children: renderError ? renderError(retry) : /* @__PURE__ */ jsxs(View, { style: styles.error, children: [
|
|
196
|
+
/* @__PURE__ */ jsx(Text, { style: styles.errorText, children: "N\xE3o foi poss\xEDvel carregar o chat." }),
|
|
197
|
+
/* @__PURE__ */ jsx(Pressable, { accessibilityRole: "button", onPress: retry, style: styles.retry, hitSlop: 8, children: /* @__PURE__ */ jsx(Text, { style: styles.retryText, children: "Tentar de novo" }) })
|
|
198
|
+
] }) })
|
|
199
|
+
] });
|
|
200
|
+
});
|
|
201
|
+
var styles = StyleSheet.create({
|
|
202
|
+
root: { flex: 1, backgroundColor: BACKGROUND },
|
|
203
|
+
webview: { flex: 1, backgroundColor: BACKGROUND },
|
|
204
|
+
cover: { position: "absolute", top: 0, right: 0, bottom: 0, left: 0, alignItems: "center", justifyContent: "center", backgroundColor: BACKGROUND },
|
|
205
|
+
error: { alignItems: "center", gap: 12, padding: 24 },
|
|
206
|
+
errorText: { fontSize: 15, color: "#353849", textAlign: "center" },
|
|
207
|
+
retry: { paddingHorizontal: 16, paddingVertical: 10, borderRadius: 8, backgroundColor: "#1A66FF", minHeight: 44, justifyContent: "center" },
|
|
208
|
+
retryText: { color: "#FFFFFF", fontSize: 15, fontWeight: Platform.OS === "ios" ? "600" : "bold" }
|
|
209
|
+
});
|
|
210
|
+
|
|
211
|
+
// src/TalquiProvider.tsx
|
|
212
|
+
import { jsx as jsx2, jsxs as jsxs2 } from "react/jsx-runtime";
|
|
213
|
+
var RESET_TIMEOUT_MS = 2e3;
|
|
214
|
+
var TalquiContext = createContext(null);
|
|
215
|
+
var emptyReplay = () => ({ contact: null, contactMeta: {}, sessionMeta: {}, prefill: null });
|
|
216
|
+
function TalquiProvider(props) {
|
|
217
|
+
const { tenantId, connectionId, onOpenUrl, renderLoading, renderError, debug, children } = props;
|
|
218
|
+
const baseUrl = props.__unstableBaseUrl ?? DEFAULT_BASE_URL;
|
|
219
|
+
const supported = Platform2.OS === "ios" || Platform2.OS === "android";
|
|
220
|
+
const log = useCallback2((...args) => debug && console.log("[talqui]", ...args), [debug]);
|
|
221
|
+
const warn = useCallback2((message) => console.warn(`[talqui] ${message}`), []);
|
|
222
|
+
const [identityLoaded, setIdentityLoaded] = useState2(false);
|
|
223
|
+
const [bootIdentity, setBootIdentity] = useState2(null);
|
|
224
|
+
const [pageKey, setPageKey] = useState2(0);
|
|
225
|
+
const identity = useRef2(null);
|
|
226
|
+
useEffect2(() => {
|
|
227
|
+
if (!isUuid(tenantId) || !isUuid(connectionId)) {
|
|
228
|
+
warn("tenantId and connectionId must be the UUIDs shown on the WebChat installation screen.");
|
|
229
|
+
}
|
|
230
|
+
let active = true;
|
|
231
|
+
void readIdentity(tenantId).then((stored) => {
|
|
232
|
+
if (!active) return;
|
|
233
|
+
identity.current = stored;
|
|
234
|
+
setBootIdentity(stored);
|
|
235
|
+
setIdentityLoaded(true);
|
|
236
|
+
});
|
|
237
|
+
return () => {
|
|
238
|
+
active = false;
|
|
239
|
+
};
|
|
240
|
+
}, [tenantId, connectionId, warn]);
|
|
241
|
+
const url = useMemo(
|
|
242
|
+
() => buildChatUrl({ baseUrl, tenantId, connectionId, identity: bootIdentity }),
|
|
243
|
+
[baseUrl, tenantId, connectionId, bootIdentity]
|
|
244
|
+
);
|
|
245
|
+
const allowedOrigin = useMemo(() => /^https?:\/\/[^/]+/.exec(baseUrl)?.[0] ?? baseUrl, [baseUrl]);
|
|
246
|
+
const [isOpen, setIsOpen] = useState2(false);
|
|
247
|
+
const [overlayMounted, setOverlayMounted] = useState2(false);
|
|
248
|
+
const [inline, setInline] = useState2(null);
|
|
249
|
+
const [owner, setOwner] = useState2("overlay");
|
|
250
|
+
const [appActive, setAppActive] = useState2(AppState.currentState === "active");
|
|
251
|
+
useEffect2(() => {
|
|
252
|
+
const subscription = AppState.addEventListener("change", (state) => setAppActive(state === "active"));
|
|
253
|
+
return () => subscription.remove();
|
|
254
|
+
}, []);
|
|
255
|
+
const [isReady, setIsReady] = useState2(false);
|
|
256
|
+
const [unreadCount, setUnreadCount] = useState2(0);
|
|
257
|
+
const webview = useRef2(null);
|
|
258
|
+
const replay = useRef2(emptyReplay());
|
|
259
|
+
const commandSeq = useRef2(0);
|
|
260
|
+
const listeners = useRef2(/* @__PURE__ */ new Map());
|
|
261
|
+
const readyRef = useRef2(false);
|
|
262
|
+
const send = useCallback2(
|
|
263
|
+
(name, payload) => {
|
|
264
|
+
if (!readyRef.current || !webview.current) return;
|
|
265
|
+
const id = `c-${++commandSeq.current}`;
|
|
266
|
+
log("\u2192", name, payload);
|
|
267
|
+
webview.current.inject(commandScript(name, payload, id));
|
|
268
|
+
},
|
|
269
|
+
[log]
|
|
270
|
+
);
|
|
271
|
+
useEffect2(() => {
|
|
272
|
+
if (!inline) setOwner("overlay");
|
|
273
|
+
else if (inline.visible && !isOpen) setOwner("inline");
|
|
274
|
+
}, [inline, isOpen]);
|
|
275
|
+
const inlineOwns = owner === "inline" && inline !== null;
|
|
276
|
+
const visible = appActive && (inlineOwns ? inline.visible : isOpen);
|
|
277
|
+
const visibleRef = useRef2(visible);
|
|
278
|
+
visibleRef.current = visible;
|
|
279
|
+
useEffect2(() => {
|
|
280
|
+
send("setVisibility", { visible });
|
|
281
|
+
}, [visible, send]);
|
|
282
|
+
const closeButtonVisible = !(inlineOwns && inline.hideCloseButton);
|
|
283
|
+
const closeButtonRef = useRef2(closeButtonVisible);
|
|
284
|
+
closeButtonRef.current = closeButtonVisible;
|
|
285
|
+
const pageCloseButton = useRef2(true);
|
|
286
|
+
const syncCloseButton = useCallback2(() => {
|
|
287
|
+
if (!readyRef.current || pageCloseButton.current === closeButtonRef.current) return;
|
|
288
|
+
send("setCloseButton", { visible: closeButtonRef.current });
|
|
289
|
+
pageCloseButton.current = closeButtonRef.current;
|
|
290
|
+
}, [send]);
|
|
291
|
+
useEffect2(() => {
|
|
292
|
+
syncCloseButton();
|
|
293
|
+
}, [closeButtonVisible, syncCloseButton]);
|
|
294
|
+
const emit = useCallback2((name, payload) => {
|
|
295
|
+
listeners.current.get(name)?.forEach((listener) => {
|
|
296
|
+
try {
|
|
297
|
+
listener(payload);
|
|
298
|
+
} catch (error) {
|
|
299
|
+
console.error("[talqui] event listener failed", error);
|
|
300
|
+
}
|
|
301
|
+
});
|
|
302
|
+
}, []);
|
|
303
|
+
const replayAll = useCallback2(() => {
|
|
304
|
+
const state = replay.current;
|
|
305
|
+
if (state.contact) send("setContact", state.contact);
|
|
306
|
+
if (Object.keys(state.contactMeta).length) send("setContactMeta", state.contactMeta);
|
|
307
|
+
if (Object.keys(state.sessionMeta).length) send("setSessionMeta", state.sessionMeta);
|
|
308
|
+
send("setVisibility", { visible: visibleRef.current });
|
|
309
|
+
pageCloseButton.current = true;
|
|
310
|
+
syncCloseButton();
|
|
311
|
+
if (state.prefill) {
|
|
312
|
+
send("prefill", { text: state.prefill });
|
|
313
|
+
state.prefill = null;
|
|
314
|
+
}
|
|
315
|
+
}, [send, syncCloseButton]);
|
|
316
|
+
const closeOverlay = useCallback2(() => setIsOpen(false), []);
|
|
317
|
+
const inlineRef = useRef2(inline);
|
|
318
|
+
inlineRef.current = inline;
|
|
319
|
+
const inlineOwnsRef = useRef2(inlineOwns);
|
|
320
|
+
inlineOwnsRef.current = inlineOwns;
|
|
321
|
+
const handleMessage = useCallback2(
|
|
322
|
+
(raw) => {
|
|
323
|
+
const event = parseEvent(raw);
|
|
324
|
+
if (!event) return;
|
|
325
|
+
log("\u2190", event.name, event.payload);
|
|
326
|
+
switch (event.name) {
|
|
327
|
+
case "ready": {
|
|
328
|
+
readyRef.current = true;
|
|
329
|
+
setIsReady(true);
|
|
330
|
+
const minted = event.payload.identity?.anonymousId;
|
|
331
|
+
if (minted && !identity.current) {
|
|
332
|
+
identity.current = { kind: "anonymous", id: minted };
|
|
333
|
+
void writeIdentity(tenantId, identity.current);
|
|
334
|
+
}
|
|
335
|
+
replayAll();
|
|
336
|
+
break;
|
|
337
|
+
}
|
|
338
|
+
case "unreadChanged":
|
|
339
|
+
setUnreadCount(event.payload.count);
|
|
340
|
+
break;
|
|
341
|
+
case "openUrl":
|
|
342
|
+
if (onOpenUrl) onOpenUrl(event.payload.url);
|
|
343
|
+
else void Linking2.openURL(event.payload.url).catch(() => void 0);
|
|
344
|
+
break;
|
|
345
|
+
case "closeRequested":
|
|
346
|
+
if (inlineOwnsRef.current) inlineRef.current?.onCloseRequested?.();
|
|
347
|
+
else closeOverlay();
|
|
348
|
+
break;
|
|
349
|
+
case "error":
|
|
350
|
+
warn(`${event.payload.code}: ${event.payload.message}`);
|
|
351
|
+
break;
|
|
352
|
+
default:
|
|
353
|
+
break;
|
|
354
|
+
}
|
|
355
|
+
emit(event.name, event.payload);
|
|
356
|
+
},
|
|
357
|
+
[log, tenantId, replayAll, onOpenUrl, closeOverlay, warn, emit]
|
|
358
|
+
);
|
|
359
|
+
const handleLoadStart = useCallback2(() => {
|
|
360
|
+
readyRef.current = false;
|
|
361
|
+
setIsReady(false);
|
|
362
|
+
}, []);
|
|
363
|
+
const remount = useCallback2((next) => {
|
|
364
|
+
readyRef.current = false;
|
|
365
|
+
setIsReady(false);
|
|
366
|
+
setUnreadCount(0);
|
|
367
|
+
setBootIdentity(next);
|
|
368
|
+
setPageKey((key2) => key2 + 1);
|
|
369
|
+
}, []);
|
|
370
|
+
useEffect2(() => {
|
|
371
|
+
if (!isOpen) return void 0;
|
|
372
|
+
const subscription = BackHandler.addEventListener("hardwareBackPress", () => {
|
|
373
|
+
closeOverlay();
|
|
374
|
+
return true;
|
|
375
|
+
});
|
|
376
|
+
return () => subscription.remove();
|
|
377
|
+
}, [isOpen, closeOverlay]);
|
|
378
|
+
const setContact = useCallback2(
|
|
379
|
+
(contact) => {
|
|
380
|
+
const next = { ...replay.current.contact, ...contact };
|
|
381
|
+
replay.current.contact = next;
|
|
382
|
+
send("setContact", next);
|
|
383
|
+
},
|
|
384
|
+
[send]
|
|
385
|
+
);
|
|
386
|
+
const setMeta = useCallback2(
|
|
387
|
+
(target, meta) => {
|
|
388
|
+
const normalized = normalizeMeta(meta, warn);
|
|
389
|
+
if (!Object.keys(normalized).length) return;
|
|
390
|
+
replay.current[target] = { ...replay.current[target], ...normalized };
|
|
391
|
+
send(target === "contactMeta" ? "setContactMeta" : "setSessionMeta", normalized);
|
|
392
|
+
},
|
|
393
|
+
[send, warn]
|
|
394
|
+
);
|
|
395
|
+
const logout = useCallback2(async () => {
|
|
396
|
+
if (readyRef.current && webview.current) {
|
|
397
|
+
await new Promise((resolve) => {
|
|
398
|
+
const timer = setTimeout(done, RESET_TIMEOUT_MS);
|
|
399
|
+
const unsubscribe = subscribeRef.current("resetDone", done);
|
|
400
|
+
function done() {
|
|
401
|
+
clearTimeout(timer);
|
|
402
|
+
unsubscribe();
|
|
403
|
+
resolve();
|
|
404
|
+
}
|
|
405
|
+
send("reset", {});
|
|
406
|
+
});
|
|
407
|
+
}
|
|
408
|
+
await clearIdentity(tenantId);
|
|
409
|
+
identity.current = null;
|
|
410
|
+
replay.current = emptyReplay();
|
|
411
|
+
remount(null);
|
|
412
|
+
}, [send, tenantId, remount]);
|
|
413
|
+
const identify = useCallback2(
|
|
414
|
+
async (user) => {
|
|
415
|
+
const { userHash, name, email, phone } = user;
|
|
416
|
+
if (userHash !== void 0) {
|
|
417
|
+
if (!USER_HASH_PATTERN.test(userHash)) {
|
|
418
|
+
warn("identify: userHash must be 32 to 128 chars of A-Z a-z 0-9 _ - (compute it on your backend). Ignored.");
|
|
419
|
+
} else if (identity.current?.kind !== "identified" || identity.current.id !== userHash) {
|
|
420
|
+
const next = { kind: "identified", id: userHash };
|
|
421
|
+
identity.current = next;
|
|
422
|
+
await writeIdentity(tenantId, next);
|
|
423
|
+
replay.current = emptyReplay();
|
|
424
|
+
remount(next);
|
|
425
|
+
}
|
|
426
|
+
}
|
|
427
|
+
const contact = {};
|
|
428
|
+
if (name) contact.name = name;
|
|
429
|
+
if (email) contact.email = email;
|
|
430
|
+
if (phone) contact.phone = phone;
|
|
431
|
+
if (Object.keys(contact).length) setContact(contact);
|
|
432
|
+
},
|
|
433
|
+
[tenantId, warn, remount, setContact]
|
|
434
|
+
);
|
|
435
|
+
const subscribe = useCallback2((name, listener) => {
|
|
436
|
+
const set = listeners.current.get(name) ?? /* @__PURE__ */ new Set();
|
|
437
|
+
set.add(listener);
|
|
438
|
+
listeners.current.set(name, set);
|
|
439
|
+
return () => {
|
|
440
|
+
set.delete(listener);
|
|
441
|
+
};
|
|
442
|
+
}, []);
|
|
443
|
+
const subscribeRef = useRef2(subscribe);
|
|
444
|
+
subscribeRef.current = subscribe;
|
|
445
|
+
const api = useMemo(() => {
|
|
446
|
+
if (!supported) {
|
|
447
|
+
const unsupported = () => warn("the chat SDK runs on iOS and Android only; on the web use the WebChat snippet.");
|
|
448
|
+
return {
|
|
449
|
+
open: unsupported,
|
|
450
|
+
close: unsupported,
|
|
451
|
+
preload: unsupported,
|
|
452
|
+
identify: async () => unsupported(),
|
|
453
|
+
setContact: unsupported,
|
|
454
|
+
setContactMeta: unsupported,
|
|
455
|
+
setSessionMeta: unsupported,
|
|
456
|
+
prefill: unsupported,
|
|
457
|
+
logout: async () => unsupported(),
|
|
458
|
+
unreadCount: 0,
|
|
459
|
+
isReady: false,
|
|
460
|
+
isOpen: false
|
|
461
|
+
};
|
|
462
|
+
}
|
|
463
|
+
return {
|
|
464
|
+
open: () => {
|
|
465
|
+
if (inlineRef.current?.visible) {
|
|
466
|
+
warn("open() ignored: <TalquiChat /> is on screen and already shows the chat.");
|
|
467
|
+
return;
|
|
468
|
+
}
|
|
469
|
+
setOwner("overlay");
|
|
470
|
+
setOverlayMounted(true);
|
|
471
|
+
setIsOpen(true);
|
|
472
|
+
},
|
|
473
|
+
close: closeOverlay,
|
|
474
|
+
preload: () => setOverlayMounted(true),
|
|
475
|
+
identify,
|
|
476
|
+
setContact,
|
|
477
|
+
setContactMeta: (meta) => setMeta("contactMeta", meta),
|
|
478
|
+
setSessionMeta: (meta) => setMeta("sessionMeta", meta),
|
|
479
|
+
prefill: (text) => {
|
|
480
|
+
const trimmed = typeof text === "string" ? text.trim().slice(0, 1e3) : "";
|
|
481
|
+
if (!trimmed) return;
|
|
482
|
+
if (readyRef.current) send("prefill", { text: trimmed });
|
|
483
|
+
else replay.current.prefill = trimmed;
|
|
484
|
+
},
|
|
485
|
+
logout,
|
|
486
|
+
unreadCount,
|
|
487
|
+
isReady,
|
|
488
|
+
isOpen
|
|
489
|
+
};
|
|
490
|
+
}, [supported, warn, closeOverlay, identify, setContact, setMeta, send, logout, unreadCount, isReady, isOpen]);
|
|
491
|
+
const renderWebView = useCallback2(
|
|
492
|
+
(style) => identityLoaded ? /* @__PURE__ */ jsx2(
|
|
493
|
+
TalquiWebView,
|
|
494
|
+
{
|
|
495
|
+
ref: webview,
|
|
496
|
+
url,
|
|
497
|
+
allowedOrigin,
|
|
498
|
+
isReady,
|
|
499
|
+
onMessage: handleMessage,
|
|
500
|
+
onLoadStart: handleLoadStart,
|
|
501
|
+
onOpenUrl,
|
|
502
|
+
renderLoading,
|
|
503
|
+
renderError,
|
|
504
|
+
style,
|
|
505
|
+
debug
|
|
506
|
+
},
|
|
507
|
+
pageKey
|
|
508
|
+
) : null,
|
|
509
|
+
[identityLoaded, pageKey, url, allowedOrigin, isReady, handleMessage, handleLoadStart, onOpenUrl, renderLoading, renderError, debug]
|
|
510
|
+
);
|
|
511
|
+
const internals = useMemo(
|
|
512
|
+
() => ({
|
|
513
|
+
renderInline: (style) => inlineOwns ? renderWebView(style) : null,
|
|
514
|
+
registerInline: (host) => {
|
|
515
|
+
setInline(host);
|
|
516
|
+
if (host.visible) setIsOpen(false);
|
|
517
|
+
return () => setInline(null);
|
|
518
|
+
},
|
|
519
|
+
updateInline: (host) => setInline(host)
|
|
520
|
+
}),
|
|
521
|
+
[renderWebView, inlineOwns]
|
|
522
|
+
);
|
|
523
|
+
const value = useMemo(() => ({ api, internals, subscribe }), [api, internals, subscribe]);
|
|
524
|
+
return /* @__PURE__ */ jsxs2(TalquiContext.Provider, { value, children: [
|
|
525
|
+
children,
|
|
526
|
+
supported && overlayMounted && !inlineOwns && /* @__PURE__ */ jsx2(View2, { style: [styles2.overlay, !isOpen && styles2.hidden], pointerEvents: isOpen ? "auto" : "none", children: renderWebView(void 0) })
|
|
527
|
+
] });
|
|
528
|
+
}
|
|
529
|
+
function useTalqui() {
|
|
530
|
+
return useTalquiContext().api;
|
|
531
|
+
}
|
|
532
|
+
function useTalquiEvent(name, listener) {
|
|
533
|
+
const { subscribe } = useTalquiContext();
|
|
534
|
+
const latest = useRef2(listener);
|
|
535
|
+
latest.current = listener;
|
|
536
|
+
useEffect2(() => subscribe(name, (payload) => latest.current(payload)), [subscribe, name]);
|
|
537
|
+
}
|
|
538
|
+
function useTalquiContext() {
|
|
539
|
+
const context = useContext(TalquiContext);
|
|
540
|
+
if (!context) {
|
|
541
|
+
throw new Error("[talqui] useTalqui must be used inside <TalquiProvider>.");
|
|
542
|
+
}
|
|
543
|
+
return context;
|
|
544
|
+
}
|
|
545
|
+
var styles2 = StyleSheet2.create({
|
|
546
|
+
overlay: {
|
|
547
|
+
position: "absolute",
|
|
548
|
+
top: 0,
|
|
549
|
+
right: 0,
|
|
550
|
+
bottom: 0,
|
|
551
|
+
left: 0,
|
|
552
|
+
zIndex: 1e3,
|
|
553
|
+
elevation: 1e3,
|
|
554
|
+
backgroundColor: "#FFFFFF",
|
|
555
|
+
// Android draws the app under the status bar; the page only knows about the iOS safe areas.
|
|
556
|
+
paddingTop: Platform2.OS === "android" ? StatusBar.currentHeight ?? 0 : 0
|
|
557
|
+
},
|
|
558
|
+
// Hidden, not unmounted: the conversation keeps running so unread messages are counted.
|
|
559
|
+
hidden: { opacity: 0, transform: [{ translateY: 1e5 }] }
|
|
560
|
+
});
|
|
561
|
+
|
|
562
|
+
// src/TalquiChat.tsx
|
|
563
|
+
import { useEffect as useEffect3, useRef as useRef3 } from "react";
|
|
564
|
+
import { Fragment, jsx as jsx3 } from "react/jsx-runtime";
|
|
565
|
+
function TalquiChat({ style, visible = true, onCloseRequested, hideCloseButton = false }) {
|
|
566
|
+
const { internals } = useTalquiContext();
|
|
567
|
+
const host = useRef3({ visible, onCloseRequested, hideCloseButton });
|
|
568
|
+
host.current = { visible, onCloseRequested, hideCloseButton };
|
|
569
|
+
useEffect3(() => internals.registerInline(host.current), [internals]);
|
|
570
|
+
useEffect3(
|
|
571
|
+
() => internals.updateInline({ visible, onCloseRequested, hideCloseButton }),
|
|
572
|
+
[internals, visible, onCloseRequested, hideCloseButton]
|
|
573
|
+
);
|
|
574
|
+
return /* @__PURE__ */ jsx3(Fragment, { children: internals.renderInline(style) });
|
|
575
|
+
}
|
|
576
|
+
export {
|
|
577
|
+
TalquiChat,
|
|
578
|
+
TalquiProvider,
|
|
579
|
+
useTalqui,
|
|
580
|
+
useTalquiEvent
|
|
581
|
+
};
|
package/package.json
CHANGED
|
@@ -1,6 +1,84 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@talqui-oss/talqui-sdk-reactnative",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "Live chat SDK for React Native and Expo: in-app customer support chat with your team, bots and AI agents.",
|
|
5
|
+
"license": "MIT",
|
|
6
|
+
"author": "Talqui",
|
|
7
|
+
"homepage": "https://docs.talqui.chat/guides/chat-sdks/react-native",
|
|
8
|
+
"repository": {
|
|
9
|
+
"type": "git",
|
|
10
|
+
"url": "git+https://github.com/talqui-oss/talqui-sdk-reactnative.git"
|
|
11
|
+
},
|
|
12
|
+
"bugs": {
|
|
13
|
+
"url": "https://github.com/talqui-oss/talqui-sdk-reactnative/issues"
|
|
14
|
+
},
|
|
15
|
+
"keywords": [
|
|
16
|
+
"react-native",
|
|
17
|
+
"expo",
|
|
18
|
+
"live-chat",
|
|
19
|
+
"chat",
|
|
20
|
+
"chat-sdk",
|
|
21
|
+
"in-app-chat",
|
|
22
|
+
"in-app-messaging",
|
|
23
|
+
"messaging",
|
|
24
|
+
"customer-support",
|
|
25
|
+
"customer-service",
|
|
26
|
+
"support-chat",
|
|
27
|
+
"helpdesk",
|
|
28
|
+
"chat-widget",
|
|
29
|
+
"chatbot",
|
|
30
|
+
"ai-agent",
|
|
31
|
+
"omnichannel",
|
|
32
|
+
"whatsapp",
|
|
33
|
+
"ios",
|
|
34
|
+
"android",
|
|
35
|
+
"talqui"
|
|
36
|
+
],
|
|
37
|
+
"main": "./dist/index.js",
|
|
38
|
+
"module": "./dist/index.mjs",
|
|
39
|
+
"types": "./dist/index.d.ts",
|
|
40
|
+
"react-native": "./src/index.ts",
|
|
41
|
+
"exports": {
|
|
42
|
+
".": {
|
|
43
|
+
"types": "./dist/index.d.ts",
|
|
44
|
+
"react-native": "./src/index.ts",
|
|
45
|
+
"import": "./dist/index.mjs",
|
|
46
|
+
"require": "./dist/index.js"
|
|
47
|
+
},
|
|
48
|
+
"./package.json": "./package.json"
|
|
49
|
+
},
|
|
50
|
+
"files": [
|
|
51
|
+
"dist",
|
|
52
|
+
"src",
|
|
53
|
+
"README.md",
|
|
54
|
+
"LICENSE.md"
|
|
55
|
+
],
|
|
56
|
+
"sideEffects": false,
|
|
57
|
+
"scripts": {
|
|
58
|
+
"build": "tsup src/index.ts --format esm,cjs --dts --clean --external react --external react-native --external react-native-webview --external @react-native-async-storage/async-storage",
|
|
59
|
+
"typecheck": "tsc --noEmit",
|
|
60
|
+
"test": "node --test test/*.test.ts"
|
|
61
|
+
},
|
|
62
|
+
"peerDependencies": {
|
|
63
|
+
"@react-native-async-storage/async-storage": ">=1.21",
|
|
64
|
+
"react": ">=18",
|
|
65
|
+
"react-native": ">=0.73",
|
|
66
|
+
"react-native-webview": ">=13"
|
|
67
|
+
},
|
|
68
|
+
"devDependencies": {
|
|
69
|
+
"@react-native-async-storage/async-storage": "2.2.0",
|
|
70
|
+
"@types/react": "19.2.14",
|
|
71
|
+
"react": "19.2.3",
|
|
72
|
+
"react-native": "0.86.3",
|
|
73
|
+
"react-native-webview": "13.16.1",
|
|
74
|
+
"tsup": "8.5.1",
|
|
75
|
+
"typescript": "5.9.3"
|
|
76
|
+
},
|
|
77
|
+
"packageManager": "pnpm@10.14.0",
|
|
78
|
+
"engines": {
|
|
79
|
+
"node": ">=20"
|
|
80
|
+
},
|
|
81
|
+
"publishConfig": {
|
|
82
|
+
"access": "public"
|
|
83
|
+
}
|
|
84
|
+
}
|