@xapp/chat-widget 1.103.0 → 1.104.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/dist/index.js CHANGED
@@ -3,6 +3,7 @@
3
3
  var React = require('react');
4
4
  var require$$0 = require('react/jsx-runtime');
5
5
  var reactRedux = require('react-redux');
6
+ var reactDom = require('react-dom');
6
7
 
7
8
  var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
8
9
 
@@ -328,7 +329,7 @@ function buildChatWidgetChannel(props) {
328
329
  // and the text on it are always a matched pair rather than one scraped
329
330
  // value and one guess.
330
331
  const primaryColor = (0, color_1.usableColorOr)(props.primaryColor, DEFAULT_PRIMARY);
331
- return Object.assign({ type: "chat-widget",
332
+ return Object.assign(Object.assign({ type: "chat-widget",
332
333
  // MCP by default. The widget runs on a public page, so homeowner mode
333
334
  // — which is unauthenticated and carries the appId in the url — is the
334
335
  // only one that can work there; business_owner needs a token, and a
@@ -339,7 +340,7 @@ function buildChatWidgetChannel(props) {
339
340
  mcp: {
340
341
  mode: "homeowner"
341
342
  }
342
- }, theme: buildChatTheme(primaryColor, props.secondaryColor), actionBar: buildActionBar({ apiUrl, formWidgetKey, phoneNumber }) }, (businessName ? { botName: businessName } : {}));
343
+ }, theme: buildChatTheme(primaryColor, props.secondaryColor), actionBar: buildActionBar({ apiUrl, formWidgetKey, phoneNumber }) }, (formWidgetKey ? { formWidgetKey } : {})), (businessName ? { botName: businessName } : {}));
343
344
  }
344
345
  /**
345
346
  * The dock of buttons that replaces the plain chat bubble.
@@ -2399,6 +2400,16 @@ function stripChatContinueParam(win) {
2399
2400
  function hasConversation(chats) {
2400
2401
  return !!(chats === null || chats === void 0 ? void 0 : chats.some(function (chat) { return chat.type === "chat.msg"; }));
2401
2402
  }
2403
+ /**
2404
+ * True once the visitor has said something themselves.
2405
+ *
2406
+ * Stricter than `hasConversation`, which counts the greeting the assistant posts before anyone
2407
+ * has engaged. Visitor messages carry a `visitor:` nick, the same marker MessageList uses to
2408
+ * decide which side of the thread a message belongs on.
2409
+ */
2410
+ function hasVisitorMessage(chats) {
2411
+ return !!(chats === null || chats === void 0 ? void 0 : chats.some(function (chat) { var _a, _b; return chat.type === "chat.msg" && !!((_b = (_a = chat.user) === null || _a === void 0 ? void 0 : _a.nick) === null || _b === void 0 ? void 0 : _b.startsWith("visitor:")); }));
2412
+ }
2402
2413
  /**
2403
2414
  * The CTA to show, given whether there is a conversation to go back to.
2404
2415
  *
@@ -37100,6 +37111,22 @@ var StaticMessagesChatWidgetContainer = function (props) {
37100
37111
  * After this delay of inactivity, the "stop typing" event will be sent.
37101
37112
  */
37102
37113
  var TYPING_INDICATOR_DEBOUNCE_MS = 2000;
37114
+ /**
37115
+ * Reparenting has to happen before the browser paints, or the chat is missing for a frame on
37116
+ * every crossing. useLayoutEffect warns when a component is rendered on a server, where there is
37117
+ * nothing to paint and nothing to move, so fall back there.
37118
+ */
37119
+ var useBeforePaintEffect = typeof window === "undefined" ? React.useEffect : React.useLayoutEffect;
37120
+ /**
37121
+ * Narrowest viewport a pop-out is allowed on by default. Below this a floating window covers
37122
+ * most of the screen, which is worse than letting the chat scroll away with the page.
37123
+ */
37124
+ var DEFAULT_POP_OUT_MIN_WIDTH = 640;
37125
+ /**
37126
+ * How long to keep correcting the message list's scroll after the chat moves. Text rewraps at
37127
+ * the new width, so the content height settles over a frame or two rather than immediately.
37128
+ */
37129
+ var SCROLL_SETTLE_MS = 250;
37103
37130
  /**
37104
37131
  * Check if we're in development mode. Uses typeof to prevent TypeScript
37105
37132
  * errors after Rollup replaces "production" with a literal string.
@@ -37266,12 +37293,25 @@ var ChatWidgetConnected = function (props) {
37266
37293
  }
37267
37294
  return (require$$0.jsx(ChatConfigContext.Provider, { value: config, children: require$$0.jsx(ChatServerContext.Provider, { value: chatServer, children: require$$0.jsx(ChatWidgetUI, __assign$1({}, props, { config: rawConfig })) }) }));
37268
37295
  };
37296
+ var HOST_FORM_WIDGET_CHECK_MS = 500;
37297
+ /** About 15s: long enough for a slow host script, short enough not to poll forever. */
37298
+ var HOST_FORM_WIDGET_MAX_CHECKS = 30;
37299
+ /** The form widget key a Form/Book button carries on its own formConfig, if any. */
37300
+ function formButtonKey(button) {
37301
+ var _a, _b;
37302
+ return opensFormWidget(button)
37303
+ ? ((_b = (_a = button.formConfig) === null || _a === void 0 ? void 0 : _a.api) === null || _b === void 0 ? void 0 : _b.key) || undefined
37304
+ : undefined;
37305
+ }
37306
+ function isHostFormWidgetOnPage() {
37307
+ return isFormWidgetScriptLoaded() || isFormWidgetReady();
37308
+ }
37269
37309
  /**
37270
37310
  * Inner ChatWidget component that renders the actual UI.
37271
37311
  * Exported for use by StaticChatWidgetContainer to avoid infinite loops.
37272
37312
  */
