@flexsmb54/react-native-widget 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/LICENSE +21 -0
- package/README.md +159 -2
- package/assets/chat.png +0 -0
- package/assets/chat.svg +5 -0
- package/assets/chat@2x.png +0 -0
- package/assets/chat@3x.png +0 -0
- package/lib/ErrorView.d.ts +7 -0
- package/lib/ErrorView.js +27 -0
- package/lib/Flex54.d.ts +13 -0
- package/lib/Flex54.js +39 -0
- package/lib/Flex54Widget.d.ts +24 -0
- package/lib/Flex54Widget.js +175 -0
- package/lib/Launcher.d.ts +10 -0
- package/lib/Launcher.js +28 -0
- package/lib/controller.d.ts +51 -0
- package/lib/controller.js +147 -0
- package/lib/index.d.ts +4 -0
- package/lib/index.js +7 -0
- package/lib/protocol.d.ts +5 -0
- package/lib/protocol.js +28 -0
- package/lib/types.d.ts +4 -0
- package/lib/types.js +2 -0
- package/lib/url.d.ts +8 -0
- package/lib/url.js +40 -0
- package/lib/version.d.ts +1 -0
- package/lib/version.js +4 -0
- package/package.json +42 -4
- package/src/ErrorView.tsx +54 -0
- package/src/Flex54.ts +39 -0
- package/src/Flex54Widget.tsx +234 -0
- package/src/Launcher.tsx +49 -0
- package/src/controller.ts +166 -0
- package/src/index.ts +4 -0
- package/src/protocol.ts +25 -0
- package/src/types.ts +4 -0
- package/src/url.ts +37 -0
- package/src/version.ts +1 -0
|
@@ -0,0 +1,147 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.Flex54Controller = exports.MAX_PAGE_AGE_MS = void 0;
|
|
4
|
+
exports.clearPendingResetForTesting = clearPendingResetForTesting;
|
|
5
|
+
/**
|
|
6
|
+
* The widget fetches its config and token once per page load, and the token expires, so a
|
|
7
|
+
* page older than this is reloaded on open instead of being reused.
|
|
8
|
+
*/
|
|
9
|
+
exports.MAX_PAGE_AGE_MS = 12 * 60 * 60 * 1000;
|
|
10
|
+
// Shared by every controller (only one widget is supported at a time), so a reset requested
|
|
11
|
+
// before `ready` still reaches the page when the widget unmounts and a new one mounts.
|
|
12
|
+
let pendingReset = false;
|
|
13
|
+
/** Internal: clears the shared pending reset. Used by `resetFlex54ForTesting`; not exported from the package. */
|
|
14
|
+
function clearPendingResetForTesting() {
|
|
15
|
+
pendingReset = false;
|
|
16
|
+
}
|
|
17
|
+
/**
|
|
18
|
+
* Pure state machine behind the widget surface. Implements the "Host responsibilities"
|
|
19
|
+
* of PROTOCOL.md: sync state on every `ready` instead of replaying a command queue.
|
|
20
|
+
* `subscribe` and `getState` are arrow properties, so they can be passed around unbound
|
|
21
|
+
* (e.g. straight into `useSyncExternalStore`).
|
|
22
|
+
*/
|
|
23
|
+
class Flex54Controller {
|
|
24
|
+
constructor(callbacks = {}, now = Date.now) {
|
|
25
|
+
this.state = {
|
|
26
|
+
// Mount hidden when a reset is pending, so it is delivered without the user opening the chat.
|
|
27
|
+
mounted: pendingReset,
|
|
28
|
+
visible: false,
|
|
29
|
+
ready: false,
|
|
30
|
+
loadError: false,
|
|
31
|
+
webViewKey: 0,
|
|
32
|
+
};
|
|
33
|
+
this.listeners = new Set();
|
|
34
|
+
this.sender = null;
|
|
35
|
+
this.readyAt = 0;
|
|
36
|
+
this.widgetOpen = false;
|
|
37
|
+
this.subscribe = (listener) => {
|
|
38
|
+
this.listeners.add(listener);
|
|
39
|
+
return () => {
|
|
40
|
+
this.listeners.delete(listener);
|
|
41
|
+
};
|
|
42
|
+
};
|
|
43
|
+
this.getState = () => this.state;
|
|
44
|
+
this.callbacks = callbacks;
|
|
45
|
+
this.now = now;
|
|
46
|
+
}
|
|
47
|
+
setCallbacks(cb) {
|
|
48
|
+
this.callbacks = cb;
|
|
49
|
+
}
|
|
50
|
+
attachSender(send) {
|
|
51
|
+
this.sender = send;
|
|
52
|
+
}
|
|
53
|
+
update(patch) {
|
|
54
|
+
const next = { ...this.state, ...patch };
|
|
55
|
+
const changed = Object.keys(next).some((k) => next[k] !== this.state[k]);
|
|
56
|
+
if (!changed)
|
|
57
|
+
return;
|
|
58
|
+
this.state = next;
|
|
59
|
+
[...this.listeners].forEach((l) => l());
|
|
60
|
+
}
|
|
61
|
+
send(command) {
|
|
62
|
+
this.sender?.(command);
|
|
63
|
+
}
|
|
64
|
+
open() {
|
|
65
|
+
// A load error is sticky until retried, so reopening retries.
|
|
66
|
+
if (this.state.loadError)
|
|
67
|
+
this.retry();
|
|
68
|
+
this.update({ mounted: true, visible: true });
|
|
69
|
+
if (!this.state.ready)
|
|
70
|
+
return;
|
|
71
|
+
// The next `ready` opens the reloaded page.
|
|
72
|
+
if (this.now() - this.readyAt > exports.MAX_PAGE_AGE_MS)
|
|
73
|
+
this.remount();
|
|
74
|
+
else
|
|
75
|
+
this.send('open');
|
|
76
|
+
}
|
|
77
|
+
close() {
|
|
78
|
+
if (!this.state.visible)
|
|
79
|
+
return;
|
|
80
|
+
this.update({ visible: false });
|
|
81
|
+
// Sent even before ready: the injected script is guarded by `window.Flex54Bridge&&`,
|
|
82
|
+
// so it is a no-op on a page without the bridge.
|
|
83
|
+
this.send('close');
|
|
84
|
+
}
|
|
85
|
+
toggle() {
|
|
86
|
+
if (this.state.visible)
|
|
87
|
+
this.close();
|
|
88
|
+
else
|
|
89
|
+
this.open();
|
|
90
|
+
}
|
|
91
|
+
reset() {
|
|
92
|
+
pendingReset = true;
|
|
93
|
+
this.update({ mounted: true });
|
|
94
|
+
if (this.state.ready) {
|
|
95
|
+
pendingReset = false;
|
|
96
|
+
this.send('reset');
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
isOpen() {
|
|
100
|
+
return this.state.visible;
|
|
101
|
+
}
|
|
102
|
+
handleWidgetEvent(e) {
|
|
103
|
+
switch (e) {
|
|
104
|
+
case 'ready':
|
|
105
|
+
this.readyAt = this.now();
|
|
106
|
+
this.update({ ready: true, loadError: false });
|
|
107
|
+
if (pendingReset) {
|
|
108
|
+
pendingReset = false;
|
|
109
|
+
this.send('reset');
|
|
110
|
+
}
|
|
111
|
+
if (this.state.visible)
|
|
112
|
+
this.send('open');
|
|
113
|
+
break;
|
|
114
|
+
case 'opened':
|
|
115
|
+
this.widgetOpen = true;
|
|
116
|
+
// Never leave the chat open behind a hidden surface (billing invariant).
|
|
117
|
+
if (!this.state.visible)
|
|
118
|
+
this.send('close');
|
|
119
|
+
this.callbacks.onOpen?.();
|
|
120
|
+
break;
|
|
121
|
+
case 'closed':
|
|
122
|
+
if (!this.widgetOpen)
|
|
123
|
+
return;
|
|
124
|
+
this.widgetOpen = false;
|
|
125
|
+
// Hide first so onClose sees consistent state and may safely call open().
|
|
126
|
+
if (this.state.visible)
|
|
127
|
+
this.update({ visible: false });
|
|
128
|
+
this.callbacks.onClose?.();
|
|
129
|
+
break;
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
handleLoadError() {
|
|
133
|
+
this.update({ loadError: true, ready: false });
|
|
134
|
+
}
|
|
135
|
+
retry() {
|
|
136
|
+
this.update({ loadError: false });
|
|
137
|
+
this.remount();
|
|
138
|
+
}
|
|
139
|
+
handleProcessTerminated() {
|
|
140
|
+
this.remount();
|
|
141
|
+
}
|
|
142
|
+
remount() {
|
|
143
|
+
this.widgetOpen = false;
|
|
144
|
+
this.update({ ready: false, webViewKey: this.state.webViewKey + 1 });
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
exports.Flex54Controller = Flex54Controller;
|
package/lib/index.d.ts
ADDED
package/lib/index.js
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.Flex54Widget = exports.Flex54 = void 0;
|
|
4
|
+
var Flex54_1 = require("./Flex54");
|
|
5
|
+
Object.defineProperty(exports, "Flex54", { enumerable: true, get: function () { return Flex54_1.Flex54; } });
|
|
6
|
+
var Flex54Widget_1 = require("./Flex54Widget");
|
|
7
|
+
Object.defineProperty(exports, "Flex54Widget", { enumerable: true, get: function () { return Flex54Widget_1.Flex54Widget; } });
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
import type { HostCommand, WidgetEvent } from './types';
|
|
2
|
+
/** Parses a WebView message from the widget. Returns null for foreign or malformed data. */
|
|
3
|
+
export declare function parseWidgetMessage(data: string): WidgetEvent | null;
|
|
4
|
+
/** JavaScript to inject into the WebView to deliver a command to the widget. */
|
|
5
|
+
export declare function buildCommandScript(command: HostCommand): string;
|
package/lib/protocol.js
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.parseWidgetMessage = parseWidgetMessage;
|
|
4
|
+
exports.buildCommandScript = buildCommandScript;
|
|
5
|
+
const WIDGET_SOURCE = 'kaabo-ai-widget';
|
|
6
|
+
const HOST_SOURCE = 'flex54-host';
|
|
7
|
+
const EVENTS = ['ready', 'opened', 'closed'];
|
|
8
|
+
/** Parses a WebView message from the widget. Returns null for foreign or malformed data. */
|
|
9
|
+
function parseWidgetMessage(data) {
|
|
10
|
+
let parsed;
|
|
11
|
+
try {
|
|
12
|
+
parsed = JSON.parse(data);
|
|
13
|
+
}
|
|
14
|
+
catch {
|
|
15
|
+
return null;
|
|
16
|
+
}
|
|
17
|
+
if (!parsed || typeof parsed !== 'object')
|
|
18
|
+
return null;
|
|
19
|
+
const { source, v, event } = parsed;
|
|
20
|
+
if (source !== WIDGET_SOURCE || v !== 1)
|
|
21
|
+
return null;
|
|
22
|
+
return EVENTS.find((e) => e === event) ?? null;
|
|
23
|
+
}
|
|
24
|
+
/** JavaScript to inject into the WebView to deliver a command to the widget. */
|
|
25
|
+
function buildCommandScript(command) {
|
|
26
|
+
const message = JSON.stringify({ source: HOST_SOURCE, v: 1, command });
|
|
27
|
+
return `window.Flex54Bridge&&window.Flex54Bridge.receive(${message});true;`;
|
|
28
|
+
}
|
package/lib/types.d.ts
ADDED
package/lib/types.js
ADDED
package/lib/url.d.ts
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import type { Flex54Environment } from './types';
|
|
2
|
+
export declare function widgetOrigin(env: Flex54Environment): string;
|
|
3
|
+
export declare function buildWidgetUrl(opts: {
|
|
4
|
+
widgetId: string;
|
|
5
|
+
environment: Flex54Environment;
|
|
6
|
+
}): string;
|
|
7
|
+
/** True for URLs the WebView should load itself; everything else goes to the system browser. */
|
|
8
|
+
export declare function shouldLoadInWebView(url: string, origin: string): boolean;
|
package/lib/url.js
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.widgetOrigin = widgetOrigin;
|
|
4
|
+
exports.buildWidgetUrl = buildWidgetUrl;
|
|
5
|
+
exports.shouldLoadInWebView = shouldLoadInWebView;
|
|
6
|
+
const version_1 = require("./version");
|
|
7
|
+
const ORIGINS = {
|
|
8
|
+
production: 'https://agent.flex54.com',
|
|
9
|
+
development: 'https://agent-dev.flex54.com',
|
|
10
|
+
};
|
|
11
|
+
function widgetOrigin(env) {
|
|
12
|
+
return ORIGINS[env];
|
|
13
|
+
}
|
|
14
|
+
// URLSearchParams is only partially implemented in React Native, so encode by hand
|
|
15
|
+
// (form-encoding: space becomes '+').
|
|
16
|
+
const enc = (value) => encodeURIComponent(value).replace(/%20/g, '+');
|
|
17
|
+
function buildWidgetUrl(opts) {
|
|
18
|
+
const params = [
|
|
19
|
+
['widgetId', opts.widgetId],
|
|
20
|
+
['device', 'mobile'],
|
|
21
|
+
['host', 'native'],
|
|
22
|
+
['platform', 'react-native'],
|
|
23
|
+
['sdkVersion', version_1.SDK_VERSION],
|
|
24
|
+
];
|
|
25
|
+
const query = params.map(([k, v]) => `${enc(k)}=${enc(v)}`).join('&');
|
|
26
|
+
return `${widgetOrigin(opts.environment)}/?${query}`;
|
|
27
|
+
}
|
|
28
|
+
/** True for URLs the WebView should load itself; everything else goes to the system browser. */
|
|
29
|
+
function shouldLoadInWebView(url, origin) {
|
|
30
|
+
if (typeof url !== 'string')
|
|
31
|
+
return false;
|
|
32
|
+
if (url === 'about:blank' || url === 'about:srcdoc')
|
|
33
|
+
return true;
|
|
34
|
+
if (/^(blob|data):/i.test(url))
|
|
35
|
+
return true;
|
|
36
|
+
if (!url.startsWith(origin))
|
|
37
|
+
return false;
|
|
38
|
+
const next = url.charAt(origin.length);
|
|
39
|
+
return next === '' || next === '/' || next === '?' || next === '#';
|
|
40
|
+
}
|
package/lib/version.d.ts
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export declare const SDK_VERSION = "0.1.1";
|
package/lib/version.js
ADDED
package/package.json
CHANGED
|
@@ -1,6 +1,44 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@flexsmb54/react-native-widget",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.1.1",
|
|
4
|
+
"description": "Flex54 chat widget for React Native (WebView based, no native code)",
|
|
5
|
+
"license": "MIT",
|
|
6
|
+
"main": "lib/index.js",
|
|
7
|
+
"types": "lib/index.d.ts",
|
|
8
|
+
"react-native": "src/index.ts",
|
|
9
|
+
"files": [
|
|
10
|
+
"lib",
|
|
11
|
+
"src",
|
|
12
|
+
"assets",
|
|
13
|
+
"README.md",
|
|
14
|
+
"!src/__tests__"
|
|
15
|
+
],
|
|
16
|
+
"scripts": {
|
|
17
|
+
"build": "tsc -p tsconfig.build.json",
|
|
18
|
+
"prepack": "npm run build",
|
|
19
|
+
"typecheck": "tsc --noEmit",
|
|
20
|
+
"test": "jest",
|
|
21
|
+
"render-icon": "node scripts/render-icon.mjs"
|
|
22
|
+
},
|
|
23
|
+
"peerDependencies": {
|
|
24
|
+
"react": ">=18",
|
|
25
|
+
"react-native": ">=0.72",
|
|
26
|
+
"react-native-safe-area-context": ">=4",
|
|
27
|
+
"react-native-webview": ">=13"
|
|
28
|
+
},
|
|
29
|
+
"devDependencies": {
|
|
30
|
+
"@react-native/babel-preset": "0.88.1",
|
|
31
|
+
"@react-native/jest-preset": "^0.88.1",
|
|
32
|
+
"@resvg/resvg-js": "^2.6.2",
|
|
33
|
+
"@testing-library/react-native": "^14.1.0",
|
|
34
|
+
"@types/jest": "^30.0.0",
|
|
35
|
+
"@types/react": "~19.3.0",
|
|
36
|
+
"jest": "^30.5.2",
|
|
37
|
+
"react": "19.3.0",
|
|
38
|
+
"react-native": "0.88.1",
|
|
39
|
+
"react-native-safe-area-context": "~5.11.1",
|
|
40
|
+
"react-native-webview": "14.0.1",
|
|
41
|
+
"test-renderer": "^1.3.1",
|
|
42
|
+
"typescript": "~6.0.3"
|
|
43
|
+
}
|
|
44
|
+
}
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
import * as React from 'react';
|
|
2
|
+
import { Pressable, StyleSheet, Text, View } from 'react-native';
|
|
3
|
+
|
|
4
|
+
export type ErrorViewProps = {
|
|
5
|
+
onRetry: () => void;
|
|
6
|
+
onClose: () => void;
|
|
7
|
+
};
|
|
8
|
+
|
|
9
|
+
/** Shown over the WebView when the widget page fails to load. */
|
|
10
|
+
export function ErrorView({ onRetry, onClose }: ErrorViewProps): React.ReactElement {
|
|
11
|
+
return (
|
|
12
|
+
<View style={[StyleSheet.absoluteFill, styles.container]}>
|
|
13
|
+
<Text accessibilityRole="header" style={styles.title}>
|
|
14
|
+
Couldn't load the chat
|
|
15
|
+
</Text>
|
|
16
|
+
<Text style={styles.body}>Check your connection and try again.</Text>
|
|
17
|
+
<View style={styles.actions}>
|
|
18
|
+
<Pressable
|
|
19
|
+
accessibilityRole="button"
|
|
20
|
+
onPress={onRetry}
|
|
21
|
+
style={({ pressed }) => [styles.button, styles.primary, pressed && styles.pressed]}
|
|
22
|
+
>
|
|
23
|
+
<Text style={[styles.label, styles.primaryLabel]}>Try again</Text>
|
|
24
|
+
</Pressable>
|
|
25
|
+
<Pressable
|
|
26
|
+
accessibilityRole="button"
|
|
27
|
+
onPress={onClose}
|
|
28
|
+
style={({ pressed }) => [styles.button, styles.secondary, pressed && styles.pressed]}
|
|
29
|
+
>
|
|
30
|
+
<Text style={[styles.label, styles.secondaryLabel]}>Close</Text>
|
|
31
|
+
</Pressable>
|
|
32
|
+
</View>
|
|
33
|
+
</View>
|
|
34
|
+
);
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
const styles = StyleSheet.create({
|
|
38
|
+
container: {
|
|
39
|
+
alignItems: 'center',
|
|
40
|
+
justifyContent: 'center',
|
|
41
|
+
padding: 24,
|
|
42
|
+
backgroundColor: '#ffffff',
|
|
43
|
+
},
|
|
44
|
+
title: { fontSize: 18, fontWeight: '600', color: '#000000', textAlign: 'center' },
|
|
45
|
+
body: { marginTop: 8, fontSize: 15, color: '#555555', textAlign: 'center' },
|
|
46
|
+
actions: { flexDirection: 'row', marginTop: 24, gap: 12 },
|
|
47
|
+
button: { minWidth: 112, paddingVertical: 12, paddingHorizontal: 20, borderRadius: 24, alignItems: 'center' },
|
|
48
|
+
primary: { backgroundColor: '#000000' },
|
|
49
|
+
secondary: { borderWidth: 1, borderColor: '#000000' },
|
|
50
|
+
pressed: { opacity: 0.8 },
|
|
51
|
+
label: { fontSize: 15, fontWeight: '600' },
|
|
52
|
+
primaryLabel: { color: '#ffffff' },
|
|
53
|
+
secondaryLabel: { color: '#000000' },
|
|
54
|
+
});
|
package/src/Flex54.ts
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import { clearPendingResetForTesting } from './controller';
|
|
2
|
+
import type { Flex54Controller } from './controller';
|
|
3
|
+
|
|
4
|
+
type Call = (c: Flex54Controller) => void;
|
|
5
|
+
|
|
6
|
+
let active: Flex54Controller | null = null;
|
|
7
|
+
let buffered: Call[] = [];
|
|
8
|
+
|
|
9
|
+
function dispatch(call: Call): void {
|
|
10
|
+
if (active) call(active);
|
|
11
|
+
else buffered.push(call);
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
/** Imperative API. Calls made before a widget mounts are buffered and replayed in order. */
|
|
15
|
+
export const Flex54 = {
|
|
16
|
+
open: (): void => dispatch((c) => c.open()),
|
|
17
|
+
close: (): void => dispatch((c) => c.close()),
|
|
18
|
+
toggle: (): void => dispatch((c) => c.toggle()),
|
|
19
|
+
reset: (): void => dispatch((c) => c.reset()),
|
|
20
|
+
isOpen: (): boolean => (active ? active.isOpen() : false),
|
|
21
|
+
};
|
|
22
|
+
|
|
23
|
+
/** Last registration wins. The returned function only unregisters if `c` is still active. */
|
|
24
|
+
export function registerController(c: Flex54Controller): () => void {
|
|
25
|
+
active = c;
|
|
26
|
+
const pending = buffered;
|
|
27
|
+
buffered = [];
|
|
28
|
+
pending.forEach((call) => call(c));
|
|
29
|
+
return () => {
|
|
30
|
+
if (active === c) active = null;
|
|
31
|
+
};
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/** Test helper: clears the active controller, the pending-call buffer and any pending reset. */
|
|
35
|
+
export function resetFlex54ForTesting(): void {
|
|
36
|
+
active = null;
|
|
37
|
+
buffered = [];
|
|
38
|
+
clearPendingResetForTesting();
|
|
39
|
+
}
|
|
@@ -0,0 +1,234 @@
|
|
|
1
|
+
import * as React from 'react';
|
|
2
|
+
import {
|
|
3
|
+
ActivityIndicator,
|
|
4
|
+
Animated,
|
|
5
|
+
BackHandler,
|
|
6
|
+
Linking,
|
|
7
|
+
Pressable,
|
|
8
|
+
StyleSheet,
|
|
9
|
+
View,
|
|
10
|
+
useWindowDimensions,
|
|
11
|
+
} from 'react-native';
|
|
12
|
+
import { SafeAreaProvider, SafeAreaView, useSafeAreaInsets } from 'react-native-safe-area-context';
|
|
13
|
+
import WebView from 'react-native-webview';
|
|
14
|
+
import type { WebViewMessageEvent, WebViewProps } from 'react-native-webview';
|
|
15
|
+
import { Flex54Controller } from './controller';
|
|
16
|
+
import { ErrorView } from './ErrorView';
|
|
17
|
+
import { registerController } from './Flex54';
|
|
18
|
+
import { Launcher } from './Launcher';
|
|
19
|
+
import { buildCommandScript, parseWidgetMessage } from './protocol';
|
|
20
|
+
import type { Flex54Environment, Flex54Position } from './types';
|
|
21
|
+
import { buildWidgetUrl, shouldLoadInWebView, widgetOrigin } from './url';
|
|
22
|
+
|
|
23
|
+
export type Flex54WidgetProps = {
|
|
24
|
+
widgetId: string;
|
|
25
|
+
/** Default `'production'`. */
|
|
26
|
+
environment?: Flex54Environment;
|
|
27
|
+
/** Show the floating chat button. Default `true`. */
|
|
28
|
+
launcher?: boolean;
|
|
29
|
+
/** Default `'bottom-right'`. */
|
|
30
|
+
position?: Flex54Position;
|
|
31
|
+
onOpen?: () => void;
|
|
32
|
+
onClose?: () => void;
|
|
33
|
+
};
|
|
34
|
+
|
|
35
|
+
type ShouldStartLoadRequest = Parameters<NonNullable<WebViewProps['onShouldStartLoadWithRequest']>>[0];
|
|
36
|
+
|
|
37
|
+
const SLIDE_MS = 250;
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* How long after the page finishes loading the widget has to send `ready`. A loaded page
|
|
41
|
+
* that stays silent is not a native-mode widget (e.g. a stale cached copy, or an older
|
|
42
|
+
* deploy), so show the error view instead of spinning forever.
|
|
43
|
+
*/
|
|
44
|
+
export const READY_TIMEOUT_MS = 10_000;
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* The Flex54 chat widget. Render it once, as the last child of your root component.
|
|
48
|
+
* It draws a launcher and a full-screen chat surface over the app; touches elsewhere pass through.
|
|
49
|
+
*/
|
|
50
|
+
export function Flex54Widget(props: Flex54WidgetProps): React.ReactElement {
|
|
51
|
+
return (
|
|
52
|
+
<SafeAreaProvider style={StyleSheet.absoluteFill} pointerEvents="box-none">
|
|
53
|
+
<WidgetHost {...props} />
|
|
54
|
+
</SafeAreaProvider>
|
|
55
|
+
);
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
function openExternal(url: string): void {
|
|
59
|
+
// Rejects when nothing can handle the URL; there is nothing useful to do about it here.
|
|
60
|
+
Linking.openURL(url).catch(() => {});
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
function WidgetHost({
|
|
64
|
+
widgetId,
|
|
65
|
+
environment = 'production',
|
|
66
|
+
launcher = true,
|
|
67
|
+
position = 'bottom-right',
|
|
68
|
+
onOpen,
|
|
69
|
+
onClose,
|
|
70
|
+
}: Flex54WidgetProps): React.ReactElement {
|
|
71
|
+
const controllerRef = React.useRef<Flex54Controller | null>(null);
|
|
72
|
+
if (controllerRef.current === null) controllerRef.current = new Flex54Controller();
|
|
73
|
+
const controller = controllerRef.current;
|
|
74
|
+
|
|
75
|
+
const { mounted, visible, ready, loadError, webViewKey } = React.useSyncExternalStore(
|
|
76
|
+
controller.subscribe,
|
|
77
|
+
controller.getState,
|
|
78
|
+
);
|
|
79
|
+
const insets = useSafeAreaInsets();
|
|
80
|
+
const { height } = useWindowDimensions();
|
|
81
|
+
// `object`, not the default `undefined`: react-native-webview types props as `WebViewProps & P`.
|
|
82
|
+
const webviewRef = React.useRef<WebView<object>>(null);
|
|
83
|
+
|
|
84
|
+
React.useLayoutEffect(() => {
|
|
85
|
+
controller.setCallbacks({ onOpen, onClose });
|
|
86
|
+
});
|
|
87
|
+
|
|
88
|
+
// One stable sender for the component's lifetime. It reads the ref at call time, so it
|
|
89
|
+
// follows WebView remounts (retry, process death) without being re-attached; detaching
|
|
90
|
+
// in between could drop a `close` and leave the chat open behind a hidden surface.
|
|
91
|
+
React.useEffect(() => {
|
|
92
|
+
controller.attachSender((command) => webviewRef.current?.injectJavaScript(buildCommandScript(command)));
|
|
93
|
+
return () => controller.attachSender(null);
|
|
94
|
+
}, [controller]);
|
|
95
|
+
|
|
96
|
+
React.useEffect(() => registerController(controller), [controller]);
|
|
97
|
+
|
|
98
|
+
// Registered only while the chat is visible, so it is the newest listener and runs
|
|
99
|
+
// before the app's own (e.g. navigation) back handlers.
|
|
100
|
+
React.useEffect(() => {
|
|
101
|
+
if (!visible) return;
|
|
102
|
+
const subscription = BackHandler.addEventListener('hardwareBackPress', () => {
|
|
103
|
+
if (!controller.isOpen()) return false;
|
|
104
|
+
controller.close();
|
|
105
|
+
return true;
|
|
106
|
+
});
|
|
107
|
+
return () => subscription.remove();
|
|
108
|
+
}, [controller, visible]);
|
|
109
|
+
|
|
110
|
+
const [translateY] = React.useState(() => new Animated.Value(height));
|
|
111
|
+
React.useEffect(() => {
|
|
112
|
+
if (!mounted) return;
|
|
113
|
+
Animated.timing(translateY, {
|
|
114
|
+
toValue: visible ? 0 : height,
|
|
115
|
+
duration: SLIDE_MS,
|
|
116
|
+
useNativeDriver: true,
|
|
117
|
+
}).start();
|
|
118
|
+
}, [translateY, mounted, visible, height]);
|
|
119
|
+
|
|
120
|
+
const origin = widgetOrigin(environment);
|
|
121
|
+
const uri = buildWidgetUrl({ widgetId, environment });
|
|
122
|
+
const source = React.useMemo(() => ({ uri }), [uri]);
|
|
123
|
+
|
|
124
|
+
// Armed when a page finishes loading; cancelled by `ready`, by a WebView remount (new key)
|
|
125
|
+
// and on unmount, so a replaced page's deadline never fails its successor.
|
|
126
|
+
const readyTimerRef = React.useRef<ReturnType<typeof setTimeout> | null>(null);
|
|
127
|
+
const clearReadyTimer = React.useCallback(() => {
|
|
128
|
+
if (readyTimerRef.current !== null) clearTimeout(readyTimerRef.current);
|
|
129
|
+
readyTimerRef.current = null;
|
|
130
|
+
}, []);
|
|
131
|
+
React.useEffect(() => {
|
|
132
|
+
if (ready) clearReadyTimer();
|
|
133
|
+
}, [ready, clearReadyTimer]);
|
|
134
|
+
React.useEffect(() => clearReadyTimer, [webViewKey, clearReadyTimer]);
|
|
135
|
+
|
|
136
|
+
const onLoadEnd = () => {
|
|
137
|
+
clearReadyTimer();
|
|
138
|
+
if (controller.getState().ready) return;
|
|
139
|
+
readyTimerRef.current = setTimeout(() => {
|
|
140
|
+
readyTimerRef.current = null;
|
|
141
|
+
if (!controller.getState().ready) controller.handleLoadError();
|
|
142
|
+
}, READY_TIMEOUT_MS);
|
|
143
|
+
};
|
|
144
|
+
|
|
145
|
+
const onMessage = (e: WebViewMessageEvent) => {
|
|
146
|
+
const event = parseWidgetMessage(e.nativeEvent.data);
|
|
147
|
+
if (event) controller.handleWidgetEvent(event);
|
|
148
|
+
};
|
|
149
|
+
|
|
150
|
+
const onShouldStartLoadWithRequest = (req: ShouldStartLoadRequest): boolean => {
|
|
151
|
+
if (req.isTopFrame === false || shouldLoadInWebView(req.url, origin)) return true;
|
|
152
|
+
openExternal(req.url);
|
|
153
|
+
// Before `ready`, a blocked top-frame request means the page itself never loads (e.g. an
|
|
154
|
+
// off-origin redirect). WKWebView reports the cancelled load as error 102, which
|
|
155
|
+
// react-native-webview drops, so show the error view instead of an endless spinner.
|
|
156
|
+
if (!controller.getState().ready) controller.handleLoadError();
|
|
157
|
+
return false;
|
|
158
|
+
};
|
|
159
|
+
|
|
160
|
+
return (
|
|
161
|
+
<View testID="flex54-root" style={StyleSheet.absoluteFill} pointerEvents="box-none">
|
|
162
|
+
{launcher && !visible ? (
|
|
163
|
+
<Launcher position={position} insets={insets} onPress={() => controller.open()} />
|
|
164
|
+
) : null}
|
|
165
|
+
{mounted ? (
|
|
166
|
+
<Animated.View
|
|
167
|
+
testID="flex54-surface"
|
|
168
|
+
pointerEvents={visible ? 'auto' : 'none'}
|
|
169
|
+
accessibilityElementsHidden={!visible}
|
|
170
|
+
importantForAccessibility={visible ? 'auto' : 'no-hide-descendants'}
|
|
171
|
+
style={[StyleSheet.absoluteFill, { transform: [{ translateY }] }]}
|
|
172
|
+
>
|
|
173
|
+
<SafeAreaView edges={['top', 'right', 'bottom', 'left']} style={styles.safeArea}>
|
|
174
|
+
<WebView
|
|
175
|
+
key={webViewKey}
|
|
176
|
+
ref={webviewRef}
|
|
177
|
+
source={source}
|
|
178
|
+
style={styles.webview}
|
|
179
|
+
onMessage={onMessage}
|
|
180
|
+
onLoadEnd={onLoadEnd}
|
|
181
|
+
onShouldStartLoadWithRequest={onShouldStartLoadWithRequest}
|
|
182
|
+
onOpenWindow={(e) => openExternal(e.nativeEvent.targetUrl)}
|
|
183
|
+
onError={() => controller.handleLoadError()}
|
|
184
|
+
onHttpError={(e) => {
|
|
185
|
+
if (e.nativeEvent.statusCode >= 400) controller.handleLoadError();
|
|
186
|
+
}}
|
|
187
|
+
onContentProcessDidTerminate={() => controller.handleProcessTerminated()}
|
|
188
|
+
onRenderProcessGone={() => controller.handleProcessTerminated()}
|
|
189
|
+
domStorageEnabled
|
|
190
|
+
javaScriptEnabled
|
|
191
|
+
allowsInlineMediaPlayback
|
|
192
|
+
mediaCapturePermissionGrantType="grantIfSameHostElsePrompt"
|
|
193
|
+
allowsBackForwardNavigationGestures={false}
|
|
194
|
+
webviewDebuggingEnabled={__DEV__}
|
|
195
|
+
/>
|
|
196
|
+
{loadError ? <ErrorView onRetry={() => controller.retry()} onClose={() => controller.close()} /> : null}
|
|
197
|
+
</SafeAreaView>
|
|
198
|
+
{visible && !ready && !loadError ? (
|
|
199
|
+
// Outside the SafeAreaView so the close button can be placed with the insets directly.
|
|
200
|
+
// It is the only way out on iOS (no hardware back) if the page never posts `ready`.
|
|
201
|
+
<View style={[StyleSheet.absoluteFill, styles.loading]}>
|
|
202
|
+
<ActivityIndicator testID="flex54-loading" accessibilityLabel="Loading chat" />
|
|
203
|
+
<Pressable
|
|
204
|
+
accessibilityRole="button"
|
|
205
|
+
accessibilityLabel="Close chat"
|
|
206
|
+
onPress={() => controller.close()}
|
|
207
|
+
style={({ pressed }) => [
|
|
208
|
+
styles.closeButton,
|
|
209
|
+
{ top: insets.top + 8, right: insets.right + 8 },
|
|
210
|
+
pressed && styles.pressed,
|
|
211
|
+
]}
|
|
212
|
+
>
|
|
213
|
+
<View style={[styles.closeBar, styles.closeBarA]} />
|
|
214
|
+
<View style={[styles.closeBar, styles.closeBarB]} />
|
|
215
|
+
</Pressable>
|
|
216
|
+
</View>
|
|
217
|
+
) : null}
|
|
218
|
+
</Animated.View>
|
|
219
|
+
) : null}
|
|
220
|
+
</View>
|
|
221
|
+
);
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
const styles = StyleSheet.create({
|
|
225
|
+
safeArea: { flex: 1, backgroundColor: '#ffffff' },
|
|
226
|
+
webview: { flex: 1, backgroundColor: '#ffffff' },
|
|
227
|
+
loading: { alignItems: 'center', justifyContent: 'center', backgroundColor: '#ffffff' },
|
|
228
|
+
// 44pt touch target with a quiet dark-grey X drawn from two rotated bars.
|
|
229
|
+
closeButton: { position: 'absolute', width: 44, height: 44, alignItems: 'center', justifyContent: 'center' },
|
|
230
|
+
closeBar: { position: 'absolute', width: 18, height: 2, borderRadius: 1, backgroundColor: '#444444' },
|
|
231
|
+
closeBarA: { transform: [{ rotate: '45deg' }] },
|
|
232
|
+
closeBarB: { transform: [{ rotate: '-45deg' }] },
|
|
233
|
+
pressed: { opacity: 0.5 },
|
|
234
|
+
});
|