@xapp/chat-widget 1.96.1 → 1.96.3

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.es.js CHANGED
@@ -67,6 +67,277 @@ function isActionBarPaymentButton(button) {
67
67
  return button.type === "payment";
68
68
  }
69
69
 
70
+ var buildChatWidgetChannel$1 = {};
71
+
72
+ var color = {};
73
+
74
+ /*! Copyright (c) 2026, XAPP AI */
75
+ Object.defineProperty(color, "__esModule", { value: true });
76
+ color.parseRgb = parseRgb;
77
+ color.invertColorHEX = invertColorHEX;
78
+ color.invertColorRgb = invertColorRgb;
79
+ color.invertColor = invertColor;
80
+ color.isSupportedColor = isSupportedColor;
81
+ color.readableTextOn = readableTextOn;
82
+ /**
83
+ * Colour maths for building a widget theme from a business's own branding.
84
+ *
85
+ * These lived in stentor-client, which meant the only way to work out a
86
+ * readable text colour was to be running in a browser. Studio needs the same
87
+ * answers when it builds an app server-side for a get.xapp.ai signup, and two
88
+ * implementations of "which colour reads on this background" would drift into
89
+ * two different-looking widgets.
90
+ *
91
+ * The inputs are colours scraped off a customer's website, so they are whatever
92
+ * their designer chose — any hex length, rgb or rgba, or nothing at all.
93
+ */
94
+ /** Left-pads a hex component so "f" becomes "0f". */
95
+ function padZero(value, length = 2) {
96
+ const zeros = new Array(length).join("0");
97
+ return (zeros + value).slice(-length);
98
+ }
99
+ function parseRgb(colorString) {
100
+ const rgba = /^rgba?\((\d+),\s*(\d+),\s*(\d+),\s*([\d.]+)\)$/;
101
+ const rgb = /^rgb?\((\d+),\s*(\d+),\s*(\d+)\)$/;
102
+ const withAlpha = colorString === null || colorString === void 0 ? void 0 : colorString.match(rgba);
103
+ if (withAlpha) {
104
+ return {
105
+ r: parseInt(withAlpha[1], 10),
106
+ g: parseInt(withAlpha[2], 10),
107
+ b: parseInt(withAlpha[3], 10),
108
+ a: parseFloat(withAlpha[4])
109
+ };
110
+ }
111
+ const plain = colorString === null || colorString === void 0 ? void 0 : colorString.match(rgb);
112
+ if (plain) {
113
+ return { r: parseInt(plain[1], 10), g: parseInt(plain[2], 10), b: parseInt(plain[3], 10) };
114
+ }
115
+ return null;
116
+ }
117
+ /**
118
+ * Whether text should be black or white to read on this background.
119
+ *
120
+ * The weighting is perceived brightness, not an average: the eye is far more
121
+ * sensitive to green than to blue, so a pure blue is dark to us even though its
122
+ * numeric average is mid-range.
123
+ *
124
+ * @see http://stackoverflow.com/a/3943023/112731
125
+ */
126
+ function isLight(r, g, b) {
127
+ return r * 0.299 + g * 0.587 + b * 0.114 > 186;
128
+ }
129
+ /**
130
+ * Inverts a hex colour, or returns black/white for contrast when `bw` is set.
131
+ *
132
+ * Inverting is rarely what you want behind text — a mid-tone inverts to another
133
+ * mid-tone and neither reads. `bw` is the contrast answer.
134
+ */
135
+ function invertColorHEX(hex, bw) {
136
+ if (!hex) {
137
+ return undefined;
138
+ }
139
+ let value = hex.indexOf("#") === 0 ? hex.slice(1) : hex;
140
+ if (value.length === 3) {
141
+ value = value[0] + value[0] + value[1] + value[1] + value[2] + value[2];
142
+ }
143
+ if (value.length !== 6) {
144
+ throw new Error("Invalid HEX color.");
145
+ }
146
+ const r = parseInt(value.slice(0, 2), 16);
147
+ const g = parseInt(value.slice(2, 4), 16);
148
+ const b = parseInt(value.slice(4, 6), 16);
149
+ if (bw) {
150
+ return isLight(r, g, b) ? "#000000" : "#FFFFFF";
151
+ }
152
+ return `#${padZero((255 - r).toString(16))}${padZero((255 - g).toString(16))}${padZero((255 - b).toString(16))}`;
153
+ }
154
+ /** As invertColorHEX, for rgb/rgba input. */
155
+ function invertColorRgb(rgb, bw) {
156
+ const parsed = parseRgb(rgb);
157
+ if (!parsed) {
158
+ return rgb;
159
+ }
160
+ const { r, g, b } = parsed;
161
+ if (bw) {
162
+ return isLight(r, g, b) ? "rgba(0, 0, 0, 1)" : "rgba(255, 255, 255, 1)";
163
+ }
164
+ return `rgba(${255 - r}, ${255 - g}, ${255 - b}, 1)`;
165
+ }
166
+ /** Inverts whichever colour notation was given. */
167
+ function invertColor(color, bw) {
168
+ if (!color) {
169
+ return undefined;
170
+ }
171
+ return color.startsWith("#") ? invertColorHEX(color, bw) : invertColorRgb(color, bw);
172
+ }
173
+ /**
174
+ * Whether we can work out what text reads on this colour.
175
+ *
176
+ * Hex and rgb/rgba only. A CSS named colour like `orange`, or `hsl(...)`, is
177
+ * perfectly valid CSS — we simply cannot compute its brightness, and a
178
+ * background whose contrast we cannot compute is one we must not use.
179
+ */
180
+ function isSupportedColor(color) {
181
+ if (!color) {
182
+ return false;
183
+ }
184
+ if (color.startsWith("#")) {
185
+ const value = color.slice(1);
186
+ return (value.length === 3 || value.length === 6) && /^[0-9a-f]+$/i.test(value);
187
+ }
188
+ return parseRgb(color) !== null;
189
+ }
190
+ /**
191
+ * The text colour that will read on this background: black or white, never
192
+ * anything else.
193
+ *
194
+ * That guarantee is the whole point. An earlier version leaned on invertColor,
195
+ * whose rgb path returns its input unchanged when it cannot parse it — so
196
+ * `readableTextOn("orange")` answered `"orange"`, and a header themed from a
197
+ * scraped named colour got text in exactly the background colour. Invisible,
198
+ * and by the one function meant to prevent it.
199
+ *
200
+ * Unparseable input falls back to black. That is a guess, so callers who
201
+ * control the background should check `isSupportedColor` first and use a
202
+ * colour whose contrast can actually be computed, rather than pairing a
203
+ * guessed foreground with an unknown background.
204
+ */
205
+ function readableTextOn(background) {
206
+ if (!isSupportedColor(background)) {
207
+ return "#000000";
208
+ }
209
+ const rgb = background.startsWith("#") ? hexToRgb(background) : parseRgb(background);
210
+ if (!rgb) {
211
+ return "#000000";
212
+ }
213
+ return isLight(rgb.r, rgb.g, rgb.b) ? "#000000" : "#FFFFFF";
214
+ }
215
+ function hexToRgb(hex) {
216
+ let value = hex.slice(1);
217
+ if (value.length === 3) {
218
+ value = value[0] + value[0] + value[1] + value[1] + value[2] + value[2];
219
+ }
220
+ if (value.length !== 6) {
221
+ return null;
222
+ }
223
+ return {
224
+ r: parseInt(value.slice(0, 2), 16),
225
+ g: parseInt(value.slice(2, 4), 16),
226
+ b: parseInt(value.slice(4, 6), 16)
227
+ };
228
+ }
229
+
230
+ Object.defineProperty(buildChatWidgetChannel$1, "__esModule", { value: true });
231
+ buildChatWidgetChannel$1.buildChatWidgetChannel = buildChatWidgetChannel;
232
+ buildChatWidgetChannel$1.buildChatTheme = buildChatTheme;
233
+ const color_1 = color;
234
+ /** Fallback when a crawl found no branding. Deliberately neutral. */
235
+ const DEFAULT_PRIMARY = "#1AA7DC";
236
+ function buildChatWidgetChannel(props) {
237
+ const { appId, apiUrl, mcpUrl, formWidgetKey, phoneNumber } = props;
238
+ // Only a colour whose contrast can actually be computed, so the background
239
+ // and the text on it are always a matched pair rather than one scraped
240
+ // value and one guess.
241
+ const primaryColor = (0, color_1.isSupportedColor)(props.primaryColor) ? props.primaryColor : DEFAULT_PRIMARY;
242
+ return {
243
+ type: "chat-widget",
244
+ // MCP by default. The widget runs on a public page, so homeowner mode
245
+ // — which is unauthenticated and carries the appId in the url — is the
246
+ // only one that can work there; business_owner needs a token, and a
247
+ // token on a public page is not a token.
248
+ connection: {
249
+ type: "mcp",
250
+ serverUrl: `${mcpUrl}/${appId}`,
251
+ mcp: {
252
+ mode: "homeowner"
253
+ }
254
+ },
255
+ theme: buildChatTheme(primaryColor),
256
+ actionBar: buildActionBar({ apiUrl, formWidgetKey, phoneNumber })
257
+ };
258
+ }
259
+ /**
260
+ * The dock of buttons that replaces the plain chat bubble.
261
+ *
262
+ * On by default, which is the part worth explaining: chat is not on the default
263
+ * tier, but the action bar is how someone reaches booking and the phone, and
264
+ * those are what the business is paying for.
265
+ *
266
+ * Order is deliberate. Booking is the thing we are selling, so it comes first;
267
+ * calling is the fallback for people who will not use a form; chat is last
268
+ * because it is the least likely to be enabled.
269
+ */
270
+ function buildActionBar(props) {
271
+ const { apiUrl, formWidgetKey, phoneNumber } = props;
272
+ const buttons = [];
273
+ if (formWidgetKey) {
274
+ buttons.push({
275
+ id: "book",
276
+ type: "schedule",
277
+ label: "Book",
278
+ formConfig: {
279
+ api: {
280
+ url: apiUrl,
281
+ key: formWidgetKey
282
+ }
283
+ }
284
+ });
285
+ }
286
+ if (phoneNumber) {
287
+ buttons.push({
288
+ id: "call",
289
+ type: "phone",
290
+ label: "Call",
291
+ phoneNumber
292
+ });
293
+ }
294
+ buttons.push({
295
+ id: "chat",
296
+ type: "chat",
297
+ label: "Chat"
298
+ });
299
+ return {
300
+ enabled: true,
301
+ position: "right",
302
+ buttons
303
+ };
304
+ }
305
+ /**
306
+ * A theme derived from the business's own colour.
307
+ *
308
+ * Only the text colour is computed rather than chosen: which of black or white
309
+ * reads on a given background is arithmetic, and getting it wrong ships a
310
+ * widget nobody can read.
311
+ */
312
+ function buildChatTheme(primaryColor) {
313
+ const onPrimary = (0, color_1.readableTextOn)(primaryColor);
314
+ return {
315
+ zIndex: "10000",
316
+ border: {
317
+ color: primaryColor,
318
+ radius: "10px"
319
+ },
320
+ chatButton: {
321
+ background: primaryColor,
322
+ margin: {
323
+ bottom: "10px",
324
+ left: "10px",
325
+ right: "10px",
326
+ top: "10px"
327
+ }
328
+ },
329
+ content: {
330
+ background: "#ffffff"
331
+ },
332
+ header: {
333
+ background: primaryColor,
334
+ text: {
335
+ color: onPrimary
336
+ }
337
+ }
338
+ };
339
+ }
340
+
70
341
  var ChannelData = {};
