@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 ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Flex54
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,160 @@
1
- # Temporary Holding Version
1
+ # @flexsmb54/react-native-widget
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ The Flex54 chat widget for React Native. It shows the hosted Flex54 widget in a WebView. It has no native code of its own, so it runs in Expo Go.
4
+
5
+ ## Install
6
+
7
+ Expo:
8
+
9
+ ```sh
10
+ npx expo install @flexsmb54/react-native-widget react-native-webview react-native-safe-area-context
11
+ ```
12
+
13
+ Bare React Native:
14
+
15
+ ```sh
16
+ npm install @flexsmb54/react-native-widget react-native-webview react-native-safe-area-context
17
+ cd ios && pod install
18
+ ```
19
+
20
+ Peer dependencies: `react >= 18`, `react-native >= 0.72`, `react-native-webview >= 13`, `react-native-safe-area-context >= 4`.
21
+
22
+ ## Usage
23
+
24
+ Render `<Flex54Widget>` **exactly once, as the last child of your root component**, so it draws above the rest of the app. It shows a chat button and, when opened, a full-screen chat. Touches anywhere else go to your app as usual.
25
+
26
+ ```tsx
27
+ import { Flex54Widget } from '@flexsmb54/react-native-widget';
28
+
29
+ export default function App() {
30
+ return (
31
+ <>
32
+ <RootNavigator />
33
+ <Flex54Widget widgetId="YOUR_WIDGET_ID" />
34
+ </>
35
+ );
36
+ }
37
+ ```
38
+
39
+ With Expo Router, do the same in `app/_layout.tsx`: put `<Flex54Widget>` after `<Stack />` or `<Tabs />`.
40
+
41
+ Multiple widgets at the same time are not supported. `Flex54` calls made while no widget is mounted are buffered, and replay when one mounts.
42
+
43
+ The widget brings its own `SafeAreaProvider`, so you don't need one above it.
44
+
45
+ ## Props
46
+
47
+ | Prop | Type | Default | Description |
48
+ | --- | --- | --- | --- |
49
+ | `widgetId` | `string` | required | Your Flex54 widget id. |
50
+ | `environment` | `'production' \| 'development'` | `'production'` | Which widget host to load. See [Environments](#environments). |
51
+ | `launcher` | `boolean` | `true` | Show the floating chat button. Set it to `false` to open the chat from your own UI with `Flex54.open()`. |
52
+ | `position` | `'bottom-right' \| 'bottom-left'` | `'bottom-right'` | Which corner the chat button sits in. It is inset by the safe area plus 16pt. |
53
+ | `onOpen` | `() => void` | | Called when the chat window has opened. |
54
+ | `onClose` | `() => void` | | Called when the chat window has closed: from the widget's own close button, `Flex54.close()` or Android back. It only fires after an `onOpen`. |
55
+
56
+ Set `widgetId` and `environment` once, when the widget mounts. Changing them on a mounted widget isn't supported. To switch, remount the component with a new `key`, for example `<Flex54Widget key={widgetId} widgetId={widgetId} />`.
57
+
58
+ ## `Flex54` API
59
+
60
+ Control the mounted widget from anywhere in your app:
61
+
62
+ ```ts
63
+ import { Flex54 } from '@flexsmb54/react-native-widget';
64
+
65
+ Flex54.open(); // show the chat
66
+ Flex54.close(); // hide the chat
67
+ Flex54.toggle(); // open if closed, close if open
68
+ Flex54.reset(); // discard the conversation, so the next open starts fresh
69
+ Flex54.isOpen(); // true while the chat is showing
70
+ ```
71
+
72
+ - Calls made while no widget is mounted (before it first mounts, or while it is unmounted) are queued and run, in order, when one mounts. `isOpen()` is `false` while no widget is mounted.
73
+ - **Call `Flex54.reset()` when the user logs out**, so the next person who uses the device doesn't see the previous conversation. The reset reaches the chat once the widget page has loaded, which normally happens within a second or two. If the chat hasn't been opened yet, the widget loads hidden to deliver it, and a pending reset carries over if the widget unmounts and mounts again. If the app is killed before the page loads, for example while the device is offline, the reset is lost, so call `Flex54.reset()` again when a different user signs in. `reset()` doesn't hide an open chat, so call `Flex54.close()` as well if you need to.
74
+
75
+ ```ts
76
+ async function logOut() {
77
+ Flex54.close();
78
+ Flex54.reset();
79
+ await auth.signOut();
80
+ }
81
+ ```
82
+
83
+ ## Environments
84
+
85
+ | `environment` | Widget host |
86
+ | --- | --- |
87
+ | `'production'` (default) | `https://agent.flex54.com` |
88
+ | `'development'` | `https://agent-dev.flex54.com` |
89
+
90
+ The widget loads `<host>/?widgetId=<id>&device=mobile&host=native&platform=react-native&sdkVersion=<version>`.
91
+
92
+ ## Microphone permission
93
+
94
+ Voice input uses the microphone, so the host app must declare it. Voice notes need iOS 14.5 or later.
95
+
96
+ iOS, in `Info.plist`:
97
+
98
+ ```xml
99
+ <key>NSMicrophoneUsageDescription</key>
100
+ <string>Allows you to send voice messages in chat.</string>
101
+ ```
102
+
103
+ Android, in `AndroidManifest.xml`:
104
+
105
+ ```xml
106
+ <uses-permission android:name="android.permission.RECORD_AUDIO" />
107
+ ```
108
+
109
+ Expo, in `app.json` (then rebuild the app; Expo Go already has these):
110
+
111
+ ```json
112
+ {
113
+ "expo": {
114
+ "ios": {
115
+ "infoPlist": {
116
+ "NSMicrophoneUsageDescription": "Allows you to send voice messages in chat."
117
+ }
118
+ },
119
+ "android": {
120
+ "permissions": ["android.permission.RECORD_AUDIO"]
121
+ }
122
+ }
123
+ }
124
+ ```
125
+
126
+ ## Phone and email links
127
+
128
+ `tel:` and `mailto:` links in the chat are opened by react-native-webview's default handling, which asks the system whether an app can open them. On Android 11 and later, that check needs `<queries>` entries in `AndroidManifest.xml`, or the links do nothing:
129
+
130
+ ```xml
131
+ <queries>
132
+ <intent>
133
+ <action android:name="android.intent.action.VIEW" />
134
+ <data android:scheme="tel" />
135
+ </intent>
136
+ <intent>
137
+ <action android:name="android.intent.action.VIEW" />
138
+ <data android:scheme="mailto" />
139
+ </intent>
140
+ </queries>
141
+ ```
142
+
143
+ ## How it works
144
+
145
+ `<Flex54Widget>` draws a chat button and, the first time the chat opens, a full-screen WebView that loads the hosted Flex54 widget with `host=native`. The page and the SDK talk through two small JSON envelopes. The widget posts `ready`, `opened` and `closed` events, and the SDK injects `open`, `close`, `toggle` and `reset` commands. The SDK re-syncs on every `ready` instead of replaying queued commands. Closing hides the surface and tells the widget to close, which unmounts the chat window and disconnects it, so nothing is billed while the chat is hidden. Links that leave the widget's origin open in the system browser. If the WebView's web process dies, the SDK reloads it. A page loaded more than 12 hours ago is reloaded when the chat next opens, so its session doesn't go stale.
146
+
147
+ ## Troubleshooting
148
+
149
+ - **The chat button doesn't show, or the chat appears behind your content.** Render `<Flex54Widget>` as the last child of the root component, not inside a screen, modal or `ScrollView`.
150
+ - **`Flex54.open()` does nothing, or opens a different widget.** Render exactly one `<Flex54Widget>`. Several at once are not supported.
151
+ - **The chat button covers your tab bar or another control.** Use `position="bottom-left"`, or set `launcher={false}` and call `Flex54.open()` from your own button.
152
+ - **"Couldn't load the chat".** The device is offline or the widget host is unreachable. "Try again" reloads the page.
153
+ - **"Couldn't load the chat" right after the page loads.** The page loaded but didn't answer as the chat widget within 10 seconds. Check `environment`: `production` and `development` load different widget hosts, and the one you point at must have the native-mode widget deployed. Tap Try again to reload. While the page is still loading, the X in the top-right corner closes the loading screen.
154
+ - **The microphone doesn't work.** Add the permissions above and rebuild the app. `Info.plist` and manifest changes need a native rebuild.
155
+ - **The keyboard covers the message box on Android.** Keyboard behaviour on Android 15 and later with edge-to-edge display is still being verified, and `android:windowSoftInputMode="adjustResize"` may not be enough there. If the keyboard covers the message box, please report it with the device, Android version and React Native version.
156
+ - **Android back.** While the chat is open, back closes it. Otherwise back goes to your app as usual.
157
+
158
+ ## License
159
+
160
+ MIT
Binary file
@@ -0,0 +1,5 @@
1
+ <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none">
2
+ <!-- iconsax Messages2, variant "Bulk" (iconsax-reactjs), fill #d9e3f0 -->
3
+ <path opacity=".4" d="m18.47 16.83.39 3.16c.1.83-.79 1.41-1.5.98l-4.19-2.49c-.46 0-.91-.03-1.35-.09A4.86 4.86 0 0 0 13 15.23c0-2.84-2.46-5.14-5.5-5.14-1.16 0-2.23.33-3.12.91-.03-.25-.04-.5-.04-.76C4.34 5.69 8.29 2 13.17 2S22 5.69 22 10.24c0 2.7-1.39 5.09-3.53 6.59Z" fill="#d9e3f0"/>
4
+ <path d="M13 15.23c0 1.19-.44 2.29-1.18 3.16-.99 1.2-2.56 1.97-4.32 1.97l-2.61 1.55c-.44.27-1-.1-.94-.61l.25-1.97C2.86 18.4 2 16.91 2 15.23c0-1.76.94-3.31 2.38-4.23.89-.58 1.96-.91 3.12-.91 3.04 0 5.5 2.3 5.5 5.14Z" fill="#d9e3f0"/>
5
+ </svg>
Binary file
Binary file
@@ -0,0 +1,7 @@
1
+ import * as React from 'react';
2
+ export type ErrorViewProps = {
3
+ onRetry: () => void;
4
+ onClose: () => void;
5
+ };
6
+ /** Shown over the WebView when the widget page fails to load. */
7
+ export declare function ErrorView({ onRetry, onClose }: ErrorViewProps): React.ReactElement;
@@ -0,0 +1,27 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.ErrorView = ErrorView;
4
+ const jsx_runtime_1 = require("react/jsx-runtime");
5
+ const react_native_1 = require("react-native");
6
+ /** Shown over the WebView when the widget page fails to load. */
7
+ function ErrorView({ onRetry, onClose }) {
8
+ return ((0, jsx_runtime_1.jsxs)(react_native_1.View, { style: [react_native_1.StyleSheet.absoluteFill, styles.container], children: [(0, jsx_runtime_1.jsx)(react_native_1.Text, { accessibilityRole: "header", style: styles.title, children: "Couldn't load the chat" }), (0, jsx_runtime_1.jsx)(react_native_1.Text, { style: styles.body, children: "Check your connection and try again." }), (0, jsx_runtime_1.jsxs)(react_native_1.View, { style: styles.actions, children: [(0, jsx_runtime_1.jsx)(react_native_1.Pressable, { accessibilityRole: "button", onPress: onRetry, style: ({ pressed }) => [styles.button, styles.primary, pressed && styles.pressed], children: (0, jsx_runtime_1.jsx)(react_native_1.Text, { style: [styles.label, styles.primaryLabel], children: "Try again" }) }), (0, jsx_runtime_1.jsx)(react_native_1.Pressable, { accessibilityRole: "button", onPress: onClose, style: ({ pressed }) => [styles.button, styles.secondary, pressed && styles.pressed], children: (0, jsx_runtime_1.jsx)(react_native_1.Text, { style: [styles.label, styles.secondaryLabel], children: "Close" }) })] })] }));
9
+ }
10
+ const styles = react_native_1.StyleSheet.create({
11
+ container: {
12
+ alignItems: 'center',
13
+ justifyContent: 'center',
14
+ padding: 24,
15
+ backgroundColor: '#ffffff',
16
+ },
17
+ title: { fontSize: 18, fontWeight: '600', color: '#000000', textAlign: 'center' },
18
+ body: { marginTop: 8, fontSize: 15, color: '#555555', textAlign: 'center' },
19
+ actions: { flexDirection: 'row', marginTop: 24, gap: 12 },
20
+ button: { minWidth: 112, paddingVertical: 12, paddingHorizontal: 20, borderRadius: 24, alignItems: 'center' },
21
+ primary: { backgroundColor: '#000000' },
22
+ secondary: { borderWidth: 1, borderColor: '#000000' },
23
+ pressed: { opacity: 0.8 },
24
+ label: { fontSize: 15, fontWeight: '600' },
25
+ primaryLabel: { color: '#ffffff' },
26
+ secondaryLabel: { color: '#000000' },
27
+ });
@@ -0,0 +1,13 @@
1
+ import type { Flex54Controller } from './controller';
2
+ /** Imperative API. Calls made before a widget mounts are buffered and replayed in order. */
3
+ export declare const Flex54: {
4
+ open: () => void;
5
+ close: () => void;
6
+ toggle: () => void;
7
+ reset: () => void;
8
+ isOpen: () => boolean;
9
+ };
10
+ /** Last registration wins. The returned function only unregisters if `c` is still active. */
11
+ export declare function registerController(c: Flex54Controller): () => void;
12
+ /** Test helper: clears the active controller, the pending-call buffer and any pending reset. */
13
+ export declare function resetFlex54ForTesting(): void;
package/lib/Flex54.js ADDED
@@ -0,0 +1,39 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.Flex54 = void 0;
4
+ exports.registerController = registerController;
5
+ exports.resetFlex54ForTesting = resetFlex54ForTesting;
6
+ const controller_1 = require("./controller");
7
+ let active = null;
8
+ let buffered = [];
9
+ function dispatch(call) {
10
+ if (active)
11
+ call(active);
12
+ else
13
+ buffered.push(call);
14
+ }
15
+ /** Imperative API. Calls made before a widget mounts are buffered and replayed in order. */
16
+ exports.Flex54 = {
17
+ open: () => dispatch((c) => c.open()),
18
+ close: () => dispatch((c) => c.close()),
19
+ toggle: () => dispatch((c) => c.toggle()),
20
+ reset: () => dispatch((c) => c.reset()),
21
+ isOpen: () => (active ? active.isOpen() : false),
22
+ };
23
+ /** Last registration wins. The returned function only unregisters if `c` is still active. */
24
+ function registerController(c) {
25
+ active = c;
26
+ const pending = buffered;
27
+ buffered = [];
28
+ pending.forEach((call) => call(c));
29
+ return () => {
30
+ if (active === c)
31
+ active = null;
32
+ };
33
+ }
34
+ /** Test helper: clears the active controller, the pending-call buffer and any pending reset. */
35
+ function resetFlex54ForTesting() {
36
+ active = null;
37
+ buffered = [];
38
+ (0, controller_1.clearPendingResetForTesting)();
39
+ }
@@ -0,0 +1,24 @@
1
+ import * as React from 'react';
2
+ import type { Flex54Environment, Flex54Position } from './types';
3
+ export type Flex54WidgetProps = {
4
+ widgetId: string;
5
+ /** Default `'production'`. */
6
+ environment?: Flex54Environment;
7
+ /** Show the floating chat button. Default `true`. */
8
+ launcher?: boolean;
9
+ /** Default `'bottom-right'`. */
10
+ position?: Flex54Position;
11
+ onOpen?: () => void;
12
+ onClose?: () => void;
13
+ };
14
+ /**
15
+ * How long after the page finishes loading the widget has to send `ready`. A loaded page
16
+ * that stays silent is not a native-mode widget (e.g. a stale cached copy, or an older
17
+ * deploy), so show the error view instead of spinning forever.
18
+ */
19
+ export declare const READY_TIMEOUT_MS = 10000;
20
+ /**
21
+ * The Flex54 chat widget. Render it once, as the last child of your root component.
22
+ * It draws a launcher and a full-screen chat surface over the app; touches elsewhere pass through.
23
+ */
24
+ export declare function Flex54Widget(props: Flex54WidgetProps): React.ReactElement;
@@ -0,0 +1,175 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ var __importDefault = (this && this.__importDefault) || function (mod) {
36
+ return (mod && mod.__esModule) ? mod : { "default": mod };
37
+ };
38
+ Object.defineProperty(exports, "__esModule", { value: true });
39
+ exports.READY_TIMEOUT_MS = void 0;
40
+ exports.Flex54Widget = Flex54Widget;
41
+ const jsx_runtime_1 = require("react/jsx-runtime");
42
+ const React = __importStar(require("react"));
43
+ const react_native_1 = require("react-native");
44
+ const react_native_safe_area_context_1 = require("react-native-safe-area-context");
45
+ const react_native_webview_1 = __importDefault(require("react-native-webview"));
46
+ const controller_1 = require("./controller");
47
+ const ErrorView_1 = require("./ErrorView");
48
+ const Flex54_1 = require("./Flex54");
49
+ const Launcher_1 = require("./Launcher");
50
+ const protocol_1 = require("./protocol");
51
+ const url_1 = require("./url");
52
+ const SLIDE_MS = 250;
53
+ /**
54
+ * How long after the page finishes loading the widget has to send `ready`. A loaded page
55
+ * that stays silent is not a native-mode widget (e.g. a stale cached copy, or an older
56
+ * deploy), so show the error view instead of spinning forever.
57
+ */
58
+ exports.READY_TIMEOUT_MS = 10000;
59
+ /**
60
+ * The Flex54 chat widget. Render it once, as the last child of your root component.
61
+ * It draws a launcher and a full-screen chat surface over the app; touches elsewhere pass through.
62
+ */
63
+ function Flex54Widget(props) {
64
+ return ((0, jsx_runtime_1.jsx)(react_native_safe_area_context_1.SafeAreaProvider, { style: react_native_1.StyleSheet.absoluteFill, pointerEvents: "box-none", children: (0, jsx_runtime_1.jsx)(WidgetHost, { ...props }) }));
65
+ }
66
+ function openExternal(url) {
67
+ // Rejects when nothing can handle the URL; there is nothing useful to do about it here.
68
+ react_native_1.Linking.openURL(url).catch(() => { });
69
+ }
70
+ function WidgetHost({ widgetId, environment = 'production', launcher = true, position = 'bottom-right', onOpen, onClose, }) {
71
+ const controllerRef = React.useRef(null);
72
+ if (controllerRef.current === null)
73
+ controllerRef.current = new controller_1.Flex54Controller();
74
+ const controller = controllerRef.current;
75
+ const { mounted, visible, ready, loadError, webViewKey } = React.useSyncExternalStore(controller.subscribe, controller.getState);
76
+ const insets = (0, react_native_safe_area_context_1.useSafeAreaInsets)();
77
+ const { height } = (0, react_native_1.useWindowDimensions)();
78
+ // `object`, not the default `undefined`: react-native-webview types props as `WebViewProps & P`.
79
+ const webviewRef = React.useRef(null);
80
+ React.useLayoutEffect(() => {
81
+ controller.setCallbacks({ onOpen, onClose });
82
+ });
83
+ // One stable sender for the component's lifetime. It reads the ref at call time, so it
84
+ // follows WebView remounts (retry, process death) without being re-attached; detaching
85
+ // in between could drop a `close` and leave the chat open behind a hidden surface.
86
+ React.useEffect(() => {
87
+ controller.attachSender((command) => webviewRef.current?.injectJavaScript((0, protocol_1.buildCommandScript)(command)));
88
+ return () => controller.attachSender(null);
89
+ }, [controller]);
90
+ React.useEffect(() => (0, Flex54_1.registerController)(controller), [controller]);
91
+ // Registered only while the chat is visible, so it is the newest listener and runs
92
+ // before the app's own (e.g. navigation) back handlers.
93
+ React.useEffect(() => {
94
+ if (!visible)
95
+ return;
96
+ const subscription = react_native_1.BackHandler.addEventListener('hardwareBackPress', () => {
97
+ if (!controller.isOpen())
98
+ return false;
99
+ controller.close();
100
+ return true;
101
+ });
102
+ return () => subscription.remove();
103
+ }, [controller, visible]);
104
+ const [translateY] = React.useState(() => new react_native_1.Animated.Value(height));
105
+ React.useEffect(() => {
106
+ if (!mounted)
107
+ return;
108
+ react_native_1.Animated.timing(translateY, {
109
+ toValue: visible ? 0 : height,
110
+ duration: SLIDE_MS,
111
+ useNativeDriver: true,
112
+ }).start();
113
+ }, [translateY, mounted, visible, height]);
114
+ const origin = (0, url_1.widgetOrigin)(environment);
115
+ const uri = (0, url_1.buildWidgetUrl)({ widgetId, environment });
116
+ const source = React.useMemo(() => ({ uri }), [uri]);
117
+ // Armed when a page finishes loading; cancelled by `ready`, by a WebView remount (new key)
118
+ // and on unmount, so a replaced page's deadline never fails its successor.
119
+ const readyTimerRef = React.useRef(null);
120
+ const clearReadyTimer = React.useCallback(() => {
121
+ if (readyTimerRef.current !== null)
122
+ clearTimeout(readyTimerRef.current);
123
+ readyTimerRef.current = null;
124
+ }, []);
125
+ React.useEffect(() => {
126
+ if (ready)
127
+ clearReadyTimer();
128
+ }, [ready, clearReadyTimer]);
129
+ React.useEffect(() => clearReadyTimer, [webViewKey, clearReadyTimer]);
130
+ const onLoadEnd = () => {
131
+ clearReadyTimer();
132
+ if (controller.getState().ready)
133
+ return;
134
+ readyTimerRef.current = setTimeout(() => {
135
+ readyTimerRef.current = null;
136
+ if (!controller.getState().ready)
137
+ controller.handleLoadError();
138
+ }, exports.READY_TIMEOUT_MS);
139
+ };
140
+ const onMessage = (e) => {
141
+ const event = (0, protocol_1.parseWidgetMessage)(e.nativeEvent.data);
142
+ if (event)
143
+ controller.handleWidgetEvent(event);
144
+ };
145
+ const onShouldStartLoadWithRequest = (req) => {
146
+ if (req.isTopFrame === false || (0, url_1.shouldLoadInWebView)(req.url, origin))
147
+ return true;
148
+ openExternal(req.url);
149
+ // Before `ready`, a blocked top-frame request means the page itself never loads (e.g. an
150
+ // off-origin redirect). WKWebView reports the cancelled load as error 102, which
151
+ // react-native-webview drops, so show the error view instead of an endless spinner.
152
+ if (!controller.getState().ready)
153
+ controller.handleLoadError();
154
+ return false;
155
+ };
156
+ return ((0, jsx_runtime_1.jsxs)(react_native_1.View, { testID: "flex54-root", style: react_native_1.StyleSheet.absoluteFill, pointerEvents: "box-none", children: [launcher && !visible ? ((0, jsx_runtime_1.jsx)(Launcher_1.Launcher, { position: position, insets: insets, onPress: () => controller.open() })) : null, mounted ? ((0, jsx_runtime_1.jsxs)(react_native_1.Animated.View, { testID: "flex54-surface", pointerEvents: visible ? 'auto' : 'none', accessibilityElementsHidden: !visible, importantForAccessibility: visible ? 'auto' : 'no-hide-descendants', style: [react_native_1.StyleSheet.absoluteFill, { transform: [{ translateY }] }], children: [(0, jsx_runtime_1.jsxs)(react_native_safe_area_context_1.SafeAreaView, { edges: ['top', 'right', 'bottom', 'left'], style: styles.safeArea, children: [(0, jsx_runtime_1.jsx)(react_native_webview_1.default, { ref: webviewRef, source: source, style: styles.webview, onMessage: onMessage, onLoadEnd: onLoadEnd, onShouldStartLoadWithRequest: onShouldStartLoadWithRequest, onOpenWindow: (e) => openExternal(e.nativeEvent.targetUrl), onError: () => controller.handleLoadError(), onHttpError: (e) => {
157
+ if (e.nativeEvent.statusCode >= 400)
158
+ controller.handleLoadError();
159
+ }, onContentProcessDidTerminate: () => controller.handleProcessTerminated(), onRenderProcessGone: () => controller.handleProcessTerminated(), domStorageEnabled: true, javaScriptEnabled: true, allowsInlineMediaPlayback: true, mediaCapturePermissionGrantType: "grantIfSameHostElsePrompt", allowsBackForwardNavigationGestures: false, webviewDebuggingEnabled: __DEV__ }, webViewKey), loadError ? (0, jsx_runtime_1.jsx)(ErrorView_1.ErrorView, { onRetry: () => controller.retry(), onClose: () => controller.close() }) : null] }), visible && !ready && !loadError ? ((0, jsx_runtime_1.jsxs)(react_native_1.View, { style: [react_native_1.StyleSheet.absoluteFill, styles.loading], children: [(0, jsx_runtime_1.jsx)(react_native_1.ActivityIndicator, { testID: "flex54-loading", accessibilityLabel: "Loading chat" }), (0, jsx_runtime_1.jsxs)(react_native_1.Pressable, { accessibilityRole: "button", accessibilityLabel: "Close chat", onPress: () => controller.close(), style: ({ pressed }) => [
160
+ styles.closeButton,
161
+ { top: insets.top + 8, right: insets.right + 8 },
162
+ pressed && styles.pressed,
163
+ ], children: [(0, jsx_runtime_1.jsx)(react_native_1.View, { style: [styles.closeBar, styles.closeBarA] }), (0, jsx_runtime_1.jsx)(react_native_1.View, { style: [styles.closeBar, styles.closeBarB] })] })] })) : null] })) : null] }));
164
+ }
165
+ const styles = react_native_1.StyleSheet.create({
166
+ safeArea: { flex: 1, backgroundColor: '#ffffff' },
167
+ webview: { flex: 1, backgroundColor: '#ffffff' },
168
+ loading: { alignItems: 'center', justifyContent: 'center', backgroundColor: '#ffffff' },
169
+ // 44pt touch target with a quiet dark-grey X drawn from two rotated bars.
170
+ closeButton: { position: 'absolute', width: 44, height: 44, alignItems: 'center', justifyContent: 'center' },
171
+ closeBar: { position: 'absolute', width: 18, height: 2, borderRadius: 1, backgroundColor: '#444444' },
172
+ closeBarA: { transform: [{ rotate: '45deg' }] },
173
+ closeBarB: { transform: [{ rotate: '-45deg' }] },
174
+ pressed: { opacity: 0.5 },
175
+ });
@@ -0,0 +1,10 @@
1
+ import * as React from 'react';
2
+ import type { EdgeInsets } from 'react-native-safe-area-context';
3
+ import type { Flex54Position } from './types';
4
+ export type LauncherProps = {
5
+ position: Flex54Position;
6
+ insets: EdgeInsets;
7
+ onPress: () => void;
8
+ };
9
+ /** Floating chat button; matches the web widget's ChatButton. */
10
+ export declare function Launcher({ position, insets, onPress }: LauncherProps): React.ReactElement;
@@ -0,0 +1,28 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.Launcher = Launcher;
4
+ const jsx_runtime_1 = require("react/jsx-runtime");
5
+ const react_native_1 = require("react-native");
6
+ // iconsax Messages2 "Bulk" in #d9e3f0, pre-rendered by scripts/render-icon.mjs (Metro picks @2x/@3x).
7
+ const CHAT_ICON = require('../assets/chat.png');
8
+ const MARGIN = 16;
9
+ /** Floating chat button; matches the web widget's ChatButton. */
10
+ function Launcher({ position, insets, onPress }) {
11
+ const placement = position === 'bottom-left'
12
+ ? { bottom: insets.bottom + MARGIN, left: insets.left + MARGIN }
13
+ : { bottom: insets.bottom + MARGIN, right: insets.right + MARGIN };
14
+ return ((0, jsx_runtime_1.jsx)(react_native_1.Pressable, { accessibilityRole: "button", accessibilityLabel: "Open chat", onPress: onPress, style: ({ pressed }) => [styles.button, placement, pressed && styles.pressed], children: (0, jsx_runtime_1.jsx)(react_native_1.Image, { source: CHAT_ICON, style: styles.icon }) }));
15
+ }
16
+ const styles = react_native_1.StyleSheet.create({
17
+ button: {
18
+ position: 'absolute',
19
+ width: 56,
20
+ height: 56,
21
+ borderRadius: 28,
22
+ backgroundColor: '#000000',
23
+ alignItems: 'center',
24
+ justifyContent: 'center',
25
+ },
26
+ pressed: { opacity: 0.8 },
27
+ icon: { width: 32, height: 32 },
28
+ });
@@ -0,0 +1,51 @@
1
+ import type { HostCommand, WidgetEvent } from './types';
2
+ export type SurfaceState = {
3
+ mounted: boolean;
4
+ visible: boolean;
5
+ ready: boolean;
6
+ loadError: boolean;
7
+ webViewKey: number;
8
+ };
9
+ export type ControllerCallbacks = {
10
+ onOpen?: () => void;
11
+ onClose?: () => void;
12
+ };
13
+ /**
14
+ * The widget fetches its config and token once per page load, and the token expires, so a
15
+ * page older than this is reloaded on open instead of being reused.
16
+ */
17
+ export declare const MAX_PAGE_AGE_MS: number;
18
+ /** Internal: clears the shared pending reset. Used by `resetFlex54ForTesting`; not exported from the package. */
19
+ export declare function clearPendingResetForTesting(): void;
20
+ /**
21
+ * Pure state machine behind the widget surface. Implements the "Host responsibilities"
22
+ * of PROTOCOL.md: sync state on every `ready` instead of replaying a command queue.
23
+ * `subscribe` and `getState` are arrow properties, so they can be passed around unbound
24
+ * (e.g. straight into `useSyncExternalStore`).
25
+ */
26
+ export declare class Flex54Controller {
27
+ private state;
28
+ private listeners;
29
+ private sender;
30
+ private callbacks;
31
+ private now;
32
+ private readyAt;
33
+ private widgetOpen;
34
+ constructor(callbacks?: ControllerCallbacks, now?: () => number);
35
+ setCallbacks(cb: ControllerCallbacks): void;
36
+ attachSender(send: ((c: HostCommand) => void) | null): void;
37
+ subscribe: (listener: () => void) => (() => void);
38
+ getState: () => SurfaceState;
39
+ private update;
40
+ private send;
41
+ open(): void;
42
+ close(): void;
43
+ toggle(): void;
44
+ reset(): void;
45
+ isOpen(): boolean;
46
+ handleWidgetEvent(e: WidgetEvent): void;
47
+ handleLoadError(): void;
48
+ retry(): void;
49
+ handleProcessTerminated(): void;
50
+ private remount;
51
+ }