37273
37313
  var ChatWidgetUI = function (props) {
37274
- var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x, _y, _z, _0, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14;
37314
+ var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x, _y, _z, _0, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14, _15, _16, _17, _18, _19, _20, _21, _22, _23;
37275
37315
  var innerDispatch = useChatDispatch();
37276
37316
  var dispatch = useChatServerDispatch();
37277
37317
  // Publish the visual viewport's geometry so the panel can size around the soft keyboard.
@@ -37296,23 +37336,176 @@ var ChatWidgetUI = function (props) {
37296
37336
  var arrivedViaChatLink = useArrivedViaChatLink(previewMode);
37297
37337
  var conversationOnScreen = hasConversation(chatState.chats);
37298
37338
  var chatButtonCta = React.useMemo(function () { var _a; return resolveCta((_a = props.config) === null || _a === void 0 ? void 0 : _a.cta, { hasConversation: conversationOnScreen, arrivedViaChatLink: arrivedViaChatLink }); }, [(_b = props.config) === null || _b === void 0 ? void 0 : _b.cta, conversationOnScreen, arrivedViaChatLink]);
37339
+ // Pop-out: an embedded chat follows the visitor down the page rather than scrolling away
37340
+ // mid-conversation. Same component, same store - it is moved, not reopened - so the
37341
+ // conversation continues instead of restarting in a second widget.
37342
+ var popOutEnabled = dockedMode && ((_c = props.config.popOut) === null || _c === void 0 ? void 0 : _c.enabled) === true;
37343
+ var popOutMinWidth = (_e = (_d = props.config.popOut) === null || _d === void 0 ? void 0 : _d.minWidth) !== null && _e !== void 0 ? _e : DEFAULT_POP_OUT_MIN_WIDTH;
37344
+ var anchorRef = React.useRef(null);
37345
+ var _24 = React.useState(false), anchorOffScreen = _24[0], setAnchorOffScreen = _24[1];
37346
+ // A returning visitor's chat often sits below the fold at load. Following them before they
37347
+ // have even reached it would put a floating window in front of someone who never scrolled
37348
+ // past anything, so the chat has to have been on screen once first.
37349
+ var _25 = React.useState(false), anchorSeen = _25[0], setAnchorSeen = _25[1];
37350
+ // Set when the visitor puts the floating window away: it stays put until their own
37351
+ // scrolling brings the chat's place on the page back into view.
37352
+ var _26 = React.useState(false), popOutDismissed = _26[0], setPopOutDismissed = _26[1];
37353
+ // On a phone the chat offers its entry point rather than covering the page; this is set when
37354
+ // the visitor taps that and asks for the conversation.
37355
+ var _27 = React.useState(false), mobileOpened = _27[0], setMobileOpened = _27[1];
37356
+ // Tracked rather than read at render: a visitor who narrows the window or rotates a tablet
37357
+ // while the chat is popped out would otherwise keep a floating window over most of a phone
37358
+ // screen until some unrelated re-render happened along.
37359
+ var _28 = React.useState(typeof window === "undefined" ? 0 : window.innerWidth), viewportWidth = _28[0], setViewportWidth = _28[1];
37360
+ React.useEffect(function () {
37361
+ if (!popOutEnabled || typeof window === "undefined") {
37362
+ return undefined;
37363
+ }
37364
+ var handleResize = function () { return setViewportWidth(window.innerWidth); };
37365
+ handleResize();
37366
+ window.addEventListener("resize", handleResize);
37367
+ return function () { return window.removeEventListener("resize", handleResize); };
37368
+ }, [popOutEnabled]);
37369
+ React.useEffect(function () {
37370
+ if (!popOutEnabled || typeof IntersectionObserver === "undefined" || !anchorRef.current) {
37371
+ return undefined;
37372
+ }
37373
+ var observer = new IntersectionObserver(function (entries) {
37374
+ var entry = entries[entries.length - 1];
37375
+ if (!entry) {
37376
+ return;
37377
+ }
37378
+ setAnchorOffScreen(!entry.isIntersecting);
37379
+ if (entry.isIntersecting) {
37380
+ setAnchorSeen(true);
37381
+ setPopOutDismissed(false);
37382
+ // Back at the chat itself, so the phone entry point starts over.
37383
+ setMobileOpened(false);
37384
+ }
37385
+ });
37386
+ observer.observe(anchorRef.current);
37387
+ return function () { return observer.disconnect(); };
37388
+ }, [popOutEnabled]);
37389
+ // With `after: "message"` the chat only follows a visitor who has engaged - the assistant's
37390
+ // greeting arrives before anyone types, so it does not count. A floating window also covers
37391
+ // most of a phone screen, so narrow screens stay on the page either way.
37392
+ var engaged = ((_f = props.config.popOut) === null || _f === void 0 ? void 0 : _f.after) !== "message" || hasVisitorMessage(chatState.chats);
37393
+ var following = popOutEnabled && anchorSeen && anchorOffScreen && !popOutDismissed && engaged;
37394
+ var wideEnough = viewportWidth >= popOutMinWidth;
37395
+ var mobileEntry = (_h = (_g = props.config.popOut) === null || _g === void 0 ? void 0 : _g.mobile) !== null && _h !== void 0 ? _h : "auto";
37396
+ /**
37397
+ * Too narrow for a floating window: the chat stays put and offers its entry point instead,
37398
+ * so a visitor reading on still has a way back to the conversation.
37399
+ */
37400
+ var collapsedOnMobile = following && !wideEnough && mobileEntry !== "none" && !mobileOpened;
37401
+ var poppedOut = following && (wideEnough || mobileOpened);
37402
+ function handlePopOutDismiss() {
37403
+ // On a phone, putting the window away goes back to the entry point rather than leaving
37404
+ // the visitor with nothing: the conversation is still off-screen up the page.
37405
+ if (wideEnough) {
37406
+ setPopOutDismissed(true);
37407
+ return;
37408
+ }
37409
+ setMobileOpened(false);
37410
+ }
37411
+ function handleMobileOpen() {
37412
+ setMobileOpened(true);
37413
+ }
37414
+ // The chat always renders into this one node, and the node is what moves between the page
37415
+ // and the corner. Swapping the JSX between an element and a portal instead would hand React
37416
+ // a different fiber type in the same slot, remounting the whole chat - and with it the
37417
+ // visitor's half-typed message and the message list's scroll position - on every crossing.
37418
+ var popOutHost = React.useMemo(function () { return (popOutEnabled && typeof document !== "undefined" ? document.createElement("div") : null); }, [popOutEnabled]);
37419
+ // Where the visitor is reading, recorded as they scroll. Measuring this at move time does
37420
+ // not work: React has already applied the new size by then, so the height is the new one
37421
+ // while the scroll position is still the old one, and the mix is meaningless.
37422
+ var readingRef = React.useRef({ fromBottom: 0, latest: true });
37423
+ React.useEffect(function () {
37424
+ if (!popOutHost) {
37425
+ return undefined;
37426
+ }
37427
+ var onScroll = function (event) {
37428
+ var el = event.target;
37429
+ if (!(el instanceof HTMLElement) || !el.classList.contains("message-list-container")) {
37430
+ return;
37431
+ }
37432
+ var fromBottom = el.scrollHeight - el.clientHeight - el.scrollTop;
37433
+ readingRef.current = {
37434
+ fromBottom: fromBottom,
37435
+ // Within a screenful of the newest message is "following the conversation", and
37436
+ // that is where they go back to. The list also smooth-scrolls after each
37437
+ // message, so the last position it reports can be mid-animation.
37438
+ latest: fromBottom <= el.clientHeight,
37439
+ };
37440
+ };
37441
+ // Scroll events do not bubble, but they do capture.
37442
+ popOutHost.addEventListener("scroll", onScroll, true);
37443
+ return function () { return popOutHost.removeEventListener("scroll", onScroll, true); };
37444
+ }, [popOutHost]);
37445
+ useBeforePaintEffect(function () {
37446
+ if (!popOutHost) {
37447
+ return undefined;
37448
+ }
37449
+ popOutHost.className = "widget-portal";
37450
+ var target = poppedOut ? document.body : anchorRef.current;
37451
+ if (target && popOutHost.parentElement !== target) {
37452
+ // Moving a node blurs whatever was focused inside it, which would drop the visitor
37453
+ // out of the message box mid-sentence, so put the caret back afterwards.
37454
+ var focused = document.activeElement;
37455
+ var refocus = focused instanceof HTMLElement && popOutHost.contains(focused) ? focused : undefined;
37456
+ // The embedded chat and the floating window are different heights, so a scroll
37457
+ // position kept in pixels lands somewhere else in the thread - usually leaving the
37458
+ // newest message below the fold, which reads as the conversation having been lost.
37459
+ // Distance from the bottom is what the visitor actually chose: at the newest message
37460
+ // they stay there, and reading back stays that far back.
37461
+ var messages_1 = popOutHost.querySelector(".message-list-container");
37462
+ // appendChild moves the node, children and all, without React re-rendering them.
37463
+ target.appendChild(popOutHost);
37464
+ // Read afresh each time rather than closing over the position from before the move:
37465
+ // the delayed corrections below run up to a quarter of a second later, and a visitor
37466
+ // who scrolls back through the thread in that window must not be snapped forward
37467
+ // again. Their scrolling updates the ref, so the later passes simply hold their place.
37468
+ var restoreScroll = function () {
37469
+ if (!messages_1) {
37470
+ return;
37471
+ }
37472
+ var _a = readingRef.current, fromBottom = _a.fromBottom, latest = _a.latest;
37473
+ var bottom = messages_1.scrollHeight - messages_1.clientHeight;
37474
+ messages_1.scrollTop = latest ? bottom : Math.max(0, bottom - fromBottom);
37475
+ };
37476
+ restoreScroll();
37477
+ refocus === null || refocus === void 0 ? void 0 : refocus.focus({ preventScroll: true });
37478
+ // The thread rewraps at the new width, so the content keeps growing for a frame or
37479
+ // two after the move. Restoring only once leaves the newest message under the fold,
37480
+ // which is what a visitor reads as "my conversation is gone".
37481
+ var frame_1 = requestAnimationFrame(restoreScroll);
37482
+ var settled_1 = window.setTimeout(restoreScroll, SCROLL_SETTLE_MS);
37483
+ return function () {
37484
+ cancelAnimationFrame(frame_1);
37485
+ window.clearTimeout(settled_1);
37486
+ };
37487
+ }
37488
+ return undefined;
37489
+ }, [popOutHost, poppedOut]);
37490
+ React.useEffect(function () { return function () { return popOutHost === null || popOutHost === void 0 ? void 0 : popOutHost.remove(); }; }, [popOutHost]);
37299
37491
  // Only an embedded widget may drop its header. In normal mode the header holds the
37300
37492
  // minimize and close buttons, so hiding it would leave a floating window with no way out.
37301
- var headerHidden = ((_c = props.config.header) === null || _c === void 0 ? void 0 : _c.hidden) === true && (dockedMode || staticMode);
37493
+ // While popped out the header is what lets the visitor put the window away, so it stays.
37494
+ var headerHidden = ((_j = props.config.header) === null || _j === void 0 ? void 0 : _j.hidden) === true && (dockedMode || staticMode) && !poppedOut;
37302
37495
  // The header is the only place a HEADER_LEFT / HEADER_RIGHT menu button renders. Without it
37303
37496
  // the menu would be unreachable, so hand the button to the footer instead.
37304
37497
  var menuConfig = React.useMemo(function () {
37305
37498
  return headerHidden && props.config.menu && props.config.menu.menuButtonLocation !== "FOOTER"
37306
37499
  ? __assign$1(__assign$1({}, props.config.menu), { menuButtonLocation: "FOOTER" }) : props.config.menu;
37307
37500
  }, [headerHidden, props.config.menu]);
37308
- var canRefresh = (_e = (_d = props.config.header) === null || _d === void 0 ? void 0 : _d.actions) === null || _e === void 0 ? void 0 : _e.refresh;
37501
+ var canRefresh = (_l = (_k = props.config.header) === null || _k === void 0 ? void 0 : _k.actions) === null || _l === void 0 ? void 0 : _l.refresh;
37309
37502
  // can't minimize in docked mode, static mode, or preview mode.
37310
- var canMinimize = !dockedMode && !staticMode && !previewMode && ((_g = (_f = props.config.header) === null || _f === void 0 ? void 0 : _f.actions) === null || _g === void 0 ? void 0 : _g.minimize);
37311
- log("docked: ".concat(dockedMode, " static: ").concat(staticMode, " preview: ").concat(previewMode, " minimized: ").concat((_j = (_h = props.config.header) === null || _h === void 0 ? void 0 : _h.actions) === null || _j === void 0 ? void 0 : _j.minimize));
37503
+ var canMinimize = !dockedMode && !staticMode && !previewMode && ((_o = (_m = props.config.header) === null || _m === void 0 ? void 0 : _m.actions) === null || _o === void 0 ? void 0 : _o.minimize);
37504
+ log("docked: ".concat(dockedMode, " static: ").concat(staticMode, " preview: ").concat(previewMode, " minimized: ").concat((_q = (_p = props.config.header) === null || _p === void 0 ? void 0 : _p.actions) === null || _q === void 0 ? void 0 : _q.minimize));
37312
37505
  var canCancel;
37313
37506
  // To preserve legacy behavior, cancel needs a little more checks
37314
- if (typeof ((_l = (_k = props.config.header) === null || _k === void 0 ? void 0 : _k.actions) === null || _l === void 0 ? void 0 : _l.cancel) === "boolean") {
37315
- canCancel = !dockedMode && !staticMode && !previewMode && ((_o = (_m = props.config.header) === null || _m === void 0 ? void 0 : _m.actions) === null || _o === void 0 ? void 0 : _o.cancel);
37507
+ if (typeof ((_s = (_r = props.config.header) === null || _r === void 0 ? void 0 : _r.actions) === null || _s === void 0 ? void 0 : _s.cancel) === "boolean") {
37508
+ canCancel = !dockedMode && !staticMode && !previewMode && ((_u = (_t = props.config.header) === null || _t === void 0 ? void 0 : _t.actions) === null || _u === void 0 ? void 0 : _u.cancel);
37316
37509
  }
37317
37510
  else {
37318
37511
  canCancel = !dockedMode && !staticMode && !previewMode;
@@ -37323,16 +37516,16 @@ var ChatWidgetUI = function (props) {
37323
37516
  }
37324
37517
  // Our state - pull from storage
37325
37518
  // Parse autoOpenOnWidth once for use in both initial state and useEffect
37326
- var autoOpenOnWidthValue = ((_p = props.config) === null || _p === void 0 ? void 0 : _p.autoOpenOnWidth)
37519
+ var autoOpenOnWidthValue = ((_v = props.config) === null || _v === void 0 ? void 0 : _v.autoOpenOnWidth)
37327
37520
  ? parseInt(props.config.autoOpenOnWidth, 10)
37328
37521
  : NaN;
37329
37522
  var autoOpenOnWidthMatch = !isNaN(autoOpenOnWidthValue) && window.innerWidth >= autoOpenOnWidthValue;
37330
37523
  // When autoOpenOnWidth is configured, use width check instead of persisted visible state
37331
37524
  // to prevent greeting requests on viewports below the threshold
37332
- var _15 = React.useState((!canMinimize && !canCancel) ||
37525
+ var _29 = React.useState((!canMinimize && !canCancel) ||
37333
37526
  // !!get("visible") ||
37334
- (!isNaN(autoOpenOnWidthValue) ? autoOpenOnWidthMatch : chatState.visuals.visible)), visible = _15[0], setVisibleState = _15[1];
37335
- var _16 = React.useState(false); _16[0]; var setTypingState = _16[1]; // false initially - state kept for potential external observers
37527
+ (!isNaN(autoOpenOnWidthValue) ? autoOpenOnWidthMatch : chatState.visuals.visible)), visible = _29[0], setVisibleState = _29[1];
37528
+ var _30 = React.useState(false); _30[0]; var setTypingState = _30[1]; // false initially - state kept for potential external observers
37336
37529
  // Ref to track typing state for use in timeout callbacks
37337
37530
  var typingRef = React.useRef(false);
37338
37531
  // Timeout ref for debouncing "stop typing" events
@@ -37340,11 +37533,11 @@ var ChatWidgetUI = function (props) {
37340
37533
  // Track whether autoOpenOnWidth has already fired so it doesn't re-open after user closes
37341
37534
  var autoOpenFiredRef = React.useRef(autoOpenOnWidthMatch);
37342
37535
  var chatServer = React.useContext(ChatServerContext);
37343
- var patternsConfig = (_r = (_q = props.config) === null || _q === void 0 ? void 0 : _q.autoOpenOnPattern) === null || _r === void 0 ? void 0 : _r.patterns;
37536
+ var patternsConfig = (_x = (_w = props.config) === null || _w === void 0 ? void 0 : _w.autoOpenOnPattern) === null || _x === void 0 ? void 0 : _x.patterns;
37344
37537
  var currentUrl = window.location.href;
37345
37538
  var patternExist = patternsConfig && patternsConfig.length > 0;
37346
37539
  var patternMatches = patternsConfig === null || patternsConfig === void 0 ? void 0 : patternsConfig.some(function (pattern) { return currentUrl.includes(pattern); });
37347
- var configWidth = (_t = (_s = props.config) === null || _s === void 0 ? void 0 : _s.autoOpenOnPattern) === null || _t === void 0 ? void 0 : _t.minimumWidth;
37540
+ var configWidth = (_z = (_y = props.config) === null || _y === void 0 ? void 0 : _y.autoOpenOnPattern) === null || _z === void 0 ? void 0 : _z.minimumWidth;
37348
37541
  var currentWidth = window.innerWidth;
37349
37542
  var setVisible = React.useCallback(function (newVisible) {
37350
37543
  if (staticMode || previewMode) {
@@ -37379,7 +37572,7 @@ var ChatWidgetUI = function (props) {
37379
37572
  };
37380
37573
  // eslint-disable-next-line react-hooks/exhaustive-deps
37381
37574
  }, []);
37382
- var _17 = React.useState(!document.hidden), isTabVisible = _17[0], setIsTabVisible = _17[1];
37575
+ var _31 = React.useState(!document.hidden), isTabVisible = _31[0], setIsTabVisible = _31[1];
37383
37576
  React.useEffect(function () {
37384
37577
  var handleVisibilityChange = function () {
37385
37578
  setIsTabVisible(!document.hidden);
@@ -37603,8 +37796,8 @@ var ChatWidgetUI = function (props) {
37603
37796
  }));
37604
37797
  }
37605
37798
  // Action Bar state and handlers
37606
- var _18 = React.useState(false), formModalOpen = _18[0], setFormModalOpen = _18[1];
37607
- var _19 = React.useState(null), activeFormConfig = _19[0], setActiveFormConfig = _19[1];
37799
+ var _32 = React.useState(false), formModalOpen = _32[0], setFormModalOpen = _32[1];
37800
+ var _33 = React.useState(null), activeFormConfig = _33[0], setActiveFormConfig = _33[1];
37608
37801
  var handleFormButtonClick = React.useCallback(function (formButton) {
37609
37802
  // If form-widget is configured, use its openForm API
37610
37803
  // The form-widget script should already be pre-loaded
@@ -37671,19 +37864,56 @@ var ChatWidgetUI = function (props) {
37671
37864
  var messages = chatState && chatState.chats;
37672
37865
  log("Rendering - accountStatus: \"".concat(chatState.accountStatus, "\", connectionStatus: \"").concat(chatState.connection.connectionStatus, "\""));
37673
37866
  var config = props.config, onConnectionStatusChange = props.onConnectionStatusChange;
37674
- var actionBarEnabled = ((_u = config === null || config === void 0 ? void 0 : config.actionBar) === null || _u === void 0 ? void 0 : _u.enabled) === true;
37867
+ var actionBarEnabled = ((_0 = config === null || config === void 0 ? void 0 : config.actionBar) === null || _0 === void 0 ? void 0 : _0.enabled) === true;
37675
37868
  // The host page declares this; the widget cannot work it out. On the standalone
37676
37869
  // contact/booking page the form already *is* the page, which makes every button that
37677
37870
  // only opens one redundant. XappMedia/chat-widget#1626.
37678
37871
  var isFormPage = useIsFormPage();
37872
+ // Studio can save Form/Book buttons with no form widget key anywhere. They can only open the
37873
+ // FormModal fallback, which then says "Form widget key not configured" - so drop them, unless
37874
+ // the host page installed the form widget itself. One key anywhere is enough: a page has one
37875
+ // form widget and every Form/Book button opens it through the same global.
37876
+ var configuredButtons = (_2 = (_1 = config === null || config === void 0 ? void 0 : config.actionBar) === null || _1 === void 0 ? void 0 : _1.buttons) !== null && _2 !== void 0 ? _2 : [];
37877
+ var hasKeylessFormButton = !(config === null || config === void 0 ? void 0 : config.formWidgetKey) &&
37878
+ configuredButtons.some(opensFormWidget) &&
37879
+ !configuredButtons.some(formButtonKey);
37880
+ var _34 = React.useState(function () { return hasKeylessFormButton && isHostFormWidgetOnPage(); }), hostFormWidget = _34[0], setHostFormWidget = _34[1];
37881
+ // The host's form-widget script loads independently of ours and can arrive after the first
37882
+ // render, so keep looking for a while rather than deciding once. This only runs when there is
37883
+ // no key anywhere, and with no key we never preload - so the script this finds by its fixed id
37884
+ // cannot be our own.
37885
+ React.useEffect(function () {
37886
+ if (!hasKeylessFormButton || hostFormWidget) {
37887
+ return undefined;
37888
+ }
37889
+ var checks = 0;
37890
+ var interval = setInterval(function () {
37891
+ checks++;
37892
+ if (isHostFormWidgetOnPage()) {
37893
+ setHostFormWidget(true);
37894
+ clearInterval(interval);
37895
+ }
37896
+ else if (checks >= HOST_FORM_WIDGET_MAX_CHECKS) {
37897
+ clearInterval(interval);
37898
+ }
37899
+ }, HOST_FORM_WIDGET_CHECK_MS);
37900
+ return function () { return clearInterval(interval); };
37901
+ }, [hasKeylessFormButton, hostFormWidget]);
37902
+ var actionBarConfig = React.useMemo(function () {
37903
+ var actionBar = config === null || config === void 0 ? void 0 : config.actionBar;
37904
+ if (!actionBar || !hasKeylessFormButton || hostFormWidget) {
37905
+ return actionBar;
37906
+ }
37907
+ return __assign$1(__assign$1({}, actionBar), { buttons: actionBar.buttons.filter(function (button) { return !opensFormWidget(button); }) });
37908
+ }, [config === null || config === void 0 ? void 0 : config.actionBar, hasKeylessFormButton, hostFormWidget]);
37679
37909
  var actionBarButtons = React.useMemo(function () {
37680
- return actionBarEnabled && (config === null || config === void 0 ? void 0 : config.actionBar)
37681
- ? visibleActionBarButtons(config.actionBar.buttons, {
37910
+ return actionBarEnabled && actionBarConfig
37911
+ ? visibleActionBarButtons(actionBarConfig.buttons, {
37682
37912
  chatDisabled: config.disabled,
37683
37913
  formDisabled: isFormPage,
37684
37914
  })
37685
37915
  : [];
37686
- }, [actionBarEnabled, config === null || config === void 0 ? void 0 : config.actionBar, config === null || config === void 0 ? void 0 : config.disabled, isFormPage]);
37916
+ }, [actionBarEnabled, actionBarConfig, config === null || config === void 0 ? void 0 : config.disabled, isFormPage]);
37687
37917
  // A bar that filters down to nothing is a bare strip of chrome. Treat it as if the bar
37688
37918
  // were off, so the visitor still gets the plain chat button rather than an empty shell.
37689
37919
  var actionBarVisible = actionBarEnabled && actionBarButtons.length > 0;
@@ -37695,7 +37925,7 @@ var ChatWidgetUI = function (props) {
37695
37925
  onConnectionStatusChange(connectionStatus);
37696
37926
  }
37697
37927
  }, [connectionStatus, onConnectionStatusChange]);
37698
- useExternalScript((_v = props.config) === null || _v === void 0 ? void 0 : _v.middlewareUrl);
37928
+ useExternalScript((_3 = props.config) === null || _3 === void 0 ? void 0 : _3.middlewareUrl);
37699
37929
  // Only reach for form.xapp.ai when something on this page can still open the form.
37700
37930
  //
37701
37931
  // Loading it is not free: the script mounts a second form-widget instance whose wrapper
@@ -37705,11 +37935,16 @@ var ChatWidgetUI = function (props) {
37705
37935
  //
37706
37936
  // With no bar configured the side button IS the entry point, so that case still loads.
37707
37937
  var formWidgetNeeded = !isFormPage && (!actionBarEnabled || actionBarButtons.some(opensFormWidget));
37938
+ // The top-level key is the documented place for it, but an App can carry the key only on
37939
+ // a Form/Book button's formConfig - buildChatWidgetChannel did exactly that. Reading only
37940
+ // the top-level key left the script unloaded, so every click waited out
37941
+ // openFormWidgetWhenReady before the modal fallback found the button's key.
37942
+ var formWidgetKey = (_4 = config === null || config === void 0 ? void 0 : config.formWidgetKey) !== null && _4 !== void 0 ? _4 : actionBarButtons.map(formButtonKey).find(Boolean);
37708
37943
  React.useEffect(function () {
37709
- if ((config === null || config === void 0 ? void 0 : config.formWidgetKey) && formWidgetNeeded) {
37710
- preloadFormWidgetScript(config.formWidgetKey);
37944
+ if (formWidgetKey && formWidgetNeeded) {
37945
+ preloadFormWidgetScript(formWidgetKey);
37711
37946
  }
37712
- }, [config === null || config === void 0 ? void 0 : config.formWidgetKey, formWidgetNeeded]);
37947
+ }, [formWidgetKey, formWidgetNeeded]);
37713
37948
  // Set body attribute when actionBar is enabled (used by CSS to hide form-widget side button on mobile)
37714
37949
  // Uses reference counting to handle multiple widget instances
37715
37950
  React.useEffect(function () {
@@ -37735,18 +37970,23 @@ var ChatWidgetUI = function (props) {
37735
37970
  };
37736
37971
  }, [actionBarVisible]);
37737
37972
  // This is a pseudo agent. It represent's the widget (shown in the header avatar for instance)
37738
- var widgetAgent = ((_w = chatState.agents["agent:robot"]) === null || _w === void 0 ? void 0 : _w.user) ||
37973
+ var widgetAgent = ((_5 = chatState.agents["agent:robot"]) === null || _5 === void 0 ? void 0 : _5.user) ||
37739
37974
  (config === null || config === void 0 ? void 0 : config.agent) || {
37740
37975
  nick: "agent:robot",
37741
37976
  avatarPath: config.avatarUrl,
37742
37977
  display_name: "Agent",
37743
37978
  };
37744
- return (require$$0.jsxs(require$$0.Fragment, { children: [require$$0.jsxs("div", { className: "widget-container ".concat(modeClass, " ").concat(getVisibilityClass()).concat(actionBarVisible ? " widget-container--with-action-bar" : ""), children: [require$$0.jsx(WidgetStylesheet, { theme: config === null || config === void 0 ? void 0 : config.theme }), !headerHidden && (require$$0.jsx(ChatHeader, { accountStatus: chatState.accountStatus, refreshOnClick: handleRestartClick, minimizeOnClick: handleMinimizeClick, cancelOnClick: handleCancelClick, agent: widgetAgent, canRefresh: canRefresh, canMinimize: canMinimize, canCancel: canCancel, config: config === null || config === void 0 ? void 0 : config.header, menuConfig: config.menu, debugMode: (_z = (_y = (_x = props.config) === null || _x === void 0 ? void 0 : _x.connection) === null || _y === void 0 ? void 0 : _y.mcp) === null || _z === void 0 ? void 0 : _z.debugMode, onSubmit: handleOnSubmit })), require$$0.jsx(MessageList, { visible: visible, queuePosition: chatState.queuePosition, isChatting: chatState.isChatting, isOffline: isOffline, messages: messages, agents: chatState.agents, agent: config === null || config === void 0 ? void 0 : config.agent, lastRatingRequestTimestamp: chatState.lastRatingRequestTimestamp, hasRating: chatState.hasRating, visitorId: chatState.visitorId, hasWsButton: !!chatState.wsButton, messageMiddleware: props.messageMiddleware, textTypingStatusEnabled: (_1 = (_0 = props.config) === null || _0 === void 0 ? void 0 : _0.typingStatus) === null || _1 === void 0 ? void 0 : _1.textTypingStatusEnabled, disableAutoScroll: props.disableAutoScroll, onSend: handleSendMessage, onWrite: handleWriteMessage, onOpenUrl: handleOpenUrl, minimizeOnClick: handleMinimizeClick }), require$$0.jsx("div", { className: "xa-spinner-container ".concat(visible && connectionStatus === "pending" ? "visible" : ""), children: require$$0.jsx("div", { className: "xa-spinner" }) }), connectionStatus === "offline" && require$$0.jsx(ServerOffline, {}), chatState.wsButton && visible && (require$$0.jsx(WsButton, { button: chatState.wsButton, onPress: handleWsButtonPress })), require$$0.jsx(ChatFooter, { isAdmin: config === null || config === void 0 ? void 0 : config.isAdmin, isChatting: chatState.isChatting, placeholder: (_2 = config === null || config === void 0 ? void 0 : config.input) === null || _2 === void 0 ? void 0 : _2.placeholder, sendButtonIcon: (_4 = (_3 = config === null || config === void 0 ? void 0 : config.footer) === null || _3 === void 0 ? void 0 : _3.sendButton) === null || _4 === void 0 ? void 0 : _4.icon, sendButtonIconHover: (_6 = (_5 = config === null || config === void 0 ? void 0 : config.footer) === null || _5 === void 0 ? void 0 : _5.sendButton) === null || _6 === void 0 ? void 0 : _6.iconHover, sendButtonIconDisabled: (_8 = (_7 = config === null || config === void 0 ? void 0 : config.footer) === null || _7 === void 0 ? void 0 : _7.sendButton) === null || _8 === void 0 ? void 0 : _8.iconDisabled, visible: visible, hasWsButton: !!chatState.wsButton, menuConfig: menuConfig, footerConfig: (_9 = props.config) === null || _9 === void 0 ? void 0 : _9.footer, inputConfig: (_10 = props.config) === null || _10 === void 0 ? void 0 : _10.input, disabled: previewMode, onChange: handleOnChange, onSubmit: handleOnSubmit, onFileUpload: handleFileUpload }), require$$0.jsx("div", { className: "restartModal", ref: modalRef, onClick: handleRestartModalCloseClick, children: require$$0.jsx(ModalContent, { onClose: handleRestartModalCloseClick, onReset: handleReset }) })] }), actionBarVisible && config.actionBar ? (require$$0.jsxs(require$$0.Fragment, { children: [require$$0.jsx(ActionBar, { config: __assign$1(__assign$1({}, config.actionBar), {
37979
+ var widgetContainer = (require$$0.jsxs("div", { className: "widget-container ".concat(modeClass, " ").concat(getVisibilityClass()).concat(actionBarVisible ? " widget-container--with-action-bar" : "").concat(poppedOut ? " widget-container--popped" : "").concat(collapsedOnMobile ? " widget-container--collapsed" : ""), children: [require$$0.jsx(WidgetStylesheet, { theme: config === null || config === void 0 ? void 0 : config.theme }), !headerHidden && (require$$0.jsx(ChatHeader, { accountStatus: chatState.accountStatus, refreshOnClick: handleRestartClick, minimizeOnClick: poppedOut ? handlePopOutDismiss : handleMinimizeClick, cancelOnClick: handleCancelClick, agent: widgetAgent, canRefresh: canRefresh, canMinimize: poppedOut || canMinimize, canCancel: canCancel, config: config === null || config === void 0 ? void 0 : config.header, menuConfig: config.menu, debugMode: (_8 = (_7 = (_6 = props.config) === null || _6 === void 0 ? void 0 : _6.connection) === null || _7 === void 0 ? void 0 : _7.mcp) === null || _8 === void 0 ? void 0 : _8.debugMode, onSubmit: handleOnSubmit })), require$$0.jsx(MessageList, { visible: visible, queuePosition: chatState.queuePosition, isChatting: chatState.isChatting, isOffline: isOffline, messages: messages, agents: chatState.agents, agent: config === null || config === void 0 ? void 0 : config.agent, lastRatingRequestTimestamp: chatState.lastRatingRequestTimestamp, hasRating: chatState.hasRating, visitorId: chatState.visitorId, hasWsButton: !!chatState.wsButton, messageMiddleware: props.messageMiddleware, textTypingStatusEnabled: (_10 = (_9 = props.config) === null || _9 === void 0 ? void 0 : _9.typingStatus) === null || _10 === void 0 ? void 0 : _10.textTypingStatusEnabled, disableAutoScroll: props.disableAutoScroll, onSend: handleSendMessage, onWrite: handleWriteMessage, onOpenUrl: handleOpenUrl, minimizeOnClick: handleMinimizeClick }), require$$0.jsx("div", { className: "xa-spinner-container ".concat(visible && connectionStatus === "pending" ? "visible" : ""), children: require$$0.jsx("div", { className: "xa-spinner" }) }), connectionStatus === "offline" && require$$0.jsx(ServerOffline, {}), chatState.wsButton && visible && (require$$0.jsx(WsButton, { button: chatState.wsButton, onPress: handleWsButtonPress })), require$$0.jsx(ChatFooter, { isAdmin: config === null || config === void 0 ? void 0 : config.isAdmin, isChatting: chatState.isChatting, placeholder: (_11 = config === null || config === void 0 ? void 0 : config.input) === null || _11 === void 0 ? void 0 : _11.placeholder, sendButtonIcon: (_13 = (_12 = config === null || config === void 0 ? void 0 : config.footer) === null || _12 === void 0 ? void 0 : _12.sendButton) === null || _13 === void 0 ? void 0 : _13.icon, sendButtonIconHover: (_15 = (_14 = config === null || config === void 0 ? void 0 : config.footer) === null || _14 === void 0 ? void 0 : _14.sendButton) === null || _15 === void 0 ? void 0 : _15.iconHover, sendButtonIconDisabled: (_17 = (_16 = config === null || config === void 0 ? void 0 : config.footer) === null || _16 === void 0 ? void 0 : _16.sendButton) === null || _17 === void 0 ? void 0 : _17.iconDisabled, visible: visible, hasWsButton: !!chatState.wsButton, menuConfig: menuConfig, footerConfig: (_18 = props.config) === null || _18 === void 0 ? void 0 : _18.footer, inputConfig: (_19 = props.config) === null || _19 === void 0 ? void 0 : _19.input, disabled: previewMode, onChange: handleOnChange, onSubmit: handleOnSubmit, onFileUpload: handleFileUpload }), require$$0.jsx("div", { className: "restartModal", ref: modalRef, onClick: handleRestartModalCloseClick, children: require$$0.jsx(ModalContent, { onClose: handleRestartModalCloseClick, onReset: handleReset }) })] }));
37980
+ return (require$$0.jsxs(require$$0.Fragment, { children: [popOutEnabled ? (
37981
+ // The anchor keeps the chat's place in the page, so the layout does not jump when
37982
+ // the chat pops out. The chat itself lives in popOutHost, which the effect above
37983
+ // moves between this anchor and the body.
37984
+ require$$0.jsx("div", { className: "widget-anchor", ref: anchorRef, children: popOutHost && reactDom.createPortal(widgetContainer, popOutHost) })) : (widgetContainer), actionBarVisible && actionBarConfig && !(collapsedOnMobile && mobileEntry === "button") ? (require$$0.jsxs(require$$0.Fragment, { children: [require$$0.jsx(ActionBar, { config: __assign$1(__assign$1({}, actionBarConfig), {
37745
37985
  // Use actionBar.cta if set, otherwise fall back to widget-level cta
37746
- cta: resolveCta((_11 = config.actionBar.cta) !== null && _11 !== void 0 ? _11 : config.cta, {
37986
+ cta: resolveCta((_20 = actionBarConfig.cta) !== null && _20 !== void 0 ? _20 : config.cta, {
37747
37987
  hasConversation: conversationOnScreen,
37748
37988
  arrivedViaChatLink: arrivedViaChatLink,
37749
- }) }), visible: visible, chatDisabled: config.disabled, formDisabled: isFormPage, hasUserInteracted: (_12 = chatState.visuals) === null || _12 === void 0 ? void 0 : _12.hasInteracted, onChatClick: chatButtonOnClick, onChatMinimize: handleMinimizeClick, onFormClick: handleFormButtonClick, onCtaDismiss: handleCtaDismiss }), formModalOpen && activeFormConfig && (require$$0.jsx(FormModal, { config: activeFormConfig, widgetEnv: config, onClose: handleFormModalClose }))] })) : (require$$0.jsx(ChatButton, { addClass: visible ? "visible" : "", onClick: chatButtonOnClick, config: chatButtonCta, imageUrl: (_13 = config === null || config === void 0 ? void 0 : config.chatButton) === null || _13 === void 0 ? void 0 : _13.imageUrl, visible: visible, hasInteracted: (_14 = chatState.visuals) === null || _14 === void 0 ? void 0 : _14.hasInteracted, onCtaDismiss: handleCtaDismiss })), require$$0.jsx(ErrorOverlay, { enableErrorOverlay: config === null || config === void 0 ? void 0 : config.enableErrorOverlay })] }));
37989
+ }) }), visible: collapsedOnMobile ? false : visible, chatDisabled: config.disabled, formDisabled: isFormPage, hasUserInteracted: (_21 = chatState.visuals) === null || _21 === void 0 ? void 0 : _21.hasInteracted, onChatClick: collapsedOnMobile ? handleMobileOpen : chatButtonOnClick, onChatMinimize: handleMinimizeClick, onFormClick: handleFormButtonClick, onCtaDismiss: handleCtaDismiss }), formModalOpen && activeFormConfig && (require$$0.jsx(FormModal, { config: activeFormConfig, widgetEnv: config, onClose: handleFormModalClose }))] })) : (require$$0.jsx(ChatButton, { addClass: visible && !collapsedOnMobile ? "visible" : "", onClick: collapsedOnMobile ? handleMobileOpen : chatButtonOnClick, config: chatButtonCta, imageUrl: (_22 = config === null || config === void 0 ? void 0 : config.chatButton) === null || _22 === void 0 ? void 0 : _22.imageUrl, visible: collapsedOnMobile ? false : visible, hasInteracted: (_23 = chatState.visuals) === null || _23 === void 0 ? void 0 : _23.hasInteracted, onCtaDismiss: handleCtaDismiss })), require$$0.jsx(ErrorOverlay, { enableErrorOverlay: config === null || config === void 0 ? void 0 : config.enableErrorOverlay })] }));
37750
37990
  };
37751
37991
  /**
37752
37992
  * Top-level wrapper that dispatches between preview mode and connected mode.