71
342
 
72
343
  Object.defineProperty(ChannelData, "__esModule", { value: true });
@@ -132,7 +403,9 @@ function isOpenURLMenuItem(item) {
132
403
  Object.defineProperty(exports, "__esModule", { value: true });
133
404
  /*! Copyright (c) 2021, XAPPmedia */
134
405
  __exportStar(ActionBar$1, exports);
406
+ __exportStar(buildChatWidgetChannel$1, exports);
135
407
  __exportStar(ChannelData, exports);
408
+ __exportStar(color, exports);
136
409
  __exportStar(Constants, exports);
137
410
  __exportStar(Types, exports);
138
411
  __exportStar(UserInfo, exports);
@@ -390,8 +663,19 @@ var ActionBarCta = function (_a) {
390
663
  }, children: [jsx("span", { className: "xapp-action-bar-cta__message", children: message }), dismissible && (jsx("button", { className: "xapp-action-bar-cta__dismiss", onClick: handleDismiss, "aria-label": "Dismiss", type: "button", children: jsx("svg", { width: "14", height: "14", viewBox: "0 0 14 14", fill: "none", xmlns: "http://www.w3.org/2000/svg", children: jsx("path", { d: "M13 1L1 13M1 1L13 13", stroke: "currentColor", strokeWidth: "2", strokeLinecap: "round", strokeLinejoin: "round" }) }) }))] }));
