@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.
@@ -0,0 +1,49 @@
1
+ import * as React from 'react';
2
+ import { Image, Pressable, StyleSheet } from 'react-native';
3
+ import type { ImageSourcePropType } from 'react-native';
4
+ import type { EdgeInsets } from 'react-native-safe-area-context';
5
+ import type { Flex54Position } from './types';
6
+
7
+ // iconsax Messages2 "Bulk" in #d9e3f0, pre-rendered by scripts/render-icon.mjs (Metro picks @2x/@3x).
8
+ const CHAT_ICON: ImageSourcePropType = require('../assets/chat.png');
9
+
10
+ const MARGIN = 16;
11
+
12
+ export type LauncherProps = {
13
+ position: Flex54Position;
14
+ insets: EdgeInsets;
15
+ onPress: () => void;
16
+ };
17
+
18
+ /** Floating chat button; matches the web widget's ChatButton. */
19
+ export function Launcher({ position, insets, onPress }: LauncherProps): React.ReactElement {
20
+ const placement =
21
+ position === 'bottom-left'
22
+ ? { bottom: insets.bottom + MARGIN, left: insets.left + MARGIN }
23
+ : { bottom: insets.bottom + MARGIN, right: insets.right + MARGIN };
24
+
25
+ return (
26
+ <Pressable
27
+ accessibilityRole="button"
28
+ accessibilityLabel="Open chat"
29
+ onPress={onPress}
30
+ style={({ pressed }) => [styles.button, placement, pressed && styles.pressed]}
31
+ >
32
+ <Image source={CHAT_ICON} style={styles.icon} />
33
+ </Pressable>
34
+ );
35
+ }
36
+
37
+ const styles = StyleSheet.create({
38
+ button: {
39
+ position: 'absolute',
40
+ width: 56,
41
+ height: 56,
42
+ borderRadius: 28,
43
+ backgroundColor: '#000000',
44
+ alignItems: 'center',
45
+ justifyContent: 'center',
46
+ },
47
+ pressed: { opacity: 0.8 },
48
+ icon: { width: 32, height: 32 },
49
+ });
@@ -0,0 +1,166 @@
1
+ import type { HostCommand, WidgetEvent } from './types';
2
+
3
+ export type SurfaceState = {
4
+ mounted: boolean;
5
+ visible: boolean;
6
+ ready: boolean;
7
+ loadError: boolean;
8
+ webViewKey: number;
9
+ };
10
+
11
+ export type ControllerCallbacks = { onOpen?: () => void; 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 const MAX_PAGE_AGE_MS = 12 * 60 * 60 * 1000;
18
+
19
+ // Shared by every controller (only one widget is supported at a time), so a reset requested
20
+ // before `ready` still reaches the page when the widget unmounts and a new one mounts.
21
+ let pendingReset = false;
22
+
23
+ /** Internal: clears the shared pending reset. Used by `resetFlex54ForTesting`; not exported from the package. */
24
+ export function clearPendingResetForTesting(): void {
25
+ pendingReset = false;
26
+ }
27
+
28
+ /**
29
+ * Pure state machine behind the widget surface. Implements the "Host responsibilities"
30
+ * of PROTOCOL.md: sync state on every `ready` instead of replaying a command queue.
31
+ * `subscribe` and `getState` are arrow properties, so they can be passed around unbound
32
+ * (e.g. straight into `useSyncExternalStore`).
33
+ */
34
+ export class Flex54Controller {
35
+ private state: SurfaceState = {
36
+ // Mount hidden when a reset is pending, so it is delivered without the user opening the chat.
37
+ mounted: pendingReset,
38
+ visible: false,
39
+ ready: false,
40
+ loadError: false,
41
+ webViewKey: 0,
42
+ };
43
+ private listeners = new Set<() => void>();
44
+ private sender: ((c: HostCommand) => void) | null = null;
45
+ private callbacks: ControllerCallbacks;
46
+ private now: () => number;
47
+ private readyAt = 0;
48
+ private widgetOpen = false;
49
+
50
+ constructor(callbacks: ControllerCallbacks = {}, now: () => number = Date.now) {
51
+ this.callbacks = callbacks;
52
+ this.now = now;
53
+ }
54
+
55
+ setCallbacks(cb: ControllerCallbacks): void {
56
+ this.callbacks = cb;
57
+ }
58
+
59
+ attachSender(send: ((c: HostCommand) => void) | null): void {
60
+ this.sender = send;
61
+ }
62
+
63
+ subscribe = (listener: () => void): (() => void) => {
64
+ this.listeners.add(listener);
65
+ return () => {
66
+ this.listeners.delete(listener);
67
+ };
68
+ };
69
+
70
+ getState = (): SurfaceState => this.state;
71
+
72
+ private update(patch: Partial<SurfaceState>): void {
73
+ const next = { ...this.state, ...patch };
74
+ const changed = (Object.keys(next) as (keyof SurfaceState)[]).some(
75
+ (k) => next[k] !== this.state[k],
76
+ );
77
+ if (!changed) return;
78
+ this.state = next;
79
+ [...this.listeners].forEach((l) => l());
80
+ }
81
+
82
+ private send(command: HostCommand): void {
83
+ this.sender?.(command);
84
+ }
85
+
86
+ open(): void {
87
+ // A load error is sticky until retried, so reopening retries.
88
+ if (this.state.loadError) this.retry();
89
+ this.update({ mounted: true, visible: true });
90
+ if (!this.state.ready) return;
91
+ // The next `ready` opens the reloaded page.
92
+ if (this.now() - this.readyAt > MAX_PAGE_AGE_MS) this.remount();
93
+ else this.send('open');
94
+ }
95
+
96
+ close(): void {
97
+ if (!this.state.visible) return;
98
+ this.update({ visible: false });
99
+ // Sent even before ready: the injected script is guarded by `window.Flex54Bridge&&`,
100
+ // so it is a no-op on a page without the bridge.
101
+ this.send('close');
102
+ }
103
+
104
+ toggle(): void {
105
+ if (this.state.visible) this.close();
106
+ else this.open();
107
+ }
108
+
109
+ reset(): void {
110
+ pendingReset = true;
111
+ this.update({ mounted: true });
112
+ if (this.state.ready) {
113
+ pendingReset = false;
114
+ this.send('reset');
115
+ }
116
+ }
117
+
118
+ isOpen(): boolean {
119
+ return this.state.visible;
120
+ }
121
+
122
+ handleWidgetEvent(e: WidgetEvent): void {
123
+ switch (e) {
124
+ case 'ready':
125
+ this.readyAt = this.now();
126
+ this.update({ ready: true, loadError: false });
127
+ if (pendingReset) {
128
+ pendingReset = false;
129
+ this.send('reset');
130
+ }
131
+ if (this.state.visible) this.send('open');
132
+ break;
133
+ case 'opened':
134
+ this.widgetOpen = true;
135
+ // Never leave the chat open behind a hidden surface (billing invariant).
136
+ if (!this.state.visible) this.send('close');
137
+ this.callbacks.onOpen?.();
138
+ break;
139
+ case 'closed':
140
+ if (!this.widgetOpen) return;
141
+ this.widgetOpen = false;
142
+ // Hide first so onClose sees consistent state and may safely call open().
143
+ if (this.state.visible) this.update({ visible: false });
144
+ this.callbacks.onClose?.();
145
+ break;
146
+ }
147
+ }
148
+
149
+ handleLoadError(): void {
150
+ this.update({ loadError: true, ready: false });
151
+ }
152
+
153
+ retry(): void {
154
+ this.update({ loadError: false });
155
+ this.remount();
156
+ }
157
+
158
+ handleProcessTerminated(): void {
159
+ this.remount();
160
+ }
161
+
162
+ private remount(): void {
163
+ this.widgetOpen = false;
164
+ this.update({ ready: false, webViewKey: this.state.webViewKey + 1 });
165
+ }
166
+ }
package/src/index.ts ADDED
@@ -0,0 +1,4 @@
1
+ export type { Flex54Environment, Flex54Position, HostCommand, WidgetEvent } from './types';
2
+ export { Flex54 } from './Flex54';
3
+ export { Flex54Widget } from './Flex54Widget';
4
+ export type { Flex54WidgetProps } from './Flex54Widget';
@@ -0,0 +1,25 @@
1
+ import type { HostCommand, WidgetEvent } from './types';
2
+
3
+ const WIDGET_SOURCE = 'kaabo-ai-widget';
4
+ const HOST_SOURCE = 'flex54-host';
5
+ const EVENTS: readonly WidgetEvent[] = ['ready', 'opened', 'closed'];
6
+
7
+ /** Parses a WebView message from the widget. Returns null for foreign or malformed data. */
8
+ export function parseWidgetMessage(data: string): WidgetEvent | null {
9
+ let parsed: unknown;
10
+ try {
11
+ parsed = JSON.parse(data);
12
+ } catch {
13
+ return null;
14
+ }
15
+ if (!parsed || typeof parsed !== 'object') return null;
16
+ const { source, v, event } = parsed as Record<string, unknown>;
17
+ if (source !== WIDGET_SOURCE || v !== 1) return null;
18
+ return EVENTS.find((e) => e === event) ?? null;
19
+ }
20
+
21
+ /** JavaScript to inject into the WebView to deliver a command to the widget. */
22
+ export function buildCommandScript(command: HostCommand): string {
23
+ const message = JSON.stringify({ source: HOST_SOURCE, v: 1, command });
24
+ return `window.Flex54Bridge&&window.Flex54Bridge.receive(${message});true;`;
25
+ }
package/src/types.ts ADDED
@@ -0,0 +1,4 @@
1
+ export type Flex54Environment = 'production' | 'development';
2
+ export type Flex54Position = 'bottom-right' | 'bottom-left';
3
+ export type HostCommand = 'open' | 'close' | 'toggle' | 'reset';
4
+ export type WidgetEvent = 'ready' | 'opened' | 'closed';
package/src/url.ts ADDED
@@ -0,0 +1,37 @@
1
+ import type { Flex54Environment } from './types';
2
+ import { SDK_VERSION } from './version';
3
+
4
+ const ORIGINS: Record<Flex54Environment, string> = {
5
+ production: 'https://agent.flex54.com',
6
+ development: 'https://agent-dev.flex54.com',
7
+ };
8
+
9
+ export function widgetOrigin(env: Flex54Environment): string {
10
+ return ORIGINS[env];
11
+ }
12
+
13
+ // URLSearchParams is only partially implemented in React Native, so encode by hand
14
+ // (form-encoding: space becomes '+').
15
+ const enc = (value: string) => encodeURIComponent(value).replace(/%20/g, '+');
16
+
17
+ export function buildWidgetUrl(opts: { widgetId: string; environment: Flex54Environment }): string {
18
+ const params: [string, string][] = [
19
+ ['widgetId', opts.widgetId],
20
+ ['device', 'mobile'],
21
+ ['host', 'native'],
22
+ ['platform', 'react-native'],
23
+ ['sdkVersion', SDK_VERSION],
24
+ ];
25
+ const query = params.map(([k, v]) => `${enc(k)}=${enc(v)}`).join('&');
26
+ return `${widgetOrigin(opts.environment)}/?${query}`;
27
+ }
28
+
29
+ /** True for URLs the WebView should load itself; everything else goes to the system browser. */
30
+ export function shouldLoadInWebView(url: string, origin: string): boolean {
31
+ if (typeof url !== 'string') return false;
32
+ if (url === 'about:blank' || url === 'about:srcdoc') return true;
33
+ if (/^(blob|data):/i.test(url)) return true;
34
+ if (!url.startsWith(origin)) return false;
35
+ const next = url.charAt(origin.length);
36
+ return next === '' || next === '/' || next === '?' || next === '#';
37
+ }
package/src/version.ts ADDED
@@ -0,0 +1 @@
1
+ export const SDK_VERSION = '0.1.1';