@ahmedramez-org/chat 0.0.0-stage → 0.6.0-beta.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/react.js ADDED
@@ -0,0 +1,312 @@
1
+ // <IncortaChat /> — the connector as a React component (the app's React 18 or
2
+ // 19 renders only this wrapper; the chat runs its own React). Two ways in:
3
+ //
4
+ // - Direct: the chat mounts into an element this renders, sharing the page's
5
+ // session. It fills its box and the app draws any frame around it, or, with
6
+ // `modes` or `defaultMode` instead of a `window`, it draws the same window
7
+ // as embedded.
8
+ // - Embedded (`embedUrl`): the chat runs in an <iframe> served by Incorta, on
9
+ // the user's own Incorta session, so the app never holds a token. This
10
+ // draws the window too: a launcher icon that opens the chat floating,
11
+ // docked or fullscreen (the app picks which with `modes`).
12
+ import { createElement as h, useEffect, useRef, useState } from 'react';
13
+
14
+ import { CONTRACT_VERSION, loadChat, mountLoadedChat, showChatSkeleton } from './index.js';
15
+ import { connectEmbeddedChat, createChatWindow, embedSrc, initialView } from './window.js';
16
+
17
+ function emitter() {
18
+ const listeners = new Set();
19
+ return {
20
+ notify: () => listeners.forEach((onChange) => onChange()),
21
+ subscribe(onChange) {
22
+ listeners.add(onChange);
23
+ return () => listeners.delete(onChange);
24
+ },
25
+ };
26
+ }
27
+
28
+ function DirectChat({
29
+ theme,
30
+ locale,
31
+ direction,
32
+ tenantId,
33
+ user,
34
+ window: hostWindow,
35
+ onReady,
36
+ onLoadError,
37
+ className,
38
+ style,
39
+ ...mountOptions
40
+ }) {
41
+ const element = useRef(null);
42
+ const latest = useRef(null);
43
+ latest.current = { theme, locale, direction, tenantId, user, hostWindow, onReady, onLoadError };
44
+ const environment = useRef(null);
45
+ environment.current ??= emitter();
46
+ const windowState = useRef(null);
47
+ windowState.current ??= emitter();
48
+ const hasWindow = Boolean(hostWindow);
49
+ // Until the chat is mounted the skeleton holds the box, the same loading
50
+ // face as the embedded window, so every app shows one.
51
+ const [status, setStatus] = useState('loading');
52
+
53
+ useEffect(
54
+ () => environment.current.notify(),
55
+ [theme, locale, direction, tenantId, user?.id, user?.name],
56
+ );
57
+ useEffect(
58
+ () => windowState.current.notify(),
59
+ [
60
+ hostWindow?.docked,
61
+ hostWindow?.canDock,
62
+ hostWindow?.mode,
63
+ hostWindow?.modes?.join(),
64
+ hostWindow?.hidden,
65
+ ],
66
+ );
67
+
68
+ // Mounts once per element (and again only if `window` appears or goes):
69
+ // options other than the ones above are read at mount. It loads first and
70
+ // mounts only if the effect is still live, so StrictMode's replayed effect
71
+ // never mounts twice into the same element.
72
+ useEffect(() => {
73
+ let handle;
74
+ let cancelled = false;
75
+ const current = () => latest.current;
76
+ const { assetsUrl, timeoutMs, ...options } = mountOptions;
77
+ const source = { url: options.connection?.url, assetsUrl, timeoutMs };
78
+ // A contract `environment` or `window` the app built itself is used as is.
79
+ const ownWindow = typeof hostWindow?.get === 'function';
80
+ const mountOptionsFor = () => ({
81
+ version: CONTRACT_VERSION,
82
+ ...options,
83
+ environment: options.environment ?? {
84
+ get: () => {
85
+ const props = current();
86
+ return {
87
+ theme: props.theme,
88
+ locale: props.locale ?? navigator.language,
89
+ ...(props.direction ? { direction: props.direction } : {}),
90
+ ...(props.tenantId ? { tenantId: props.tenantId } : {}),
91
+ ...(props.user ? { user: props.user } : {}),
92
+ };
93
+ },
94
+ subscribe: environment.current.subscribe,
95
+ },
96
+ ...(ownWindow
97
+ ? { window: hostWindow }
98
+ : hasWindow
99
+ ? {
100
+ window: {
101
+ get: () => {
102
+ const { docked, canDock, mode, modes, hidden } = current().hostWindow ?? {};
103
+ const named = Boolean(mode && modes);
104
+ return {
105
+ // A window named by its mode only: what an older chat reads (beside the page
106
+ // is "docked"; docking needs full screen and another mode).
107
+ docked: docked ?? (named && mode !== 'fullscreen'),
108
+ canDock:
109
+ canDock ??
110
+ (named &&
111
+ modes.includes('fullscreen') &&
112
+ modes.some((other) => other !== 'fullscreen')),
113
+ ...(named ? { mode, modes } : {}),
114
+ ...(hidden ? { hidden: true } : {}),
115
+ };
116
+ },
117
+ subscribe: windowState.current.subscribe,
118
+ setDocked: (docked) => {
119
+ const props = current().hostWindow;
120
+ if (props?.setDocked) return props.setDocked(docked);
121
+ const next = docked
122
+ ? props?.modes?.find((mode) => mode !== 'fullscreen')
123
+ : 'fullscreen';
124
+ if (next) props?.setMode?.(next);
125
+ },
126
+ // Read at mount, like the rest of `window`'s shape (`close` too).
127
+ ...(hostWindow.setMode
128
+ ? { setMode: (mode) => current().hostWindow?.setMode?.(mode) }
129
+ : {}),
130
+ ...(hostWindow.close ? { close: () => current().hostWindow?.close?.() } : {}),
131
+ },
132
+ }
133
+ : {}),
134
+ });
135
+ const fail = (error) => {
136
+ if (cancelled) return;
137
+ // The app draws its own failure (and Retry) where the chat would be.
138
+ setStatus('failed');
139
+ current().onLoadError?.(error);
140
+ };
141
+ // In a promise, so a missing source reaches onLoadError like any load failure.
142
+ Promise.resolve()
143
+ .then(() => loadChat(source))
144
+ .then((mount) => {
145
+ if (cancelled) return;
146
+ try {
147
+ handle = mountLoadedChat(mount, element.current, mountOptionsFor(), source);
148
+ } catch (error) {
149
+ return fail(error);
150
+ }
151
+ setStatus('ready');
152
+ current().onReady?.(handle);
153
+ }, fail);
154
+ return () => {
155
+ cancelled = true;
156
+ const mounted = handle;
157
+ handle = undefined;
158
+ if (!mounted) return;
159
+ try {
160
+ mounted.unmount();
161
+ } catch (error) {
162
+ // Called on the app's own events object: its `onError` may read `this`.
163
+ if (options.events?.onError) options.events.onError(error, { scope: 'unmount' });
164
+ else console.error('The chat could not be unmounted cleanly.', error);
165
+ }
166
+ current().onReady?.(null);
167
+ };
168
+ }, [hasWindow]);
169
+
170
+ // The app's className and style stay on the chat's own root (the mount element).
171
+ return h(
172
+ 'div',
173
+ { style: { position: 'relative', width: '100%', height: '100%' } },
174
+ h('div', { ref: element, className, style: { width: '100%', height: '100%', ...style } }),
175
+ // A failure leaves at once: the app's own failure takes the box.
176
+ h(Skeleton, { status, theme: theme ?? mountOptions.environment?.get().theme }),
177
+ );
178
+ }
179
+
180
+ /**
181
+ * The skeleton (index.js) over the box that holds this, until the chat is
182
+ * 'ready' (it fades) or 'failed' (gone at once).
183
+ */
184
+ function Skeleton({ status, theme }) {
185
+ const anchor = useRef(null);
186
+ const skeleton = useRef(null);
187
+ useEffect(() => {
188
+ const shown = showChatSkeleton(anchor.current.parentNode, theme);
189
+ skeleton.current = shown;
190
+ return shown.remove;
191
+ }, []);
192
+ useEffect(() => skeleton.current.setTheme(theme), [theme]);
193
+ useEffect(() => {
194
+ if (status === 'ready') skeleton.current.done();
195
+ if (status === 'failed') skeleton.current.remove();
196
+ }, [status]);
197
+ return h('span', { ref: anchor, hidden: true });
198
+ }
199
+
200
+ // ---- the window: window.js draws it; React renders the panel's content
201
+
202
+ const NAME = 'Incorta Intelligence';
203
+ /** The panel React renders; window.js places it (React never styles it again). */
204
+ const PANEL = { display: 'none' };
205
+
206
+ /**
207
+ * The window (window.js) around a panel this renders, re-rendering when it
208
+ * changes. `host` holds the panel and the launcher; until the window exists
209
+ * (the first effect) the panel is opened as `defaultMode` says, so a page
210
+ * rendered on a server already holds its chat's frame (loaded once connected).
211
+ */
212
+ function useChatWindow({ modes, defaultMode, theme }) {
213
+ const host = useRef(null);
214
+ const panel = useRef(null);
215
+ const [win, setWin] = useState(null);
216
+ const [, changed] = useState(0);
217
+ const [openedAtFirst] = useState(() => initialView(modes, defaultMode) !== 'minimized');
218
+ useEffect(() => {
219
+ const created = createChatWindow({
220
+ into: host.current,
221
+ panel: panel.current,
222
+ modes,
223
+ defaultMode,
224
+ theme,
225
+ });
226
+ const unsubscribe = created.subscribe(() => changed((count) => count + 1));
227
+ setWin(created);
228
+ return () => {
229
+ unsubscribe();
230
+ created.destroy();
231
+ };
232
+ }, []);
233
+ useEffect(() => win?.setTheme(theme), [win, theme]);
234
+ return { host, panel, win, opened: win ? win.opened : openedAtFirst };
235
+ }
236
+
237
+ // ---- direct, in the window: the app gives `modes` or `defaultMode` instead of a `window`
238
+
239
+ function WindowedChat({ modes, defaultMode, onReady, ...props }) {
240
+ const theme = props.theme ?? props.environment?.get().theme;
241
+ const { host, panel, win, opened } = useChatWindow({ modes, defaultMode, theme });
242
+ return h(
243
+ 'div',
244
+ { ref: host },
245
+ h(
246
+ 'div',
247
+ { ref: panel, style: PANEL },
248
+ opened &&
249
+ win &&
250
+ h(DirectChat, {
251
+ ...props,
252
+ window: {
253
+ ...win.state(),
254
+ setMode: win.setMode,
255
+ setDocked: win.setDocked,
256
+ close: win.close,
257
+ },
258
+ onReady: (chat) => {
259
+ win.setMounted(Boolean(chat));
260
+ onReady?.(chat);
261
+ },
262
+ }),
263
+ ),
264
+ );
265
+ }
266
+
267
+ // ---- embedded: the chat in an Incorta-served iframe, in the window
268
+
269
+ function EmbeddedChat({ embedUrl, modes, defaultMode, theme = 'light', locale, tenant }) {
270
+ const { host, panel, win, opened } = useChatWindow({ modes, defaultMode, theme });
271
+ const frame = useRef(null);
272
+ const embedded = useRef(null);
273
+ // Set once: a new src would reload the chat. Later theme changes go by message.
274
+ const [src] = useState(() => embedSrc(embedUrl, { theme, locale, tenant }));
275
+ useEffect(() => {
276
+ if (!win || !opened) return undefined;
277
+ const connected = connectEmbeddedChat(win, frame.current, { embedUrl, theme, locale });
278
+ // Only now: a page loaded before this listened (a frame a server rendered with its src)
279
+ // would say `loaded` to nobody, and its contract version would never be checked.
280
+ if (!frame.current.getAttribute('src')) frame.current.src = src;
281
+ embedded.current = connected;
282
+ return () => {
283
+ connected.destroy();
284
+ embedded.current = null;
285
+ };
286
+ }, [win, opened, embedUrl]);
287
+ useEffect(() => embedded.current?.setTheme(theme), [theme]);
288
+ useEffect(() => embedded.current?.setLocale(locale), [locale]);
289
+
290
+ return h(
291
+ 'div',
292
+ { ref: host },
293
+ h(
294
+ 'div',
295
+ { ref: panel, style: PANEL },
296
+ opened &&
297
+ h('iframe', {
298
+ ref: frame,
299
+ title: NAME,
300
+ allow: 'storage-access; microphone; clipboard-write',
301
+ style: { display: 'block', width: '100%', height: '100%', border: 0 },
302
+ }),
303
+ ),
304
+ );
305
+ }
306
+
307
+ export function IncortaChat(props) {
308
+ if (props.embedUrl) return h(EmbeddedChat, props);
309
+ // Direct: the app's own `window` (or none) keeps the chat in its box.
310
+ const windowed = !props.window && (props.modes !== undefined || props.defaultMode !== undefined);
311
+ return h(windowed ? WindowedChat : DirectChat, props);
312
+ }