391
664
  };
392
665
 
393
- var DEFAULT_MOBILE_BREAKPOINT = 768;
394
- var RESIZE_DEBOUNCE_MS = 150;
666
+ /**
667
+ * The same query the stylesheets use, as a string rather than a number.
668
+ *
669
+ * A bare width could not express this. A phone on its side is 740-863px wide, so any
670
+ * width-only threshold either excludes landscape phones or catches tablets - #1592 moved
671
+ * the stylesheets to `(max-width: 640px), (max-height: 480px) and (pointer: coarse)` for
672
+ * exactly that reason, and a JS constant of 640 or 768 cannot mirror it either way.
673
+ *
674
+ * Sharing the query text is what keeps the two halves from drifting: matchMedia evaluates
675
+ * the identical condition the CSS does, so there is one definition of "phone" and it lives
676
+ * in `_mixins.scss`. Keep this in step with the `mobile()` mixin. XappMedia/chat-widget#1594.
677
+ */
678
+ var MOBILE_MEDIA_QUERY = "(max-width: 640px), (max-height: 480px) and (pointer: coarse)";
395
679
  /**
396
680
  * ChatWidget.scss sizes the chat panel against this variable. Nothing used to set it, so it always
397
681
  * fell back to the hardcoded 80px in the SCSS - and the real mobile bar is taller than that once
@@ -404,33 +688,43 @@ var RESIZE_DEBOUNCE_MS = 150;
404
688
  */
