@ahmedramez-org/chat 0.0.0-stage → 0.6.0-beta.2

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/window.js ADDED
@@ -0,0 +1,515 @@
1
+ // The chat's window, without a framework: a launcher icon that opens a panel
2
+ // floating, docked at the page's end edge (the page makes room; left in RTL) or full screen, and the
3
+ // embedded chat's side of the iframe protocol. <IncortaChat> (react.js) and the
4
+ // one-line script (widget.js) both draw the window with this, so they behave
5
+ // the same.
6
+ import { CONTRACT_VERSION, ICON, PALETTE, reducedMotion, showChatSkeleton } from './index.js';
7
+
8
+ export const MODES = ['floating', 'docked', 'fullscreen'];
9
+ const PANEL_WIDTH = 400;
10
+ /** The floating window opens out of the launcher, end edges aligned, 12px above it. */
11
+ const FLOATING = { width: 380, height: 620, edge: 24, launcher: 52, gap: 12 };
12
+ /** Below this width a floating or docked chat would crush the app, so it covers it. */
13
+ const NARROW_VIEWPORT = 768;
14
+ /** If the page never says it is ready (an Incorta login page instead), stop the skeleton. */
15
+ const READY_FALLBACK_MS = 5_000;
16
+ /** The page says it runs before its frame loads; silent this long after, Incorta refused to frame it. */
17
+ const BLOCKED_AFTER_MS = 3_000;
18
+ /** For a browser that fires no load on a refused frame: the notice after this long regardless. */
19
+ const BLOCKED_WITHOUT_LOAD_MS = 15_000;
20
+ /** At most this often, the app tells the chat the user is working (the chat paces its session reads). */
21
+ const KEEP_ALIVE_MS = 10_000;
22
+ const NAME = 'Incorta Intelligence';
23
+
24
+ /** The floating window and its launcher lift off the page; the launcher is a surface of its own. */
25
+ const LIFT = {
26
+ light: '0 20px 50px rgba(20,20,30,.14), 0 2px 6px rgba(20,20,30,.06)',
27
+ dark: '0 24px 60px rgba(0,0,0,.55)',
28
+ };
29
+ const LAUNCHER = {
30
+ light: { background: '#ffffff', border: '#e4e4e7', icon: '#3f3f46' },
31
+ dark: { background: '#1f1f21', border: '#323235', icon: '#e6e6e9' },
32
+ };
33
+ /** The blocked notice's inks: embed.html's sign-in panels' title and text. */
34
+ const NOTICE_INK = {
35
+ light: { title: '#1c1e2b', text: '#4b5066' },
36
+ dark: { title: '#eef1f2', text: '#b9c2c5' },
37
+ };
38
+ const { edge, launcher: LAUNCHER_SIZE, gap } = FLOATING;
39
+ /** Every placement property any mode sets, cleared before the next mode's. */
40
+ const PLACED = [
41
+ 'top',
42
+ 'insetInlineEnd',
43
+ 'bottom',
44
+ 'insetInlineStart',
45
+ 'inset',
46
+ 'width',
47
+ 'height',
48
+ 'border',
49
+ 'borderInlineStart',
50
+ 'borderRadius',
51
+ 'boxShadow',
52
+ 'transformOrigin',
53
+ ];
54
+
55
+ const isNarrow = () => typeof window !== 'undefined' && window.innerWidth < NARROW_VIEWPORT;
56
+ /** Placement follows the page's `dir`: logical properties, plus this for what has none. */
57
+ const isRtl = () =>
58
+ typeof document !== 'undefined' && getComputedStyle(document.documentElement).direction === 'rtl';
59
+ const tone = (theme) => (theme === 'dark' ? 'dark' : 'light');
60
+
61
+ function placement(mode, theme) {
62
+ const palette = PALETTE[tone(theme)];
63
+ if (mode === 'docked') {
64
+ // Flush against the page's end edge (right, or left in RTL), full height: only a hairline between them.
65
+ return {
66
+ top: '0',
67
+ insetInlineEnd: '0',
68
+ bottom: '0',
69
+ width: `${PANEL_WIDTH}px`,
70
+ borderInlineStart: `1px solid ${palette.line}`,
71
+ };
72
+ }
73
+ if (mode === 'fullscreen') return { inset: '0' };
74
+ // A card lifted off the page, opening out of the launcher below it.
75
+ return {
76
+ insetInlineEnd: `${edge}px`,
77
+ bottom: `${edge + LAUNCHER_SIZE + gap}px`,
78
+ width: `min(${FLOATING.width}px, calc(100vw - ${2 * edge}px))`,
79
+ height: `min(${FLOATING.height}px, calc(100vh - ${2 * edge + LAUNCHER_SIZE + gap}px))`,
80
+ border: `1px solid ${palette.line}`,
81
+ borderRadius: '16px',
82
+ boxShadow: LIFT[tone(theme)],
83
+ transformOrigin: `bottom ${isRtl() ? 'left' : 'right'}`,
84
+ };
85
+ }
86
+
87
+ /** The window a page first shows: `defaultMode` when it is allowed, else only the launcher. */
88
+ export function initialView(modes = MODES, defaultMode) {
89
+ return modes.includes(defaultMode) ? defaultMode : 'minimized';
90
+ }
91
+
92
+ /**
93
+ * embed.html with the app's theme, locale and Incorta tenant (where its sign-in opens); the
94
+ * app's URL is kept as given (relative ones resolve like any iframe src).
95
+ */
96
+ export function embedSrc(embedUrl, { theme = 'light', locale, tenant } = {}) {
97
+ const query = new URLSearchParams({
98
+ theme,
99
+ ...(locale ? { locale } : {}),
100
+ ...(tenant ? { tenant } : {}),
101
+ });
102
+ const at = embedUrl.includes('#') ? embedUrl.indexOf('#') : embedUrl.length;
103
+ const path = embedUrl.slice(0, at);
104
+ return `${path}${path.includes('?') ? '&' : '?'}${query}${embedUrl.slice(at)}`;
105
+ }
106
+
107
+ /**
108
+ * Draws the window around `panel` (created in `into` when not given) and puts
109
+ * the launcher in `into`. The panel's content is the caller's; until the chat
110
+ * says it is mounted and draws its own controls, the panel keeps a close of
111
+ * its own. Its state and setters are the contract's `ChatWindow` terms:
112
+ * the embedded chat gets them by message, the direct one as its `window`.
113
+ */
114
+ export function createChatWindow({ into, panel, modes = MODES, defaultMode, theme = 'light' }) {
115
+ const allowed = modes.filter((mode) => MODES.includes(mode));
116
+ const canFullscreen = allowed.includes('fullscreen');
117
+ let view = initialView(allowed, defaultMode);
118
+ // Opened once, kept while minimized, so the conversation stays.
119
+ let opened = view !== 'minimized';
120
+ // The launcher reopens the window last shown (the first listed, before any).
121
+ let last = view === 'minimized' ? allowed[0] : view;
122
+ // Where "dock" goes back to from full screen: the window last shown beside the page.
123
+ let side =
124
+ view === 'floating' || view === 'docked' ? view : allowed.find((mode) => mode !== 'fullscreen');
125
+ let narrow = isNarrow();
126
+ let mounted = false;
127
+ let shownBefore;
128
+ let paddedFrom; // the page's own padding while docked
129
+ let destroyed = false;
130
+ const listeners = new Set();
131
+
132
+ const ownPanel = !panel;
133
+ panel ??= into.appendChild(document.createElement('div'));
134
+ panel.setAttribute('role', 'complementary');
135
+ panel.setAttribute('aria-label', NAME);
136
+ Object.assign(panel.style, {
137
+ position: 'fixed',
138
+ zIndex: '50',
139
+ boxSizing: 'border-box',
140
+ overflow: 'hidden',
141
+ });
142
+
143
+ const close = document.createElement('button');
144
+ close.type = 'button';
145
+ close.setAttribute('aria-label', `Close ${NAME}`);
146
+ close.title = 'Close';
147
+ close.textContent = '×';
148
+ close.style.cssText =
149
+ 'position:absolute;top:12px;inset-inline-end:14px;z-index:1;width:36px;height:36px;border:0;border-radius:8px;background:transparent;color:inherit;font:20px/1 system-ui,sans-serif;cursor:pointer';
150
+ close.onclick = () => show('minimized');
151
+
152
+ const button = document.createElement('button');
153
+ button.type = 'button';
154
+ button.style.cssText = `position:fixed;inset-inline-end:${edge}px;bottom:${edge}px;z-index:50;box-sizing:border-box;width:${LAUNCHER_SIZE}px;height:${LAUNCHER_SIZE}px;padding:0;border-radius:50%;place-items:center;cursor:pointer`;
155
+ button.onclick = () =>
156
+ show(view === 'floating' && !narrow ? 'minimized' : (last ?? 'fullscreen'));
157
+ into.appendChild(button);
158
+
159
+ const shown = () => (view === 'minimized' ? undefined : narrow ? 'fullscreen' : view);
160
+ const state = () => ({
161
+ // An older chat reads "docked" as beside the page (floating or docked), the opposite of
162
+ // full screen; undocking goes to full screen, so it is offered only where the app allows it.
163
+ docked: shown() !== 'fullscreen',
164
+ canDock: !narrow && side !== undefined && canFullscreen,
165
+ mode: shown() ?? 'floating',
166
+ // None while the viewport is too narrow for anything but full screen.
167
+ modes: narrow ? [] : allowed,
168
+ // Minimized keeps the chat mounted; it still has to know it is out of sight.
169
+ ...(opened && shown() ? {} : { hidden: true }),
170
+ });
171
+
172
+ function draw() {
173
+ if (destroyed) return;
174
+ const now = shown();
175
+ const look = tone(theme);
176
+ // The panel
177
+ panel.style.display = opened && now ? 'block' : 'none';
178
+ panel.style.background = PALETTE[look].ground;
179
+ for (const key of PLACED) panel.style[key] = '';
180
+ Object.assign(panel.style, placement(now ?? 'floating', theme));
181
+ if (now === 'floating' && shownBefore !== 'floating' && !reducedMotion()) {
182
+ panel.animate?.(
183
+ [
184
+ { opacity: 0, transform: 'scale(0.96)' },
185
+ { opacity: 1, transform: 'scale(1)' },
186
+ ],
187
+ { duration: 180, easing: 'ease-out' },
188
+ );
189
+ }
190
+ if (mounted) close.remove();
191
+ else if (opened && close.parentNode !== panel) panel.appendChild(close);
192
+ // A docked panel takes its width from the page instead of covering it.
193
+ const root = document.documentElement;
194
+ if (now === 'docked' && paddedFrom === undefined) {
195
+ paddedFrom = root.style.paddingInlineEnd;
196
+ root.style.paddingInlineEnd = `${PANEL_WIDTH}px`;
197
+ } else if (now !== 'docked' && paddedFrom !== undefined) {
198
+ root.style.paddingInlineEnd = paddedFrom;
199
+ paddedFrom = undefined;
200
+ }
201
+ shownBefore = now;
202
+ // The launcher: shown while minimized, and under the floating window as its toggle.
203
+ const floatingOpen = now === 'floating';
204
+ const launcherShown = view === 'minimized' || floatingOpen;
205
+ button.hidden = !launcherShown;
206
+ // The attribute alone loses to an inline display: say it in the style too.
207
+ button.style.display = launcherShown ? 'grid' : 'none';
208
+ button.setAttribute('aria-label', `${floatingOpen ? 'Hide' : 'Open'} ${NAME}`);
209
+ button.setAttribute('aria-expanded', String(floatingOpen));
210
+ button.title = floatingOpen ? 'Hide chat' : NAME;
211
+ button.style.border = `1px solid ${LAUNCHER[look].border}`;
212
+ button.style.background = LAUNCHER[look].background;
213
+ button.style.boxShadow = LIFT[look];
214
+ const face = floatingOpen ? 'hide' : 'open';
215
+ if (button.dataset.face !== face) {
216
+ button.dataset.face = face;
217
+ button.innerHTML =
218
+ face === 'hide'
219
+ ? `<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="${LAUNCHER[look].icon}" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M6 9l6 6 6-6"/></svg>`
220
+ : '<img alt="" width="26" height="28">';
221
+ button.querySelector('img')?.setAttribute('src', ICON);
222
+ } else button.querySelector('svg')?.setAttribute('stroke', LAUNCHER[look].icon);
223
+ }
224
+
225
+ const changed = () => {
226
+ if (destroyed) return;
227
+ draw();
228
+ listeners.forEach((onChange) => onChange());
229
+ };
230
+ function show(next) {
231
+ view = next;
232
+ if (next === 'floating' || next === 'docked') side = next;
233
+ if (next !== 'minimized') {
234
+ opened = true;
235
+ last = next;
236
+ }
237
+ changed();
238
+ }
239
+ const onResize = () => {
240
+ if (narrow === isNarrow()) return;
241
+ narrow = !narrow;
242
+ changed();
243
+ };
244
+ window.addEventListener('resize', onResize);
245
+ draw();
246
+
247
+ return {
248
+ panel,
249
+ get opened() {
250
+ return opened;
251
+ },
252
+ get view() {
253
+ return view;
254
+ },
255
+ state,
256
+ subscribe(onChange) {
257
+ listeners.add(onChange);
258
+ return () => listeners.delete(onChange);
259
+ },
260
+ open: () => show(last ?? 'fullscreen'),
261
+ setMode: (mode) => allowed.includes(mode) && show(mode),
262
+ setDocked: (docked) => (docked || canFullscreen) && show(docked ? side : 'fullscreen'),
263
+ close: () => show('minimized'),
264
+ setTheme(next) {
265
+ theme = next;
266
+ draw();
267
+ },
268
+ /** The chat is up and draws its own controls (false again when its session ends). */
269
+ setMounted(next) {
270
+ if (mounted === next) return;
271
+ mounted = next;
272
+ draw();
273
+ },
274
+ destroy() {
275
+ destroyed = true;
276
+ window.removeEventListener('resize', onResize);
277
+ if (paddedFrom !== undefined) document.documentElement.style.paddingInlineEnd = paddedFrom;
278
+ paddedFrom = undefined;
279
+ button.remove();
280
+ close.remove();
281
+ if (ownPanel) panel.remove();
282
+ listeners.clear();
283
+ },
284
+ };
285
+ }
286
+
287
+ /**
288
+ * Incorta does not let the site frame embed.html (its Chat UI Embedding allowed domains, or
289
+ * iframe inclusion off). A check, not a verdict: an Incorta that is down looks the same from here.
290
+ */
291
+ function blockedNotice() {
292
+ // The document's origin: "null" when opaque (a sandboxed or file: page), whatever its URL.
293
+ const site = window.origin === 'null' ? 'this site' : window.origin;
294
+ return {
295
+ title: "Incorta chat can't open on this site",
296
+ text: `Ask your Incorta admin to make sure ${site} is in the allowed domains for chat embedding.`,
297
+ };
298
+ }
299
+
300
+ /** The page answered `loaded` with another contract version than this file's. */
301
+ const UPDATE_NOTICE = {
302
+ title: 'Incorta chat needs an update',
303
+ text: "This site's chat doesn't match your Incorta's. Ask the site's owner to update it.",
304
+ };
305
+
306
+ /**
307
+ * Says over `panel` why the chat cannot open: `blockedNotice` (Incorta does not let the site
308
+ * frame embed.html) or `UPDATE_NOTICE` (the page speaks another contract version).
309
+ */
310
+ function showNotice(panel, theme, { title: heading, text: detail }) {
311
+ const notice = document.createElement('div');
312
+ notice.setAttribute('role', 'alert');
313
+ // No z-index: the panel's own close stays above it.
314
+ notice.style.cssText =
315
+ 'position:absolute;inset:0;box-sizing:border-box;display:flex;flex-direction:column;align-items:center;justify-content:center;gap:10px;padding:24px 36px;text-align:center;font-family:Roboto,ui-sans-serif,system-ui,sans-serif';
316
+ const mark = document.createElement('img');
317
+ mark.alt = '';
318
+ mark.width = 32;
319
+ mark.height = 34;
320
+ mark.src = ICON;
321
+ mark.style.marginBottom = '14px';
322
+ const title = document.createElement('h2');
323
+ title.textContent = heading;
324
+ title.style.cssText = 'margin:0;font-size:20px;font-weight:700;line-height:1.25';
325
+ const text = document.createElement('p');
326
+ // As text, never markup.
327
+ text.textContent = detail;
328
+ text.style.cssText =
329
+ 'max-width:26rem;margin:0;font-size:15px;line-height:1.55;overflow-wrap:anywhere';
330
+ notice.append(mark, title, text);
331
+ const setTheme = (next) => {
332
+ const look = tone(next);
333
+ notice.style.background = PALETTE[look].ground;
334
+ title.style.color = NOTICE_INK[look].title;
335
+ text.style.color = NOTICE_INK[look].text;
336
+ };
337
+ setTheme(theme);
338
+ panel.append(notice);
339
+ return { setTheme, remove: () => notice.remove() };
340
+ }
341
+
342
+ /**
343
+ * The app's side of the embedded chat's protocol, over `iframe` (embed.html)
344
+ * in `win`'s panel: a skeleton until the page inside says it is ready, the
345
+ * window's state and the theme sent in, the chat's mode, dock and close
346
+ * buttons applied, and "active" sent while the user works in the app, so
347
+ * Incorta's idle timeout does not end the chat's session. `explainBlocked`:
348
+ * when the page never runs in its frame, say the site may not be allowed
349
+ * (only where embed.html ships with this file: an older one says nothing
350
+ * until `ready`, which can come later than the notice).
351
+ */
352
+ export function connectEmbeddedChat(
353
+ win,
354
+ iframe,
355
+ { embedUrl, theme = 'light', locale, explainBlocked = false },
356
+ ) {
357
+ // From the chat page itself, not a sign-in page the frame navigated to.
358
+ const origin = new URL(embedUrl, location.href).origin;
359
+ const skeleton = showChatSkeleton(win.panel, theme);
360
+ let fallback;
361
+ let sent;
362
+ let spoke = false; // the page sent a message: it runs, so this site may frame it
363
+ let loadedOnce = false; // later loads are the page's own navigations (sign-in)
364
+ let notice;
365
+ let refused = false; // the page said `loaded` with another contract version
366
+ const post = (message) =>
367
+ iframe.contentWindow?.postMessage({ ...message, v: CONTRACT_VERSION }, origin);
368
+ const sendStyle = (force) => {
369
+ const message = { incortaChat: 'style', theme, locale, window: win.state() };
370
+ const key = JSON.stringify(message);
371
+ if (!force && key === sent) return;
372
+ sent = key;
373
+ post(message);
374
+ };
375
+ const onMessage = (event) => {
376
+ if (event.source !== iframe.contentWindow) return;
377
+ const { data } = event;
378
+ // The handshake: a page of another contract version is refused until it loads again.
379
+ if (event.origin === origin && data?.incortaChat === 'loaded') {
380
+ refused = data.v !== CONTRACT_VERSION;
381
+ if (refused) return showUpdate();
382
+ }
383
+ if (refused) return;
384
+ if (data?.incortaChat === 'ready') {
385
+ clearTimeout(fallback);
386
+ skeleton.done();
387
+ win.setMounted(data.mounted === true);
388
+ }
389
+ if (event.origin !== origin) return;
390
+ spoke = true;
391
+ clearTimeout(blocked);
392
+ if (notice) {
393
+ notice.remove();
394
+ notice = undefined;
395
+ iframe.style.visibility = '';
396
+ }
397
+ if (data?.incortaChat === 'mode') win.setMode(data.mode);
398
+ if (data?.incortaChat === 'dock') win.setDocked(data.docked);
399
+ if (data?.incortaChat === 'close') win.close();
400
+ };
401
+ const showBlocked = () => {
402
+ // Already up: a first load after the no-load fallback must not add a second.
403
+ if (notice) return;
404
+ clearTimeout(fallback);
405
+ skeleton.remove();
406
+ // The browser's own error page stays out of sight.
407
+ iframe.style.visibility = 'hidden';
408
+ notice = showNotice(win.panel, theme, blockedNotice());
409
+ };
410
+ const showUpdate = () => {
411
+ spoke = true; // it runs: not blocked
412
+ clearTimeout(fallback);
413
+ clearTimeout(blocked);
414
+ skeleton.remove();
415
+ iframe.style.visibility = 'hidden';
416
+ // A chat that was up is gone: the window's own Close comes back.
417
+ win.setMounted(false);
418
+ notice?.remove();
419
+ notice = showNotice(win.panel, theme, UPDATE_NOTICE);
420
+ };
421
+ let blocked = explainBlocked ? setTimeout(showBlocked, BLOCKED_WITHOUT_LOAD_MS) : undefined;
422
+ const onLoad = () => {
423
+ sendStyle(true);
424
+ clearTimeout(fallback);
425
+ fallback = setTimeout(() => skeleton.done(), READY_FALLBACK_MS);
426
+ if (explainBlocked && !spoke && !loadedOnce) {
427
+ clearTimeout(blocked);
428
+ blocked = setTimeout(showBlocked, BLOCKED_AFTER_MS);
429
+ }
430
+ loadedOnce = true;
431
+ };
432
+ let active = 0;
433
+ const onActivity = () => {
434
+ // A refused page is not kept signed in: nobody can use the chat behind the notice.
435
+ if (refused || Date.now() - active < KEEP_ALIVE_MS) return;
436
+ active = Date.now();
437
+ post({ incortaChat: 'active' });
438
+ };
439
+ const capture = { capture: true, passive: true };
440
+ window.addEventListener('message', onMessage);
441
+ window.addEventListener('pointerdown', onActivity, capture);
442
+ window.addEventListener('keydown', onActivity, capture);
443
+ iframe.addEventListener('load', onLoad);
444
+ const unsubscribe = win.subscribe(() => sendStyle());
445
+ sendStyle();
446
+
447
+ return {
448
+ setTheme(next) {
449
+ theme = next;
450
+ skeleton.setTheme(next);
451
+ notice?.setTheme(next);
452
+ sendStyle();
453
+ },
454
+ setLocale(next) {
455
+ locale = next;
456
+ sendStyle();
457
+ },
458
+ destroy() {
459
+ clearTimeout(fallback);
460
+ clearTimeout(blocked);
461
+ notice?.remove();
462
+ skeleton.remove();
463
+ unsubscribe();
464
+ window.removeEventListener('message', onMessage);
465
+ window.removeEventListener('pointerdown', onActivity, capture);
466
+ window.removeEventListener('keydown', onActivity, capture);
467
+ iframe.removeEventListener('load', onLoad);
468
+ },
469
+ };
470
+ }
471
+
472
+ /**
473
+ * The embedded chat with its window, all in plain DOM (the one-line script):
474
+ * the launcher and panel go in `into`, and the iframe is created on first open.
475
+ */
476
+ export function createEmbeddedChat({
477
+ into = document.body,
478
+ embedUrl,
479
+ modes,
480
+ defaultMode,
481
+ theme = 'light',
482
+ locale,
483
+ tenant,
484
+ }) {
485
+ const win = createChatWindow({ into, modes, defaultMode, theme });
486
+ let embedded;
487
+ const embed = () => {
488
+ if (embedded || !win.opened) return;
489
+ const iframe = document.createElement('iframe');
490
+ iframe.title = NAME;
491
+ iframe.allow = 'storage-access; microphone; clipboard-write';
492
+ iframe.src = embedSrc(embedUrl, { theme, locale, tenant });
493
+ iframe.style.cssText = 'display:block;width:100%;height:100%;border:0';
494
+ win.panel.prepend(iframe);
495
+ // widget.js and embed.html ship together, so the page always says `loaded`.
496
+ embedded = connectEmbeddedChat(win, iframe, { embedUrl, theme, locale, explainBlocked: true });
497
+ };
498
+ const unsubscribe = win.subscribe(embed);
499
+ embed();
500
+ return {
501
+ open: win.open,
502
+ close: win.close,
503
+ setMode: win.setMode,
504
+ setTheme(next) {
505
+ theme = next;
506
+ win.setTheme(next);
507
+ embedded?.setTheme(next);
508
+ },
509
+ destroy() {
510
+ unsubscribe();
511
+ embedded?.destroy();
512
+ win.destroy();
513
+ },
514
+ };
515
+ }