405
689
  var ACTION_BAR_HEIGHT_VAR = "--xapp-action-bar-height";
406
690
  var ActionBar = function (_a) {
407
- var _b, _c, _d;
408
- var config = _a.config, visible = _a.visible, chatDisabled = _a.chatDisabled, _e = _a.hasUserInteracted, hasUserInteracted = _e === void 0 ? false : _e, onChatClick = _a.onChatClick, onChatMinimize = _a.onChatMinimize, onFormClick = _a.onFormClick, onCtaDismiss = _a.onCtaDismiss;
409
- var _f = useState(false), isMobile = _f[0], setIsMobile = _f[1];
410
- var mobileBreakpoint = (_b = config.mobileBreakpoint) !== null && _b !== void 0 ? _b : DEFAULT_MOBILE_BREAKPOINT;
411
- var position = (_c = config.position) !== null && _c !== void 0 ? _c : "right";
412
- var resizeTimeoutRef = useRef(null);
691
+ var _b, _c;
692
+ var config = _a.config, visible = _a.visible, chatDisabled = _a.chatDisabled, _d = _a.hasUserInteracted, hasUserInteracted = _d === void 0 ? false : _d, onChatClick = _a.onChatClick, onChatMinimize = _a.onChatMinimize, onFormClick = _a.onFormClick, onCtaDismiss = _a.onCtaDismiss;
693
+ var _e = useState(false), isMobile = _e[0], setIsMobile = _e[1];
694
+ // An explicit override can only be a width; without one we ask the same question the
695
+ // stylesheets ask, so the two cannot disagree. A survey of production on 2026-08-19
696
+ // found the override set by nobody - zero of 971 bundles, against 18 configured
697
+ // ActionBars - so in practice every bar takes the shared query.
698
+ // `!= null`, not a truthy check: 0 is a legitimate override meaning "never mobile", and
699
+ // treating it as unset would hand back the default responsive query - the opposite of
700
+ // what was asked for.
701
+ var mediaQuery = config.mobileBreakpoint != null
702
+ ? "(max-width: ".concat(config.mobileBreakpoint, "px)")
703
+ : MOBILE_MEDIA_QUERY;
704
+ var position = (_b = config.position) !== null && _b !== void 0 ? _b : "right";
413
705
  var barRef = useRef(null);
414
- // Debounced resize handler
415
- var handleResize = useCallback(function () {
416
- if (resizeTimeoutRef.current) {
417
- window.clearTimeout(resizeTimeoutRef.current);
418
- }
419
- resizeTimeoutRef.current = window.setTimeout(function () {
420
- setIsMobile(window.innerWidth <= mobileBreakpoint);
421
- }, RESIZE_DEBOUNCE_MS);
422
- }, [mobileBreakpoint]);
423
706
  useEffect(function () {
424
- // Initial check (immediate, not debounced)
425
- setIsMobile(window.innerWidth <= mobileBreakpoint);
426
- window.addEventListener("resize", handleResize);
427
- return function () {
428
- window.removeEventListener("resize", handleResize);
429
- if (resizeTimeoutRef.current) {
430
- window.clearTimeout(resizeTimeoutRef.current);
431
- }
707
+ // matchMedia fires only when the answer actually changes, so there is nothing to
708
+ // debounce - unlike a resize listener, which fires continuously through a drag.
709
+ // Guarded because jsdom does not implement matchMedia, and a widget that throws on
710
+ // mount in a consumer's test suite is a worse failure than one that assumes desktop.
711
+ if (typeof window.matchMedia !== "function") {
712
+ return undefined;
713
+ }
714
+ var query = window.matchMedia(mediaQuery);
715
+ setIsMobile(query.matches);
716
+ var onChange = function (event) {
717
+ setIsMobile(event.matches);
432
718
  };
433
- }, [mobileBreakpoint, handleResize]);
719
+ // addListener is the pre-2021 Safari spelling. Still worth carrying: this widget
720
+ // runs on whatever browser a customer's visitor brings.
721
+ if (typeof query.addEventListener === "function") {
722
+ query.addEventListener("change", onChange);
723
+ return function () { return query.removeEventListener("change", onChange); };
724
+ }
725
+ query.addListener(onChange);
726
+ return function () { return query.removeListener(onChange); };
727
+ }, [mediaQuery]);
434
728
  // Publish the bar's real height so the chat panel can size around it.
435
729
  //
436
730
  // useLayoutEffect, not useEffect: this commits before paint, so the panel never gets a
@@ -483,7 +777,7 @@ var ActionBar = function (_a) {
483
777
  // - Chat must not be visible (user hasn't opened it)
484
778
  // - Chat must not be disabled
485
779
  var hasChatButton = config.buttons.some(lib.isActionBarChatButton);
486
- var showCta = ((_d = config.cta) === null || _d === void 0 ? void 0 : _d.message) && !visible && !chatDisabled && hasChatButton;
780
+ var showCta = ((_c = config.cta) === null || _c === void 0 ? void 0 : _c.message) && !visible && !chatDisabled && hasChatButton;
487
781
  var handleCtaClick = function () {
488
782
  onChatClick();
489
783
  };