@blumessage/react-chat 1.0.0 → 1.0.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.js CHANGED
@@ -1,2291 +1 @@
1
- 'use strict';
2
-
3
- var jsxRuntime = require('react/jsx-runtime');
4
- var react = require('react');
5
-
6
- /******************************************************************************
7
- Copyright (c) Microsoft Corporation.
8
-
9
- Permission to use, copy, modify, and/or distribute this software for any
10
- purpose with or without fee is hereby granted.
11
-
12
- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
13
- REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
14
- AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
15
- INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
16
- LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
17
- OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
18
- PERFORMANCE OF THIS SOFTWARE.
19
- ***************************************************************************** */
20
- /* global Reflect, Promise, SuppressedError, Symbol, Iterator */
21
-
22
-
23
- function __awaiter(thisArg, _arguments, P, generator) {
24
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
25
- return new (P || (P = Promise))(function (resolve, reject) {
26
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
27
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
28
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
29
- step((generator = generator.apply(thisArg, _arguments || [])).next());
30
- });
31
- }
32
-
33
- typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) {
34
- var e = new Error(message);
35
- return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
36
- };
37
-
38
- /**
39
- * @license lucide-react v0.462.0 - ISC
40
- *
41
- * This source code is licensed under the ISC license.
42
- * See the LICENSE file in the root directory of this source tree.
43
- */
44
-
45
- const toKebabCase = (string) => string.replace(/([a-z0-9])([A-Z])/g, "$1-$2").toLowerCase();
46
- const mergeClasses = (...classes) => classes.filter((className, index, array) => {
47
- return Boolean(className) && className.trim() !== "" && array.indexOf(className) === index;
48
- }).join(" ").trim();
49
-
50
- /**
51
- * @license lucide-react v0.462.0 - ISC
52
- *
53
- * This source code is licensed under the ISC license.
54
- * See the LICENSE file in the root directory of this source tree.
55
- */
56
-
57
- var defaultAttributes = {
58
- xmlns: "http://www.w3.org/2000/svg",
59
- width: 24,
60
- height: 24,
61
- viewBox: "0 0 24 24",
62
- fill: "none",
63
- stroke: "currentColor",
64
- strokeWidth: 2,
65
- strokeLinecap: "round",
66
- strokeLinejoin: "round"
67
- };
68
-
69
- /**
70
- * @license lucide-react v0.462.0 - ISC
71
- *
72
- * This source code is licensed under the ISC license.
73
- * See the LICENSE file in the root directory of this source tree.
74
- */
75
-
76
-
77
- const Icon$1 = react.forwardRef(
78
- ({
79
- color = "currentColor",
80
- size = 24,
81
- strokeWidth = 2,
82
- absoluteStrokeWidth,
83
- className = "",
84
- children,
85
- iconNode,
86
- ...rest
87
- }, ref) => {
88
- return react.createElement(
89
- "svg",
90
- {
91
- ref,
92
- ...defaultAttributes,
93
- width: size,
94
- height: size,
95
- stroke: color,
96
- strokeWidth: absoluteStrokeWidth ? Number(strokeWidth) * 24 / Number(size) : strokeWidth,
97
- className: mergeClasses("lucide", className),
98
- ...rest
99
- },
100
- [
101
- ...iconNode.map(([tag, attrs]) => react.createElement(tag, attrs)),
102
- ...Array.isArray(children) ? children : [children]
103
- ]
104
- );
105
- }
106
- );
107
-
108
- /**
109
- * @license lucide-react v0.462.0 - ISC
110
- *
111
- * This source code is licensed under the ISC license.
112
- * See the LICENSE file in the root directory of this source tree.
113
- */
114
-
115
-
116
- const createLucideIcon = (iconName, iconNode) => {
117
- const Component = react.forwardRef(
118
- ({ className, ...props }, ref) => react.createElement(Icon$1, {
119
- ref,
120
- iconNode,
121
- className: mergeClasses(`lucide-${toKebabCase(iconName)}`, className),
122
- ...props
123
- })
124
- );
125
- Component.displayName = `${iconName}`;
126
- return Component;
127
- };
128
-
129
- /**
130
- * @license lucide-react v0.462.0 - ISC
131
- *
132
- * This source code is licensed under the ISC license.
133
- * See the LICENSE file in the root directory of this source tree.
134
- */
135
-
136
-
137
- const Maximize = createLucideIcon("Maximize", [
138
- ["path", { d: "M8 3H5a2 2 0 0 0-2 2v3", key: "1dcmit" }],
139
- ["path", { d: "M21 8V5a2 2 0 0 0-2-2h-3", key: "1e4gt3" }],
140
- ["path", { d: "M3 16v3a2 2 0 0 0 2 2h3", key: "wsl5sc" }],
141
- ["path", { d: "M16 21h3a2 2 0 0 0 2-2v-3", key: "18trek" }]
142
- ]);
143
-
144
- /**
145
- * @license lucide-react v0.462.0 - ISC
146
- *
147
- * This source code is licensed under the ISC license.
148
- * See the LICENSE file in the root directory of this source tree.
149
- */
150
-
151
-
152
- const Minimize = createLucideIcon("Minimize", [
153
- ["path", { d: "M8 3v3a2 2 0 0 1-2 2H3", key: "hohbtr" }],
154
- ["path", { d: "M21 8h-3a2 2 0 0 1-2-2V3", key: "5jw1f3" }],
155
- ["path", { d: "M3 16h3a2 2 0 0 1 2 2v3", key: "198tvr" }],
156
- ["path", { d: "M16 21v-3a2 2 0 0 1 2-2h3", key: "ph8mxp" }]
157
- ]);
158
-
159
- /**
160
- * @license lucide-react v0.462.0 - ISC
161
- *
162
- * This source code is licensed under the ISC license.
163
- * See the LICENSE file in the root directory of this source tree.
164
- */
165
-
166
-
167
- const X = createLucideIcon("X", [
168
- ["path", { d: "M18 6 6 18", key: "1bl5f8" }],
169
- ["path", { d: "m6 6 12 12", key: "d8bk6v" }]
170
- ]);
171
-
172
- const defaultIconDimensions = Object.freeze(
173
- {
174
- left: 0,
175
- top: 0,
176
- width: 16,
177
- height: 16
178
- }
179
- );
180
- const defaultIconTransformations = Object.freeze({
181
- rotate: 0,
182
- vFlip: false,
183
- hFlip: false
184
- });
185
- const defaultIconProps = Object.freeze({
186
- ...defaultIconDimensions,
187
- ...defaultIconTransformations
188
- });
189
- const defaultExtendedIconProps = Object.freeze({
190
- ...defaultIconProps,
191
- body: "",
192
- hidden: false
193
- });
194
-
195
- function mergeIconTransformations(obj1, obj2) {
196
- const result = {};
197
- if (!obj1.hFlip !== !obj2.hFlip) {
198
- result.hFlip = true;
199
- }
200
- if (!obj1.vFlip !== !obj2.vFlip) {
201
- result.vFlip = true;
202
- }
203
- const rotate = ((obj1.rotate || 0) + (obj2.rotate || 0)) % 4;
204
- if (rotate) {
205
- result.rotate = rotate;
206
- }
207
- return result;
208
- }
209
-
210
- function mergeIconData(parent, child) {
211
- const result = mergeIconTransformations(parent, child);
212
- for (const key in defaultExtendedIconProps) {
213
- if (key in defaultIconTransformations) {
214
- if (key in parent && !(key in result)) {
215
- result[key] = defaultIconTransformations[key];
216
- }
217
- } else if (key in child) {
218
- result[key] = child[key];
219
- } else if (key in parent) {
220
- result[key] = parent[key];
221
- }
222
- }
223
- return result;
224
- }
225
-
226
- function getIconsTree(data, names) {
227
- const icons = data.icons;
228
- const aliases = data.aliases || /* @__PURE__ */ Object.create(null);
229
- const resolved = /* @__PURE__ */ Object.create(null);
230
- function resolve(name) {
231
- if (icons[name]) {
232
- return resolved[name] = [];
233
- }
234
- if (!(name in resolved)) {
235
- resolved[name] = null;
236
- const parent = aliases[name] && aliases[name].parent;
237
- const value = parent && resolve(parent);
238
- if (value) {
239
- resolved[name] = [parent].concat(value);
240
- }
241
- }
242
- return resolved[name];
243
- }
244
- (Object.keys(icons).concat(Object.keys(aliases))).forEach(resolve);
245
- return resolved;
246
- }
247
-
248
- function internalGetIconData(data, name, tree) {
249
- const icons = data.icons;
250
- const aliases = data.aliases || /* @__PURE__ */ Object.create(null);
251
- let currentProps = {};
252
- function parse(name2) {
253
- currentProps = mergeIconData(
254
- icons[name2] || aliases[name2],
255
- currentProps
256
- );
257
- }
258
- parse(name);
259
- tree.forEach(parse);
260
- return mergeIconData(data, currentProps);
261
- }
262
-
263
- function parseIconSet(data, callback) {
264
- const names = [];
265
- if (typeof data !== "object" || typeof data.icons !== "object") {
266
- return names;
267
- }
268
- if (data.not_found instanceof Array) {
269
- data.not_found.forEach((name) => {
270
- callback(name, null);
271
- names.push(name);
272
- });
273
- }
274
- const tree = getIconsTree(data);
275
- for (const name in tree) {
276
- const item = tree[name];
277
- if (item) {
278
- callback(name, internalGetIconData(data, name, item));
279
- names.push(name);
280
- }
281
- }
282
- return names;
283
- }
284
-
285
- const optionalPropertyDefaults = {
286
- provider: "",
287
- aliases: {},
288
- not_found: {},
289
- ...defaultIconDimensions
290
- };
291
- function checkOptionalProps(item, defaults) {
292
- for (const prop in defaults) {
293
- if (prop in item && typeof item[prop] !== typeof defaults[prop]) {
294
- return false;
295
- }
296
- }
297
- return true;
298
- }
299
- function quicklyValidateIconSet(obj) {
300
- if (typeof obj !== "object" || obj === null) {
301
- return null;
302
- }
303
- const data = obj;
304
- if (typeof data.prefix !== "string" || !obj.icons || typeof obj.icons !== "object") {
305
- return null;
306
- }
307
- if (!checkOptionalProps(obj, optionalPropertyDefaults)) {
308
- return null;
309
- }
310
- const icons = data.icons;
311
- for (const name in icons) {
312
- const icon = icons[name];
313
- if (
314
- // Name cannot be empty
315
- !name || // Must have body
316
- typeof icon.body !== "string" || // Check other props
317
- !checkOptionalProps(
318
- icon,
319
- defaultExtendedIconProps
320
- )
321
- ) {
322
- return null;
323
- }
324
- }
325
- const aliases = data.aliases || /* @__PURE__ */ Object.create(null);
326
- for (const name in aliases) {
327
- const icon = aliases[name];
328
- const parent = icon.parent;
329
- if (
330
- // Name cannot be empty
331
- !name || // Parent must be set and point to existing icon
332
- typeof parent !== "string" || !icons[parent] && !aliases[parent] || // Check other props
333
- !checkOptionalProps(
334
- icon,
335
- defaultExtendedIconProps
336
- )
337
- ) {
338
- return null;
339
- }
340
- }
341
- return data;
342
- }
343
-
344
- const matchIconName = /^[a-z0-9]+(-[a-z0-9]+)*$/;
345
- const stringToIcon = (value, validate, allowSimpleName, provider = "") => {
346
- const colonSeparated = value.split(":");
347
- if (value.slice(0, 1) === "@") {
348
- if (colonSeparated.length < 2 || colonSeparated.length > 3) {
349
- return null;
350
- }
351
- provider = colonSeparated.shift().slice(1);
352
- }
353
- if (colonSeparated.length > 3 || !colonSeparated.length) {
354
- return null;
355
- }
356
- if (colonSeparated.length > 1) {
357
- const name2 = colonSeparated.pop();
358
- const prefix = colonSeparated.pop();
359
- const result = {
360
- // Allow provider without '@': "provider:prefix:name"
361
- provider: colonSeparated.length > 0 ? colonSeparated[0] : provider,
362
- prefix,
363
- name: name2
364
- };
365
- return validate && !validateIconName(result) ? null : result;
366
- }
367
- const name = colonSeparated[0];
368
- const dashSeparated = name.split("-");
369
- if (dashSeparated.length > 1) {
370
- const result = {
371
- provider,
372
- prefix: dashSeparated.shift(),
373
- name: dashSeparated.join("-")
374
- };
375
- return validate && !validateIconName(result) ? null : result;
376
- }
377
- if (allowSimpleName && provider === "") {
378
- const result = {
379
- provider,
380
- prefix: "",
381
- name
382
- };
383
- return validate && !validateIconName(result, allowSimpleName) ? null : result;
384
- }
385
- return null;
386
- };
387
- const validateIconName = (icon, allowSimpleName) => {
388
- if (!icon) {
389
- return false;
390
- }
391
- return !!// Check prefix: cannot be empty, unless allowSimpleName is enabled
392
- // Check name: cannot be empty
393
- ((allowSimpleName && icon.prefix === "" || !!icon.prefix) && !!icon.name);
394
- };
395
-
396
- const dataStorage = /* @__PURE__ */ Object.create(null);
397
- function newStorage(provider, prefix) {
398
- return {
399
- provider,
400
- prefix,
401
- icons: /* @__PURE__ */ Object.create(null),
402
- missing: /* @__PURE__ */ new Set()
403
- };
404
- }
405
- function getStorage(provider, prefix) {
406
- const providerStorage = dataStorage[provider] || (dataStorage[provider] = /* @__PURE__ */ Object.create(null));
407
- return providerStorage[prefix] || (providerStorage[prefix] = newStorage(provider, prefix));
408
- }
409
- function addIconSet(storage, data) {
410
- if (!quicklyValidateIconSet(data)) {
411
- return [];
412
- }
413
- return parseIconSet(data, (name, icon) => {
414
- if (icon) {
415
- storage.icons[name] = icon;
416
- } else {
417
- storage.missing.add(name);
418
- }
419
- });
420
- }
421
- function addIconToStorage(storage, name, icon) {
422
- try {
423
- if (typeof icon.body === "string") {
424
- storage.icons[name] = { ...icon };
425
- return true;
426
- }
427
- } catch (err) {
428
- }
429
- return false;
430
- }
431
-
432
- let simpleNames = false;
433
- function allowSimpleNames(allow) {
434
- if (typeof allow === "boolean") {
435
- simpleNames = allow;
436
- }
437
- return simpleNames;
438
- }
439
- function getIconData(name) {
440
- const icon = typeof name === "string" ? stringToIcon(name, true, simpleNames) : name;
441
- if (icon) {
442
- const storage = getStorage(icon.provider, icon.prefix);
443
- const iconName = icon.name;
444
- return storage.icons[iconName] || (storage.missing.has(iconName) ? null : void 0);
445
- }
446
- }
447
- function addIcon(name, data) {
448
- const icon = stringToIcon(name, true, simpleNames);
449
- if (!icon) {
450
- return false;
451
- }
452
- const storage = getStorage(icon.provider, icon.prefix);
453
- if (data) {
454
- return addIconToStorage(storage, icon.name, data);
455
- } else {
456
- storage.missing.add(icon.name);
457
- return true;
458
- }
459
- }
460
- function addCollection(data, provider) {
461
- if (typeof data !== "object") {
462
- return false;
463
- }
464
- if (typeof provider !== "string") {
465
- provider = data.provider || "";
466
- }
467
- if (simpleNames && !provider && !data.prefix) {
468
- let added = false;
469
- if (quicklyValidateIconSet(data)) {
470
- data.prefix = "";
471
- parseIconSet(data, (name, icon) => {
472
- if (addIcon(name, icon)) {
473
- added = true;
474
- }
475
- });
476
- }
477
- return added;
478
- }
479
- const prefix = data.prefix;
480
- if (!validateIconName({
481
- prefix,
482
- name: "a"
483
- })) {
484
- return false;
485
- }
486
- const storage = getStorage(provider, prefix);
487
- return !!addIconSet(storage, data);
488
- }
489
-
490
- const defaultIconSizeCustomisations = Object.freeze({
491
- width: null,
492
- height: null
493
- });
494
- const defaultIconCustomisations = Object.freeze({
495
- // Dimensions
496
- ...defaultIconSizeCustomisations,
497
- // Transformations
498
- ...defaultIconTransformations
499
- });
500
-
501
- const unitsSplit = /(-?[0-9.]*[0-9]+[0-9.]*)/g;
502
- const unitsTest = /^-?[0-9.]*[0-9]+[0-9.]*$/g;
503
- function calculateSize(size, ratio, precision) {
504
- if (ratio === 1) {
505
- return size;
506
- }
507
- precision = precision || 100;
508
- if (typeof size === "number") {
509
- return Math.ceil(size * ratio * precision) / precision;
510
- }
511
- if (typeof size !== "string") {
512
- return size;
513
- }
514
- const oldParts = size.split(unitsSplit);
515
- if (oldParts === null || !oldParts.length) {
516
- return size;
517
- }
518
- const newParts = [];
519
- let code = oldParts.shift();
520
- let isNumber = unitsTest.test(code);
521
- while (true) {
522
- if (isNumber) {
523
- const num = parseFloat(code);
524
- if (isNaN(num)) {
525
- newParts.push(code);
526
- } else {
527
- newParts.push(Math.ceil(num * ratio * precision) / precision);
528
- }
529
- } else {
530
- newParts.push(code);
531
- }
532
- code = oldParts.shift();
533
- if (code === void 0) {
534
- return newParts.join("");
535
- }
536
- isNumber = !isNumber;
537
- }
538
- }
539
-
540
- function splitSVGDefs(content, tag = "defs") {
541
- let defs = "";
542
- const index = content.indexOf("<" + tag);
543
- while (index >= 0) {
544
- const start = content.indexOf(">", index);
545
- const end = content.indexOf("</" + tag);
546
- if (start === -1 || end === -1) {
547
- break;
548
- }
549
- const endEnd = content.indexOf(">", end);
550
- if (endEnd === -1) {
551
- break;
552
- }
553
- defs += content.slice(start + 1, end).trim();
554
- content = content.slice(0, index).trim() + content.slice(endEnd + 1);
555
- }
556
- return {
557
- defs,
558
- content
559
- };
560
- }
561
- function mergeDefsAndContent(defs, content) {
562
- return defs ? "<defs>" + defs + "</defs>" + content : content;
563
- }
564
- function wrapSVGContent(body, start, end) {
565
- const split = splitSVGDefs(body);
566
- return mergeDefsAndContent(split.defs, start + split.content + end);
567
- }
568
-
569
- const isUnsetKeyword = (value) => value === "unset" || value === "undefined" || value === "none";
570
- function iconToSVG(icon, customisations) {
571
- const fullIcon = {
572
- ...defaultIconProps,
573
- ...icon
574
- };
575
- const fullCustomisations = {
576
- ...defaultIconCustomisations,
577
- ...customisations
578
- };
579
- const box = {
580
- left: fullIcon.left,
581
- top: fullIcon.top,
582
- width: fullIcon.width,
583
- height: fullIcon.height
584
- };
585
- let body = fullIcon.body;
586
- [fullIcon, fullCustomisations].forEach((props) => {
587
- const transformations = [];
588
- const hFlip = props.hFlip;
589
- const vFlip = props.vFlip;
590
- let rotation = props.rotate;
591
- if (hFlip) {
592
- if (vFlip) {
593
- rotation += 2;
594
- } else {
595
- transformations.push(
596
- "translate(" + (box.width + box.left).toString() + " " + (0 - box.top).toString() + ")"
597
- );
598
- transformations.push("scale(-1 1)");
599
- box.top = box.left = 0;
600
- }
601
- } else if (vFlip) {
602
- transformations.push(
603
- "translate(" + (0 - box.left).toString() + " " + (box.height + box.top).toString() + ")"
604
- );
605
- transformations.push("scale(1 -1)");
606
- box.top = box.left = 0;
607
- }
608
- let tempValue;
609
- if (rotation < 0) {
610
- rotation -= Math.floor(rotation / 4) * 4;
611
- }
612
- rotation = rotation % 4;
613
- switch (rotation) {
614
- case 1:
615
- tempValue = box.height / 2 + box.top;
616
- transformations.unshift(
617
- "rotate(90 " + tempValue.toString() + " " + tempValue.toString() + ")"
618
- );
619
- break;
620
- case 2:
621
- transformations.unshift(
622
- "rotate(180 " + (box.width / 2 + box.left).toString() + " " + (box.height / 2 + box.top).toString() + ")"
623
- );
624
- break;
625
- case 3:
626
- tempValue = box.width / 2 + box.left;
627
- transformations.unshift(
628
- "rotate(-90 " + tempValue.toString() + " " + tempValue.toString() + ")"
629
- );
630
- break;
631
- }
632
- if (rotation % 2 === 1) {
633
- if (box.left !== box.top) {
634
- tempValue = box.left;
635
- box.left = box.top;
636
- box.top = tempValue;
637
- }
638
- if (box.width !== box.height) {
639
- tempValue = box.width;
640
- box.width = box.height;
641
- box.height = tempValue;
642
- }
643
- }
644
- if (transformations.length) {
645
- body = wrapSVGContent(
646
- body,
647
- '<g transform="' + transformations.join(" ") + '">',
648
- "</g>"
649
- );
650
- }
651
- });
652
- const customisationsWidth = fullCustomisations.width;
653
- const customisationsHeight = fullCustomisations.height;
654
- const boxWidth = box.width;
655
- const boxHeight = box.height;
656
- let width;
657
- let height;
658
- if (customisationsWidth === null) {
659
- height = customisationsHeight === null ? "1em" : customisationsHeight === "auto" ? boxHeight : customisationsHeight;
660
- width = calculateSize(height, boxWidth / boxHeight);
661
- } else {
662
- width = customisationsWidth === "auto" ? boxWidth : customisationsWidth;
663
- height = customisationsHeight === null ? calculateSize(width, boxHeight / boxWidth) : customisationsHeight === "auto" ? boxHeight : customisationsHeight;
664
- }
665
- const attributes = {};
666
- const setAttr = (prop, value) => {
667
- if (!isUnsetKeyword(value)) {
668
- attributes[prop] = value.toString();
669
- }
670
- };
671
- setAttr("width", width);
672
- setAttr("height", height);
673
- const viewBox = [box.left, box.top, boxWidth, boxHeight];
674
- attributes.viewBox = viewBox.join(" ");
675
- return {
676
- attributes,
677
- viewBox,
678
- body
679
- };
680
- }
681
-
682
- const regex = /\sid="(\S+)"/g;
683
- const randomPrefix = "IconifyId" + Date.now().toString(16) + (Math.random() * 16777216 | 0).toString(16);
684
- let counter = 0;
685
- function replaceIDs(body, prefix = randomPrefix) {
686
- const ids = [];
687
- let match;
688
- while (match = regex.exec(body)) {
689
- ids.push(match[1]);
690
- }
691
- if (!ids.length) {
692
- return body;
693
- }
694
- const suffix = "suffix" + (Math.random() * 16777216 | Date.now()).toString(16);
695
- ids.forEach((id) => {
696
- const newID = typeof prefix === "function" ? prefix(id) : prefix + (counter++).toString();
697
- const escapedID = id.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
698
- body = body.replace(
699
- // Allowed characters before id: [#;"]
700
- // Allowed characters after id: [)"], .[a-z]
701
- new RegExp('([#;"])(' + escapedID + ')([")]|\\.[a-z])', "g"),
702
- "$1" + newID + suffix + "$3"
703
- );
704
- });
705
- body = body.replace(new RegExp(suffix, "g"), "");
706
- return body;
707
- }
708
-
709
- const storage = /* @__PURE__ */ Object.create(null);
710
- function setAPIModule(provider, item) {
711
- storage[provider] = item;
712
- }
713
- function getAPIModule(provider) {
714
- return storage[provider] || storage[""];
715
- }
716
-
717
- function createAPIConfig(source) {
718
- let resources;
719
- if (typeof source.resources === "string") {
720
- resources = [source.resources];
721
- } else {
722
- resources = source.resources;
723
- if (!(resources instanceof Array) || !resources.length) {
724
- return null;
725
- }
726
- }
727
- const result = {
728
- // API hosts
729
- resources,
730
- // Root path
731
- path: source.path || "/",
732
- // URL length limit
733
- maxURL: source.maxURL || 500,
734
- // Timeout before next host is used.
735
- rotate: source.rotate || 750,
736
- // Timeout before failing query.
737
- timeout: source.timeout || 5e3,
738
- // Randomise default API end point.
739
- random: source.random === true,
740
- // Start index
741
- index: source.index || 0,
742
- // Receive data after time out (used if time out kicks in first, then API module sends data anyway).
743
- dataAfterTimeout: source.dataAfterTimeout !== false
744
- };
745
- return result;
746
- }
747
- const configStorage = /* @__PURE__ */ Object.create(null);
748
- const fallBackAPISources = [
749
- "https://api.simplesvg.com",
750
- "https://api.unisvg.com"
751
- ];
752
- const fallBackAPI = [];
753
- while (fallBackAPISources.length > 0) {
754
- if (fallBackAPISources.length === 1) {
755
- fallBackAPI.push(fallBackAPISources.shift());
756
- } else {
757
- if (Math.random() > 0.5) {
758
- fallBackAPI.push(fallBackAPISources.shift());
759
- } else {
760
- fallBackAPI.push(fallBackAPISources.pop());
761
- }
762
- }
763
- }
764
- configStorage[""] = createAPIConfig({
765
- resources: ["https://api.iconify.design"].concat(fallBackAPI)
766
- });
767
- function addAPIProvider(provider, customConfig) {
768
- const config = createAPIConfig(customConfig);
769
- if (config === null) {
770
- return false;
771
- }
772
- configStorage[provider] = config;
773
- return true;
774
- }
775
- function getAPIConfig(provider) {
776
- return configStorage[provider];
777
- }
778
-
779
- const detectFetch = () => {
780
- let callback;
781
- try {
782
- callback = fetch;
783
- if (typeof callback === "function") {
784
- return callback;
785
- }
786
- } catch (err) {
787
- }
788
- };
789
- let fetchModule = detectFetch();
790
- function calculateMaxLength(provider, prefix) {
791
- const config = getAPIConfig(provider);
792
- if (!config) {
793
- return 0;
794
- }
795
- let result;
796
- if (!config.maxURL) {
797
- result = 0;
798
- } else {
799
- let maxHostLength = 0;
800
- config.resources.forEach((item) => {
801
- const host = item;
802
- maxHostLength = Math.max(maxHostLength, host.length);
803
- });
804
- const url = prefix + ".json?icons=";
805
- result = config.maxURL - maxHostLength - config.path.length - url.length;
806
- }
807
- return result;
808
- }
809
- function shouldAbort(status) {
810
- return status === 404;
811
- }
812
- const prepare = (provider, prefix, icons) => {
813
- const results = [];
814
- const maxLength = calculateMaxLength(provider, prefix);
815
- const type = "icons";
816
- let item = {
817
- type,
818
- provider,
819
- prefix,
820
- icons: []
821
- };
822
- let length = 0;
823
- icons.forEach((name, index) => {
824
- length += name.length + 1;
825
- if (length >= maxLength && index > 0) {
826
- results.push(item);
827
- item = {
828
- type,
829
- provider,
830
- prefix,
831
- icons: []
832
- };
833
- length = name.length;
834
- }
835
- item.icons.push(name);
836
- });
837
- results.push(item);
838
- return results;
839
- };
840
- function getPath(provider) {
841
- if (typeof provider === "string") {
842
- const config = getAPIConfig(provider);
843
- if (config) {
844
- return config.path;
845
- }
846
- }
847
- return "/";
848
- }
849
- const send = (host, params, callback) => {
850
- if (!fetchModule) {
851
- callback("abort", 424);
852
- return;
853
- }
854
- let path = getPath(params.provider);
855
- switch (params.type) {
856
- case "icons": {
857
- const prefix = params.prefix;
858
- const icons = params.icons;
859
- const iconsList = icons.join(",");
860
- const urlParams = new URLSearchParams({
861
- icons: iconsList
862
- });
863
- path += prefix + ".json?" + urlParams.toString();
864
- break;
865
- }
866
- case "custom": {
867
- const uri = params.uri;
868
- path += uri.slice(0, 1) === "/" ? uri.slice(1) : uri;
869
- break;
870
- }
871
- default:
872
- callback("abort", 400);
873
- return;
874
- }
875
- let defaultError = 503;
876
- fetchModule(host + path).then((response) => {
877
- const status = response.status;
878
- if (status !== 200) {
879
- setTimeout(() => {
880
- callback(shouldAbort(status) ? "abort" : "next", status);
881
- });
882
- return;
883
- }
884
- defaultError = 501;
885
- return response.json();
886
- }).then((data) => {
887
- if (typeof data !== "object" || data === null) {
888
- setTimeout(() => {
889
- if (data === 404) {
890
- callback("abort", data);
891
- } else {
892
- callback("next", defaultError);
893
- }
894
- });
895
- return;
896
- }
897
- setTimeout(() => {
898
- callback("success", data);
899
- });
900
- }).catch(() => {
901
- callback("next", defaultError);
902
- });
903
- };
904
- const fetchAPIModule = {
905
- prepare,
906
- send
907
- };
908
-
909
- function sortIcons(icons) {
910
- const result = {
911
- loaded: [],
912
- missing: [],
913
- pending: []
914
- };
915
- const storage = /* @__PURE__ */ Object.create(null);
916
- icons.sort((a, b) => {
917
- if (a.provider !== b.provider) {
918
- return a.provider.localeCompare(b.provider);
919
- }
920
- if (a.prefix !== b.prefix) {
921
- return a.prefix.localeCompare(b.prefix);
922
- }
923
- return a.name.localeCompare(b.name);
924
- });
925
- let lastIcon = {
926
- provider: "",
927
- prefix: "",
928
- name: ""
929
- };
930
- icons.forEach((icon) => {
931
- if (lastIcon.name === icon.name && lastIcon.prefix === icon.prefix && lastIcon.provider === icon.provider) {
932
- return;
933
- }
934
- lastIcon = icon;
935
- const provider = icon.provider;
936
- const prefix = icon.prefix;
937
- const name = icon.name;
938
- const providerStorage = storage[provider] || (storage[provider] = /* @__PURE__ */ Object.create(null));
939
- const localStorage = providerStorage[prefix] || (providerStorage[prefix] = getStorage(provider, prefix));
940
- let list;
941
- if (name in localStorage.icons) {
942
- list = result.loaded;
943
- } else if (prefix === "" || localStorage.missing.has(name)) {
944
- list = result.missing;
945
- } else {
946
- list = result.pending;
947
- }
948
- const item = {
949
- provider,
950
- prefix,
951
- name
952
- };
953
- list.push(item);
954
- });
955
- return result;
956
- }
957
-
958
- function removeCallback(storages, id) {
959
- storages.forEach((storage) => {
960
- const items = storage.loaderCallbacks;
961
- if (items) {
962
- storage.loaderCallbacks = items.filter((row) => row.id !== id);
963
- }
964
- });
965
- }
966
- function updateCallbacks(storage) {
967
- if (!storage.pendingCallbacksFlag) {
968
- storage.pendingCallbacksFlag = true;
969
- setTimeout(() => {
970
- storage.pendingCallbacksFlag = false;
971
- const items = storage.loaderCallbacks ? storage.loaderCallbacks.slice(0) : [];
972
- if (!items.length) {
973
- return;
974
- }
975
- let hasPending = false;
976
- const provider = storage.provider;
977
- const prefix = storage.prefix;
978
- items.forEach((item) => {
979
- const icons = item.icons;
980
- const oldLength = icons.pending.length;
981
- icons.pending = icons.pending.filter((icon) => {
982
- if (icon.prefix !== prefix) {
983
- return true;
984
- }
985
- const name = icon.name;
986
- if (storage.icons[name]) {
987
- icons.loaded.push({
988
- provider,
989
- prefix,
990
- name
991
- });
992
- } else if (storage.missing.has(name)) {
993
- icons.missing.push({
994
- provider,
995
- prefix,
996
- name
997
- });
998
- } else {
999
- hasPending = true;
1000
- return true;
1001
- }
1002
- return false;
1003
- });
1004
- if (icons.pending.length !== oldLength) {
1005
- if (!hasPending) {
1006
- removeCallback([storage], item.id);
1007
- }
1008
- item.callback(
1009
- icons.loaded.slice(0),
1010
- icons.missing.slice(0),
1011
- icons.pending.slice(0),
1012
- item.abort
1013
- );
1014
- }
1015
- });
1016
- });
1017
- }
1018
- }
1019
- let idCounter = 0;
1020
- function storeCallback(callback, icons, pendingSources) {
1021
- const id = idCounter++;
1022
- const abort = removeCallback.bind(null, pendingSources, id);
1023
- if (!icons.pending.length) {
1024
- return abort;
1025
- }
1026
- const item = {
1027
- id,
1028
- icons,
1029
- callback,
1030
- abort
1031
- };
1032
- pendingSources.forEach((storage) => {
1033
- (storage.loaderCallbacks || (storage.loaderCallbacks = [])).push(item);
1034
- });
1035
- return abort;
1036
- }
1037
-
1038
- function listToIcons(list, validate = true, simpleNames = false) {
1039
- const result = [];
1040
- list.forEach((item) => {
1041
- const icon = typeof item === "string" ? stringToIcon(item, validate, simpleNames) : item;
1042
- if (icon) {
1043
- result.push(icon);
1044
- }
1045
- });
1046
- return result;
1047
- }
1048
-
1049
- // src/config.ts
1050
- var defaultConfig = {
1051
- resources: [],
1052
- index: 0,
1053
- timeout: 2e3,
1054
- rotate: 750,
1055
- random: false,
1056
- dataAfterTimeout: false
1057
- };
1058
-
1059
- // src/query.ts
1060
- function sendQuery(config, payload, query, done) {
1061
- const resourcesCount = config.resources.length;
1062
- const startIndex = config.random ? Math.floor(Math.random() * resourcesCount) : config.index;
1063
- let resources;
1064
- if (config.random) {
1065
- let list = config.resources.slice(0);
1066
- resources = [];
1067
- while (list.length > 1) {
1068
- const nextIndex = Math.floor(Math.random() * list.length);
1069
- resources.push(list[nextIndex]);
1070
- list = list.slice(0, nextIndex).concat(list.slice(nextIndex + 1));
1071
- }
1072
- resources = resources.concat(list);
1073
- } else {
1074
- resources = config.resources.slice(startIndex).concat(config.resources.slice(0, startIndex));
1075
- }
1076
- const startTime = Date.now();
1077
- let status = "pending";
1078
- let queriesSent = 0;
1079
- let lastError;
1080
- let timer = null;
1081
- let queue = [];
1082
- let doneCallbacks = [];
1083
- if (typeof done === "function") {
1084
- doneCallbacks.push(done);
1085
- }
1086
- function resetTimer() {
1087
- if (timer) {
1088
- clearTimeout(timer);
1089
- timer = null;
1090
- }
1091
- }
1092
- function abort() {
1093
- if (status === "pending") {
1094
- status = "aborted";
1095
- }
1096
- resetTimer();
1097
- queue.forEach((item) => {
1098
- if (item.status === "pending") {
1099
- item.status = "aborted";
1100
- }
1101
- });
1102
- queue = [];
1103
- }
1104
- function subscribe(callback, overwrite) {
1105
- if (overwrite) {
1106
- doneCallbacks = [];
1107
- }
1108
- if (typeof callback === "function") {
1109
- doneCallbacks.push(callback);
1110
- }
1111
- }
1112
- function getQueryStatus() {
1113
- return {
1114
- startTime,
1115
- payload,
1116
- status,
1117
- queriesSent,
1118
- queriesPending: queue.length,
1119
- subscribe,
1120
- abort
1121
- };
1122
- }
1123
- function failQuery() {
1124
- status = "failed";
1125
- doneCallbacks.forEach((callback) => {
1126
- callback(void 0, lastError);
1127
- });
1128
- }
1129
- function clearQueue() {
1130
- queue.forEach((item) => {
1131
- if (item.status === "pending") {
1132
- item.status = "aborted";
1133
- }
1134
- });
1135
- queue = [];
1136
- }
1137
- function moduleResponse(item, response, data) {
1138
- const isError = response !== "success";
1139
- queue = queue.filter((queued) => queued !== item);
1140
- switch (status) {
1141
- case "pending":
1142
- break;
1143
- case "failed":
1144
- if (isError || !config.dataAfterTimeout) {
1145
- return;
1146
- }
1147
- break;
1148
- default:
1149
- return;
1150
- }
1151
- if (response === "abort") {
1152
- lastError = data;
1153
- failQuery();
1154
- return;
1155
- }
1156
- if (isError) {
1157
- lastError = data;
1158
- if (!queue.length) {
1159
- if (!resources.length) {
1160
- failQuery();
1161
- } else {
1162
- execNext();
1163
- }
1164
- }
1165
- return;
1166
- }
1167
- resetTimer();
1168
- clearQueue();
1169
- if (!config.random) {
1170
- const index = config.resources.indexOf(item.resource);
1171
- if (index !== -1 && index !== config.index) {
1172
- config.index = index;
1173
- }
1174
- }
1175
- status = "completed";
1176
- doneCallbacks.forEach((callback) => {
1177
- callback(data);
1178
- });
1179
- }
1180
- function execNext() {
1181
- if (status !== "pending") {
1182
- return;
1183
- }
1184
- resetTimer();
1185
- const resource = resources.shift();
1186
- if (resource === void 0) {
1187
- if (queue.length) {
1188
- timer = setTimeout(() => {
1189
- resetTimer();
1190
- if (status === "pending") {
1191
- clearQueue();
1192
- failQuery();
1193
- }
1194
- }, config.timeout);
1195
- return;
1196
- }
1197
- failQuery();
1198
- return;
1199
- }
1200
- const item = {
1201
- status: "pending",
1202
- resource,
1203
- callback: (status2, data) => {
1204
- moduleResponse(item, status2, data);
1205
- }
1206
- };
1207
- queue.push(item);
1208
- queriesSent++;
1209
- timer = setTimeout(execNext, config.rotate);
1210
- query(resource, payload, item.callback);
1211
- }
1212
- setTimeout(execNext);
1213
- return getQueryStatus;
1214
- }
1215
-
1216
- // src/index.ts
1217
- function initRedundancy(cfg) {
1218
- const config = {
1219
- ...defaultConfig,
1220
- ...cfg
1221
- };
1222
- let queries = [];
1223
- function cleanup() {
1224
- queries = queries.filter((item) => item().status === "pending");
1225
- }
1226
- function query(payload, queryCallback, doneCallback) {
1227
- const query2 = sendQuery(
1228
- config,
1229
- payload,
1230
- queryCallback,
1231
- (data, error) => {
1232
- cleanup();
1233
- if (doneCallback) {
1234
- doneCallback(data, error);
1235
- }
1236
- }
1237
- );
1238
- queries.push(query2);
1239
- return query2;
1240
- }
1241
- function find(callback) {
1242
- return queries.find((value) => {
1243
- return callback(value);
1244
- }) || null;
1245
- }
1246
- const instance = {
1247
- query,
1248
- find,
1249
- setIndex: (index) => {
1250
- config.index = index;
1251
- },
1252
- getIndex: () => config.index,
1253
- cleanup
1254
- };
1255
- return instance;
1256
- }
1257
-
1258
- function emptyCallback$1() {
1259
- }
1260
- const redundancyCache = /* @__PURE__ */ Object.create(null);
1261
- function getRedundancyCache(provider) {
1262
- if (!redundancyCache[provider]) {
1263
- const config = getAPIConfig(provider);
1264
- if (!config) {
1265
- return;
1266
- }
1267
- const redundancy = initRedundancy(config);
1268
- const cachedReundancy = {
1269
- config,
1270
- redundancy
1271
- };
1272
- redundancyCache[provider] = cachedReundancy;
1273
- }
1274
- return redundancyCache[provider];
1275
- }
1276
- function sendAPIQuery(target, query, callback) {
1277
- let redundancy;
1278
- let send;
1279
- if (typeof target === "string") {
1280
- const api = getAPIModule(target);
1281
- if (!api) {
1282
- callback(void 0, 424);
1283
- return emptyCallback$1;
1284
- }
1285
- send = api.send;
1286
- const cached = getRedundancyCache(target);
1287
- if (cached) {
1288
- redundancy = cached.redundancy;
1289
- }
1290
- } else {
1291
- const config = createAPIConfig(target);
1292
- if (config) {
1293
- redundancy = initRedundancy(config);
1294
- const moduleKey = target.resources ? target.resources[0] : "";
1295
- const api = getAPIModule(moduleKey);
1296
- if (api) {
1297
- send = api.send;
1298
- }
1299
- }
1300
- }
1301
- if (!redundancy || !send) {
1302
- callback(void 0, 424);
1303
- return emptyCallback$1;
1304
- }
1305
- return redundancy.query(query, send, callback)().abort;
1306
- }
1307
-
1308
- function emptyCallback() {
1309
- }
1310
- function loadedNewIcons(storage) {
1311
- if (!storage.iconsLoaderFlag) {
1312
- storage.iconsLoaderFlag = true;
1313
- setTimeout(() => {
1314
- storage.iconsLoaderFlag = false;
1315
- updateCallbacks(storage);
1316
- });
1317
- }
1318
- }
1319
- function checkIconNamesForAPI(icons) {
1320
- const valid = [];
1321
- const invalid = [];
1322
- icons.forEach((name) => {
1323
- (name.match(matchIconName) ? valid : invalid).push(name);
1324
- });
1325
- return {
1326
- valid,
1327
- invalid
1328
- };
1329
- }
1330
- function parseLoaderResponse(storage, icons, data) {
1331
- function checkMissing() {
1332
- const pending = storage.pendingIcons;
1333
- icons.forEach((name) => {
1334
- if (pending) {
1335
- pending.delete(name);
1336
- }
1337
- if (!storage.icons[name]) {
1338
- storage.missing.add(name);
1339
- }
1340
- });
1341
- }
1342
- if (data && typeof data === "object") {
1343
- try {
1344
- const parsed = addIconSet(storage, data);
1345
- if (!parsed.length) {
1346
- checkMissing();
1347
- return;
1348
- }
1349
- } catch (err) {
1350
- console.error(err);
1351
- }
1352
- }
1353
- checkMissing();
1354
- loadedNewIcons(storage);
1355
- }
1356
- function parsePossiblyAsyncResponse(response, callback) {
1357
- if (response instanceof Promise) {
1358
- response.then((data) => {
1359
- callback(data);
1360
- }).catch(() => {
1361
- callback(null);
1362
- });
1363
- } else {
1364
- callback(response);
1365
- }
1366
- }
1367
- function loadNewIcons(storage, icons) {
1368
- if (!storage.iconsToLoad) {
1369
- storage.iconsToLoad = icons;
1370
- } else {
1371
- storage.iconsToLoad = storage.iconsToLoad.concat(icons).sort();
1372
- }
1373
- if (!storage.iconsQueueFlag) {
1374
- storage.iconsQueueFlag = true;
1375
- setTimeout(() => {
1376
- storage.iconsQueueFlag = false;
1377
- const { provider, prefix } = storage;
1378
- const icons2 = storage.iconsToLoad;
1379
- delete storage.iconsToLoad;
1380
- if (!icons2 || !icons2.length) {
1381
- return;
1382
- }
1383
- const customIconLoader = storage.loadIcon;
1384
- if (storage.loadIcons && (icons2.length > 1 || !customIconLoader)) {
1385
- parsePossiblyAsyncResponse(
1386
- storage.loadIcons(icons2, prefix, provider),
1387
- (data) => {
1388
- parseLoaderResponse(storage, icons2, data);
1389
- }
1390
- );
1391
- return;
1392
- }
1393
- if (customIconLoader) {
1394
- icons2.forEach((name) => {
1395
- const response = customIconLoader(name, prefix, provider);
1396
- parsePossiblyAsyncResponse(response, (data) => {
1397
- const iconSet = data ? {
1398
- prefix,
1399
- icons: {
1400
- [name]: data
1401
- }
1402
- } : null;
1403
- parseLoaderResponse(storage, [name], iconSet);
1404
- });
1405
- });
1406
- return;
1407
- }
1408
- const { valid, invalid } = checkIconNamesForAPI(icons2);
1409
- if (invalid.length) {
1410
- parseLoaderResponse(storage, invalid, null);
1411
- }
1412
- if (!valid.length) {
1413
- return;
1414
- }
1415
- const api = prefix.match(matchIconName) ? getAPIModule(provider) : null;
1416
- if (!api) {
1417
- parseLoaderResponse(storage, valid, null);
1418
- return;
1419
- }
1420
- const params = api.prepare(provider, prefix, valid);
1421
- params.forEach((item) => {
1422
- sendAPIQuery(provider, item, (data) => {
1423
- parseLoaderResponse(storage, item.icons, data);
1424
- });
1425
- });
1426
- });
1427
- }
1428
- }
1429
- const loadIcons = (icons, callback) => {
1430
- const cleanedIcons = listToIcons(icons, true, allowSimpleNames());
1431
- const sortedIcons = sortIcons(cleanedIcons);
1432
- if (!sortedIcons.pending.length) {
1433
- let callCallback = true;
1434
- if (callback) {
1435
- setTimeout(() => {
1436
- if (callCallback) {
1437
- callback(
1438
- sortedIcons.loaded,
1439
- sortedIcons.missing,
1440
- sortedIcons.pending,
1441
- emptyCallback
1442
- );
1443
- }
1444
- });
1445
- }
1446
- return () => {
1447
- callCallback = false;
1448
- };
1449
- }
1450
- const newIcons = /* @__PURE__ */ Object.create(null);
1451
- const sources = [];
1452
- let lastProvider, lastPrefix;
1453
- sortedIcons.pending.forEach((icon) => {
1454
- const { provider, prefix } = icon;
1455
- if (prefix === lastPrefix && provider === lastProvider) {
1456
- return;
1457
- }
1458
- lastProvider = provider;
1459
- lastPrefix = prefix;
1460
- sources.push(getStorage(provider, prefix));
1461
- const providerNewIcons = newIcons[provider] || (newIcons[provider] = /* @__PURE__ */ Object.create(null));
1462
- if (!providerNewIcons[prefix]) {
1463
- providerNewIcons[prefix] = [];
1464
- }
1465
- });
1466
- sortedIcons.pending.forEach((icon) => {
1467
- const { provider, prefix, name } = icon;
1468
- const storage = getStorage(provider, prefix);
1469
- const pendingQueue = storage.pendingIcons || (storage.pendingIcons = /* @__PURE__ */ new Set());
1470
- if (!pendingQueue.has(name)) {
1471
- pendingQueue.add(name);
1472
- newIcons[provider][prefix].push(name);
1473
- }
1474
- });
1475
- sources.forEach((storage) => {
1476
- const list = newIcons[storage.provider][storage.prefix];
1477
- if (list.length) {
1478
- loadNewIcons(storage, list);
1479
- }
1480
- });
1481
- return callback ? storeCallback(callback, sortedIcons, sources) : emptyCallback;
1482
- };
1483
-
1484
- function mergeCustomisations(defaults, item) {
1485
- const result = {
1486
- ...defaults
1487
- };
1488
- for (const key in item) {
1489
- const value = item[key];
1490
- const valueType = typeof value;
1491
- if (key in defaultIconSizeCustomisations) {
1492
- if (value === null || value && (valueType === "string" || valueType === "number")) {
1493
- result[key] = value;
1494
- }
1495
- } else if (valueType === typeof result[key]) {
1496
- result[key] = key === "rotate" ? value % 4 : value;
1497
- }
1498
- }
1499
- return result;
1500
- }
1501
-
1502
- const separator = /[\s,]+/;
1503
- function flipFromString(custom, flip) {
1504
- flip.split(separator).forEach((str) => {
1505
- const value = str.trim();
1506
- switch (value) {
1507
- case "horizontal":
1508
- custom.hFlip = true;
1509
- break;
1510
- case "vertical":
1511
- custom.vFlip = true;
1512
- break;
1513
- }
1514
- });
1515
- }
1516
-
1517
- function rotateFromString(value, defaultValue = 0) {
1518
- const units = value.replace(/^-?[0-9.]*/, "");
1519
- function cleanup(value2) {
1520
- while (value2 < 0) {
1521
- value2 += 4;
1522
- }
1523
- return value2 % 4;
1524
- }
1525
- if (units === "") {
1526
- const num = parseInt(value);
1527
- return isNaN(num) ? 0 : cleanup(num);
1528
- } else if (units !== value) {
1529
- let split = 0;
1530
- switch (units) {
1531
- case "%":
1532
- split = 25;
1533
- break;
1534
- case "deg":
1535
- split = 90;
1536
- }
1537
- if (split) {
1538
- let num = parseFloat(value.slice(0, value.length - units.length));
1539
- if (isNaN(num)) {
1540
- return 0;
1541
- }
1542
- num = num / split;
1543
- return num % 1 === 0 ? cleanup(num) : 0;
1544
- }
1545
- }
1546
- return defaultValue;
1547
- }
1548
-
1549
- function iconToHTML(body, attributes) {
1550
- let renderAttribsHTML = body.indexOf("xlink:") === -1 ? "" : ' xmlns:xlink="http://www.w3.org/1999/xlink"';
1551
- for (const attr in attributes) {
1552
- renderAttribsHTML += " " + attr + '="' + attributes[attr] + '"';
1553
- }
1554
- return '<svg xmlns="http://www.w3.org/2000/svg"' + renderAttribsHTML + ">" + body + "</svg>";
1555
- }
1556
-
1557
- function encodeSVGforURL(svg) {
1558
- return svg.replace(/"/g, "'").replace(/%/g, "%25").replace(/#/g, "%23").replace(/</g, "%3C").replace(/>/g, "%3E").replace(/\s+/g, " ");
1559
- }
1560
- function svgToData(svg) {
1561
- return "data:image/svg+xml," + encodeSVGforURL(svg);
1562
- }
1563
- function svgToURL(svg) {
1564
- return 'url("' + svgToData(svg) + '")';
1565
- }
1566
-
1567
- let policy;
1568
- function createPolicy() {
1569
- try {
1570
- policy = window.trustedTypes.createPolicy("iconify", {
1571
- // eslint-disable-next-line @typescript-eslint/no-unsafe-return
1572
- createHTML: (s) => s
1573
- });
1574
- } catch (err) {
1575
- policy = null;
1576
- }
1577
- }
1578
- function cleanUpInnerHTML(html) {
1579
- if (policy === void 0) {
1580
- createPolicy();
1581
- }
1582
- return policy ? policy.createHTML(html) : html;
1583
- }
1584
-
1585
- const defaultExtendedIconCustomisations = {
1586
- ...defaultIconCustomisations,
1587
- inline: false,
1588
- };
1589
-
1590
- /**
1591
- * Default SVG attributes
1592
- */
1593
- const svgDefaults = {
1594
- 'xmlns': 'http://www.w3.org/2000/svg',
1595
- 'xmlnsXlink': 'http://www.w3.org/1999/xlink',
1596
- 'aria-hidden': true,
1597
- 'role': 'img',
1598
- };
1599
- /**
1600
- * Style modes
1601
- */
1602
- const commonProps = {
1603
- display: 'inline-block',
1604
- };
1605
- const monotoneProps = {
1606
- backgroundColor: 'currentColor',
1607
- };
1608
- const coloredProps = {
1609
- backgroundColor: 'transparent',
1610
- };
1611
- // Dynamically add common props to variables above
1612
- const propsToAdd = {
1613
- Image: 'var(--svg)',
1614
- Repeat: 'no-repeat',
1615
- Size: '100% 100%',
1616
- };
1617
- const propsToAddTo = {
1618
- WebkitMask: monotoneProps,
1619
- mask: monotoneProps,
1620
- background: coloredProps,
1621
- };
1622
- for (const prefix in propsToAddTo) {
1623
- const list = propsToAddTo[prefix];
1624
- for (const prop in propsToAdd) {
1625
- list[prefix + prop] = propsToAdd[prop];
1626
- }
1627
- }
1628
- /**
1629
- * Default values for customisations for inline icon
1630
- */
1631
- const inlineDefaults = {
1632
- ...defaultExtendedIconCustomisations,
1633
- inline: true,
1634
- };
1635
- /**
1636
- * Fix size: add 'px' to numbers
1637
- */
1638
- function fixSize(value) {
1639
- return value + (value.match(/^[-0-9.]+$/) ? 'px' : '');
1640
- }
1641
- /**
1642
- * Render icon
1643
- */
1644
- const render = (
1645
- // Icon must be validated before calling this function
1646
- icon,
1647
- // Partial properties
1648
- props,
1649
- // Icon name
1650
- name) => {
1651
- // Get default properties
1652
- const defaultProps = props.inline
1653
- ? inlineDefaults
1654
- : defaultExtendedIconCustomisations;
1655
- // Get all customisations
1656
- const customisations = mergeCustomisations(defaultProps, props);
1657
- // Check mode
1658
- const mode = props.mode || 'svg';
1659
- // Create style
1660
- const style = {};
1661
- const customStyle = props.style || {};
1662
- // Create SVG component properties
1663
- const componentProps = {
1664
- ...(mode === 'svg' ? svgDefaults : {}),
1665
- };
1666
- if (name) {
1667
- const iconName = stringToIcon(name, false, true);
1668
- if (iconName) {
1669
- const classNames = ['iconify'];
1670
- const props = [
1671
- 'provider',
1672
- 'prefix',
1673
- ];
1674
- for (const prop of props) {
1675
- if (iconName[prop]) {
1676
- classNames.push('iconify--' + iconName[prop]);
1677
- }
1678
- }
1679
- componentProps.className = classNames.join(' ');
1680
- }
1681
- }
1682
- // Get element properties
1683
- for (let key in props) {
1684
- const value = props[key];
1685
- if (value === void 0) {
1686
- continue;
1687
- }
1688
- switch (key) {
1689
- // Properties to ignore
1690
- case 'icon':
1691
- case 'style':
1692
- case 'children':
1693
- case 'onLoad':
1694
- case 'mode':
1695
- case 'ssr':
1696
- break;
1697
- // Forward ref
1698
- case '_ref':
1699
- componentProps.ref = value;
1700
- break;
1701
- // Merge class names
1702
- case 'className':
1703
- componentProps[key] =
1704
- (componentProps[key] ? componentProps[key] + ' ' : '') +
1705
- value;
1706
- break;
1707
- // Boolean attributes
1708
- case 'inline':
1709
- case 'hFlip':
1710
- case 'vFlip':
1711
- customisations[key] =
1712
- value === true || value === 'true' || value === 1;
1713
- break;
1714
- // Flip as string: 'horizontal,vertical'
1715
- case 'flip':
1716
- if (typeof value === 'string') {
1717
- flipFromString(customisations, value);
1718
- }
1719
- break;
1720
- // Color: copy to style
1721
- case 'color':
1722
- style.color = value;
1723
- break;
1724
- // Rotation as string
1725
- case 'rotate':
1726
- if (typeof value === 'string') {
1727
- customisations[key] = rotateFromString(value);
1728
- }
1729
- else if (typeof value === 'number') {
1730
- customisations[key] = value;
1731
- }
1732
- break;
1733
- // Remove aria-hidden
1734
- case 'ariaHidden':
1735
- case 'aria-hidden':
1736
- if (value !== true && value !== 'true') {
1737
- delete componentProps['aria-hidden'];
1738
- }
1739
- break;
1740
- // Copy missing property if it does not exist in customisations
1741
- default:
1742
- if (defaultProps[key] === void 0) {
1743
- componentProps[key] = value;
1744
- }
1745
- }
1746
- }
1747
- // Generate icon
1748
- const item = iconToSVG(icon, customisations);
1749
- const renderAttribs = item.attributes;
1750
- // Inline display
1751
- if (customisations.inline) {
1752
- style.verticalAlign = '-0.125em';
1753
- }
1754
- if (mode === 'svg') {
1755
- // Add style
1756
- componentProps.style = {
1757
- ...style,
1758
- ...customStyle,
1759
- };
1760
- // Add icon stuff
1761
- Object.assign(componentProps, renderAttribs);
1762
- // Counter for ids based on "id" property to render icons consistently on server and client
1763
- let localCounter = 0;
1764
- let id = props.id;
1765
- if (typeof id === 'string') {
1766
- // Convert '-' to '_' to avoid errors in animations
1767
- id = id.replace(/-/g, '_');
1768
- }
1769
- // Add icon stuff
1770
- componentProps.dangerouslySetInnerHTML = {
1771
- __html: cleanUpInnerHTML(replaceIDs(item.body, id ? () => id + 'ID' + localCounter++ : 'iconifyReact')),
1772
- };
1773
- return react.createElement('svg', componentProps);
1774
- }
1775
- // Render <span> with style
1776
- const { body, width, height } = icon;
1777
- const useMask = mode === 'mask' ||
1778
- (mode === 'bg' ? false : body.indexOf('currentColor') !== -1);
1779
- // Generate SVG
1780
- const html = iconToHTML(body, {
1781
- ...renderAttribs,
1782
- width: width + '',
1783
- height: height + '',
1784
- });
1785
- // Generate style
1786
- componentProps.style = {
1787
- ...style,
1788
- '--svg': svgToURL(html),
1789
- 'width': fixSize(renderAttribs.width),
1790
- 'height': fixSize(renderAttribs.height),
1791
- ...commonProps,
1792
- ...(useMask ? monotoneProps : coloredProps),
1793
- ...customStyle,
1794
- };
1795
- return react.createElement('span', componentProps);
1796
- };
1797
-
1798
- /**
1799
- * Initialise stuff
1800
- */
1801
- // Enable short names
1802
- allowSimpleNames(true);
1803
- // Set API module
1804
- setAPIModule('', fetchAPIModule);
1805
- /**
1806
- * Browser stuff
1807
- */
1808
- if (typeof document !== 'undefined' && typeof window !== 'undefined') {
1809
- const _window = window;
1810
- // Load icons from global "IconifyPreload"
1811
- if (_window.IconifyPreload !== void 0) {
1812
- const preload = _window.IconifyPreload;
1813
- const err = 'Invalid IconifyPreload syntax.';
1814
- if (typeof preload === 'object' && preload !== null) {
1815
- (preload instanceof Array ? preload : [preload]).forEach((item) => {
1816
- try {
1817
- if (
1818
- // Check if item is an object and not null/array
1819
- typeof item !== 'object' ||
1820
- item === null ||
1821
- item instanceof Array ||
1822
- // Check for 'icons' and 'prefix'
1823
- typeof item.icons !== 'object' ||
1824
- typeof item.prefix !== 'string' ||
1825
- // Add icon set
1826
- !addCollection(item)) {
1827
- console.error(err);
1828
- }
1829
- }
1830
- catch (e) {
1831
- console.error(err);
1832
- }
1833
- });
1834
- }
1835
- }
1836
- // Set API from global "IconifyProviders"
1837
- if (_window.IconifyProviders !== void 0) {
1838
- const providers = _window.IconifyProviders;
1839
- if (typeof providers === 'object' && providers !== null) {
1840
- for (let key in providers) {
1841
- const err = 'IconifyProviders[' + key + '] is invalid.';
1842
- try {
1843
- const value = providers[key];
1844
- if (typeof value !== 'object' ||
1845
- !value ||
1846
- value.resources === void 0) {
1847
- continue;
1848
- }
1849
- if (!addAPIProvider(key, value)) {
1850
- console.error(err);
1851
- }
1852
- }
1853
- catch (e) {
1854
- console.error(err);
1855
- }
1856
- }
1857
- }
1858
- }
1859
- }
1860
- function IconComponent(props) {
1861
- const [mounted, setMounted] = react.useState(!!props.ssr);
1862
- const [abort, setAbort] = react.useState({});
1863
- // Get initial state
1864
- function getInitialState(mounted) {
1865
- if (mounted) {
1866
- const name = props.icon;
1867
- if (typeof name === 'object') {
1868
- // Icon as object
1869
- return {
1870
- name: '',
1871
- data: name,
1872
- };
1873
- }
1874
- const data = getIconData(name);
1875
- if (data) {
1876
- return {
1877
- name,
1878
- data,
1879
- };
1880
- }
1881
- }
1882
- return {
1883
- name: '',
1884
- };
1885
- }
1886
- const [state, setState] = react.useState(getInitialState(!!props.ssr));
1887
- // Cancel loading
1888
- function cleanup() {
1889
- const callback = abort.callback;
1890
- if (callback) {
1891
- callback();
1892
- setAbort({});
1893
- }
1894
- }
1895
- // Change state if it is different
1896
- function changeState(newState) {
1897
- if (JSON.stringify(state) !== JSON.stringify(newState)) {
1898
- cleanup();
1899
- setState(newState);
1900
- return true;
1901
- }
1902
- }
1903
- // Update state
1904
- function updateState() {
1905
- var _a;
1906
- const name = props.icon;
1907
- if (typeof name === 'object') {
1908
- // Icon as object
1909
- changeState({
1910
- name: '',
1911
- data: name,
1912
- });
1913
- return;
1914
- }
1915
- // New icon or got icon data
1916
- const data = getIconData(name);
1917
- if (changeState({
1918
- name,
1919
- data,
1920
- })) {
1921
- if (data === undefined) {
1922
- // Load icon, update state when done
1923
- const callback = loadIcons([name], updateState);
1924
- setAbort({
1925
- callback,
1926
- });
1927
- }
1928
- else if (data) {
1929
- // Icon data is available: trigger onLoad callback if present
1930
- (_a = props.onLoad) === null || _a === void 0 ? void 0 : _a.call(props, name);
1931
- }
1932
- }
1933
- }
1934
- // Mounted state, cleanup for loader
1935
- react.useEffect(() => {
1936
- setMounted(true);
1937
- return cleanup;
1938
- }, []);
1939
- // Icon changed or component mounted
1940
- react.useEffect(() => {
1941
- if (mounted) {
1942
- updateState();
1943
- }
1944
- }, [props.icon, mounted]);
1945
- // Render icon
1946
- const { name, data } = state;
1947
- if (!data) {
1948
- return props.children
1949
- ? props.children
1950
- : props.fallback
1951
- ? props.fallback
1952
- : react.createElement('span', {});
1953
- }
1954
- return render({
1955
- ...defaultIconProps,
1956
- ...data,
1957
- }, props, name);
1958
- }
1959
- /**
1960
- * Block icon
1961
- *
1962
- * @param props - Component properties
1963
- */
1964
- const Icon = react.forwardRef((props, ref) => IconComponent({
1965
- ...props,
1966
- _ref: ref,
1967
- }));
1968
- /**
1969
- * Inline icon (has negative verticalAlign that makes it behave like icon font)
1970
- *
1971
- * @param props - Component properties
1972
- */
1973
- react.forwardRef((props, ref) => IconComponent({
1974
- inline: true,
1975
- ...props,
1976
- _ref: ref,
1977
- }));
1978
-
1979
- const ChatComponent = ({ messages: externalMessages, onSendMessage, currentUser = { id: 'user1', name: 'You' }, inputPlaceholder = 'Type a message...', className = '', headerTitle = 'BlueMessage AI', headerDescription = 'Online • Instant responses', headerColor, headerIcon = 'mdi:message-text', headerIconColor, headerIconHide = false, headerAvatarColor = 'rgba(255, 255, 255, 0.2)', primaryColor = '#3b82f6', secondaryColor = '#2563eb', messageUserColor, messageAssistantColor = '#f3f4f6', messageTimestamps = true, messageUserAvatarVisibility = false, messageUserAvatarIcon = 'mdi:account', messageUserAvatarColor = '#3b82f6', messageAssistantAvatarVisibility = false, messageAssistantAvatarIcon = 'mdi:robot', messageAssistantAvatarColor = '#6b7280', messageUserName = null, messageAssistantName = null, sendButtonIcon = 'mdi:send', sendButtonColor, inputOutlineColor = '#3b82f6', floatingButtonPosition = 'bottom-right', floatingButtonIcon, floatingButtonIconColor, floatingButtonBackgroundColor, size = 'medium', maximizeToggle = true, maximize = false, autoOpen = false, forceOpen = false, apiKey }) => {
1980
- const [isOpen, setIsOpen] = react.useState(autoOpen || forceOpen);
1981
- const [isClosing, setIsClosing] = react.useState(false);
1982
- const [isMaximized, setIsMaximized] = react.useState(maximize);
1983
- const [isMaximizing, setIsMaximizing] = react.useState(false);
1984
- // API key validation state
1985
- const [isApiKeyValid, setIsApiKeyValid] = react.useState(false);
1986
- const [isValidatingApiKey, setIsValidatingApiKey] = react.useState(false);
1987
- // Check if API key is missing or invalid
1988
- const isApiKeyMissing = !apiKey;
1989
- const isChatDisabled = isApiKeyMissing || (!isApiKeyValid && apiKey !== 'test');
1990
- // Validate API key
1991
- react.useEffect(() => {
1992
- const validateApiKey = () => __awaiter(void 0, void 0, void 0, function* () {
1993
- if (!apiKey) {
1994
- console.error('ChatComponent: API key is missing. Chat functionality has been disabled.');
1995
- return;
1996
- }
1997
- // Special exception for test API key
1998
- if (apiKey === 'test') {
1999
- setIsApiKeyValid(true);
2000
- console.log('ChatComponent: Using test API key for demo purposes.');
2001
- return;
2002
- }
2003
- setIsValidatingApiKey(true);
2004
- try {
2005
- const response = yield fetch('https://api.blumessage.com/api/v1/api-keys/validate', {
2006
- method: 'POST',
2007
- headers: {
2008
- 'Content-Type': 'application/json',
2009
- },
2010
- body: JSON.stringify({ apiKey }),
2011
- });
2012
- if (response.status === 200) {
2013
- setIsApiKeyValid(true);
2014
- console.log('ChatComponent: API key validated successfully.');
2015
- }
2016
- else {
2017
- setIsApiKeyValid(false);
2018
- console.error('ChatComponent: API key is invalid. Chat functionality has been disabled.');
2019
- }
2020
- }
2021
- catch (error) {
2022
- setIsApiKeyValid(false);
2023
- console.error('ChatComponent: Failed to validate API key. Chat functionality has been disabled.', error);
2024
- }
2025
- finally {
2026
- setIsValidatingApiKey(false);
2027
- }
2028
- });
2029
- validateApiKey();
2030
- }, [apiKey]);
2031
- const [messages, setMessages] = react.useState(externalMessages || [
2032
- {
2033
- id: '1',
2034
- text: 'Hello! Welcome to the chat component demo.',
2035
- sender: { id: 'bot', name: 'ChatBot', avatar: '🤖' },
2036
- timestamp: new Date(Date.now() - 5 * 60000),
2037
- isOwn: false
2038
- },
2039
- {
2040
- id: '2',
2041
- text: 'This is what a user message looks like!',
2042
- sender: currentUser,
2043
- timestamp: new Date(Date.now() - 3 * 60000),
2044
- isOwn: true
2045
- },
2046
- {
2047
- id: '3',
2048
- text: 'You can customize the appearance, add your own message handlers, and integrate it with any backend.',
2049
- sender: { id: 'bot', name: 'ChatBot', avatar: '🤖' },
2050
- timestamp: new Date(Date.now() - 1 * 60000),
2051
- isOwn: false
2052
- }
2053
- ]);
2054
- const [newMessage, setNewMessage] = react.useState('');
2055
- const [isTyping, setIsTyping] = react.useState(false);
2056
- const messagesEndRef = react.useRef(null);
2057
- const [shouldScrollToBottom, setShouldScrollToBottom] = react.useState(false);
2058
- const getSizeClasses = (size) => {
2059
- switch (size) {
2060
- case 'xsmall':
2061
- return 'w-64 h-80';
2062
- case 'small':
2063
- return 'w-72 h-96';
2064
- case 'medium':
2065
- return 'w-80 sm:w-96 h-[500px] sm:h-[600px]';
2066
- case 'large':
2067
- return 'w-96 sm:w-[28rem] h-[600px] sm:h-[700px]';
2068
- case 'xlarge':
2069
- return 'w-[28rem] sm:w-[32rem] h-[700px] sm:h-[800px]';
2070
- default:
2071
- return 'w-80 sm:w-96 h-[500px] sm:h-[600px]';
2072
- }
2073
- };
2074
- const getPositionClasses = (position) => {
2075
- switch (position) {
2076
- case 'top-right':
2077
- return 'top-4 right-4';
2078
- case 'top-left':
2079
- return 'top-4 left-4';
2080
- case 'bottom-left':
2081
- return 'bottom-4 left-4';
2082
- case 'bottom-right':
2083
- default:
2084
- return 'bottom-4 right-4';
2085
- }
2086
- };
2087
- const handleOpenChat = () => {
2088
- if (!forceOpen && !isChatDisabled) {
2089
- setIsOpen(true);
2090
- setIsClosing(false);
2091
- setShouldScrollToBottom(true);
2092
- if (maximize) {
2093
- setIsMaximized(true);
2094
- }
2095
- }
2096
- };
2097
- const handleCloseChat = () => {
2098
- if (!forceOpen) {
2099
- setIsClosing(true);
2100
- setTimeout(() => {
2101
- setIsOpen(false);
2102
- setIsClosing(false);
2103
- }, 300);
2104
- }
2105
- };
2106
- const handleToggleMaximize = () => {
2107
- setIsMaximizing(true);
2108
- setTimeout(() => {
2109
- setIsMaximized(!isMaximized);
2110
- setTimeout(() => {
2111
- setIsMaximizing(false);
2112
- }, 400);
2113
- }, 50);
2114
- };
2115
- const scrollToBottom = () => {
2116
- var _a;
2117
- (_a = messagesEndRef.current) === null || _a === void 0 ? void 0 : _a.scrollIntoView({ behavior: 'smooth' });
2118
- };
2119
- react.useEffect(() => {
2120
- if (shouldScrollToBottom && isOpen) {
2121
- setTimeout(() => {
2122
- scrollToBottom();
2123
- setShouldScrollToBottom(false);
2124
- }, 100);
2125
- }
2126
- }, [shouldScrollToBottom, isOpen]);
2127
- react.useEffect(() => {
2128
- scrollToBottom();
2129
- }, [messages]);
2130
- const handleSendMessage = () => __awaiter(void 0, void 0, void 0, function* () {
2131
- if (newMessage.trim() && !isTyping && !isChatDisabled) {
2132
- const userMessage = {
2133
- id: Date.now().toString(),
2134
- text: newMessage,
2135
- sender: currentUser,
2136
- timestamp: new Date(),
2137
- isOwn: true
2138
- };
2139
- setMessages(prev => [...prev, userMessage]);
2140
- setNewMessage('');
2141
- setIsTyping(true);
2142
- if (onSendMessage) {
2143
- onSendMessage(newMessage);
2144
- }
2145
- // If we have a valid API key, send to BlueMessage API
2146
- if (apiKey && (isApiKeyValid || apiKey === 'test')) {
2147
- try {
2148
- const response = yield fetch('https://api.blumessage.com/api/v1/conversations', {
2149
- method: 'POST',
2150
- headers: {
2151
- 'Content-Type': 'application/json',
2152
- 'Authorization': `Bearer ${apiKey}`
2153
- },
2154
- body: JSON.stringify({
2155
- message: newMessage
2156
- }),
2157
- });
2158
- if (response.ok) {
2159
- const data = yield response.json();
2160
- console.log('BlueMessage API response:', data);
2161
- // Get the last assistant message from the response
2162
- const assistantMessages = data.messages.filter((msg) => msg.role === 'assistant');
2163
- if (assistantMessages.length > 0) {
2164
- const lastAssistantMessage = assistantMessages[assistantMessages.length - 1];
2165
- const botResponse = {
2166
- id: (Date.now() + 1).toString(),
2167
- text: lastAssistantMessage.content,
2168
- sender: { id: 'assistant', name: 'Assistant', avatar: '🤖' },
2169
- timestamp: new Date(lastAssistantMessage.timestamp),
2170
- isOwn: false
2171
- };
2172
- setMessages(prev => [...prev, botResponse]);
2173
- }
2174
- }
2175
- else {
2176
- console.error('Failed to send message to BlueMessage API:', response.status);
2177
- // Fallback to demo response
2178
- const botResponse = {
2179
- id: (Date.now() + 1).toString(),
2180
- text: `Thanks for your message: "${newMessage}". This is a fallback response as the API request failed.`,
2181
- sender: { id: 'bot', name: 'ChatBot', avatar: '🤖' },
2182
- timestamp: new Date(),
2183
- isOwn: false
2184
- };
2185
- setMessages(prev => [...prev, botResponse]);
2186
- }
2187
- }
2188
- catch (error) {
2189
- console.error('Error calling BlueMessage API:', error);
2190
- // Fallback to demo response
2191
- const botResponse = {
2192
- id: (Date.now() + 1).toString(),
2193
- text: `Thanks for your message: "${newMessage}". This is a fallback response due to an API error.`,
2194
- sender: { id: 'bot', name: 'ChatBot', avatar: '🤖' },
2195
- timestamp: new Date(),
2196
- isOwn: false
2197
- };
2198
- setMessages(prev => [...prev, botResponse]);
2199
- }
2200
- }
2201
- else {
2202
- // Fallback demo response when no valid API key
2203
- setTimeout(() => {
2204
- const botResponse = {
2205
- id: (Date.now() + 1).toString(),
2206
- text: `Thanks for your message: "${newMessage}". This is an automated response for the demo!`,
2207
- sender: { id: 'bot', name: 'ChatBot', avatar: '🤖' },
2208
- timestamp: new Date(),
2209
- isOwn: false
2210
- };
2211
- setMessages(prev => [...prev, botResponse]);
2212
- }, 1500);
2213
- }
2214
- setIsTyping(false);
2215
- }
2216
- });
2217
- const handleKeyPress = (e) => {
2218
- if (e.key === 'Enter' && !e.shiftKey && !isTyping && !isChatDisabled) {
2219
- e.preventDefault();
2220
- handleSendMessage();
2221
- }
2222
- };
2223
- const formatTime = (date) => {
2224
- return date.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
2225
- };
2226
- const getHeaderBackground = () => {
2227
- if (headerColor) {
2228
- return headerColor;
2229
- }
2230
- return `linear-gradient(to right, ${primaryColor}, ${secondaryColor})`;
2231
- };
2232
- const getUserMessageBackground = () => {
2233
- if (messageUserColor) {
2234
- return messageUserColor;
2235
- }
2236
- return `linear-gradient(to right, ${primaryColor}, ${secondaryColor})`;
2237
- };
2238
- const getSendButtonBackground = () => {
2239
- if (sendButtonColor) {
2240
- return sendButtonColor;
2241
- }
2242
- return (newMessage.trim() && !isTyping && !isChatDisabled)
2243
- ? `linear-gradient(to right, ${primaryColor}, ${secondaryColor})`
2244
- : 'linear-gradient(to right, #d1d5db, #9ca3af)';
2245
- };
2246
- const getFloatingButtonBackground = () => {
2247
- if (floatingButtonBackgroundColor) {
2248
- return floatingButtonBackgroundColor;
2249
- }
2250
- return `linear-gradient(to right, ${primaryColor}, ${secondaryColor})`;
2251
- };
2252
- const getFloatingButtonIcon = () => {
2253
- return floatingButtonIcon || headerIcon;
2254
- };
2255
- const getFloatingButtonIconColor = () => {
2256
- return floatingButtonIconColor || 'white';
2257
- };
2258
- // Don't render anything if API key is missing or invalid (except for test key)
2259
- if (isChatDisabled) {
2260
- return null;
2261
- }
2262
- return (jsxRuntime.jsxs("div", { className: `fixed ${getPositionClasses(floatingButtonPosition)} z-50 ${className}`, children: [!isOpen && !forceOpen && (jsxRuntime.jsx("button", { onClick: handleOpenChat, disabled: isValidatingApiKey, className: "w-14 h-14 rounded-full text-white shadow-lg transition-all duration-300 transform hover:scale-110 hover:shadow-xl disabled:opacity-50 disabled:cursor-not-allowed", style: {
2263
- background: getFloatingButtonBackground()
2264
- }, children: isValidatingApiKey ? (jsxRuntime.jsx("div", { className: "w-6 h-6 border-2 border-white/30 border-t-white rounded-full animate-spin mx-auto" })) : !headerIconHide ? (jsxRuntime.jsx(Icon, { icon: getFloatingButtonIcon(), width: 24, height: 24, className: "mx-auto", style: { color: getFloatingButtonIconColor() } })) : (jsxRuntime.jsx("div", { className: "w-6 h-6 bg-white/20 rounded-full mx-auto" })) })), jsxRuntime.jsxs("div", { className: `${isMaximized
2265
- ? 'fixed inset-4 w-auto h-auto'
2266
- : getSizeClasses(size)} bg-white rounded-2xl shadow-2xl overflow-hidden flex flex-col origin-bottom-right ${!isOpen
2267
- ? 'opacity-0 pointer-events-none scale-95 translate-y-2'
2268
- : isClosing
2269
- ? 'animate-out slide-out-to-bottom-2 fade-out-0 scale-out-95 duration-300'
2270
- : 'animate-in slide-in-from-bottom-2 fade-in-0 scale-in-95 duration-300'} ${isMaximizing
2271
- ? 'transition-all duration-400 ease-in-out transform'
2272
- : 'transition-all duration-300'}`, children: [jsxRuntime.jsxs("div", { className: "text-white p-4 flex items-center gap-3 flex-shrink-0", style: {
2273
- background: getHeaderBackground()
2274
- }, children: [!headerIconHide && (jsxRuntime.jsx("div", { className: "w-10 h-10 rounded-full backdrop-blur-sm flex items-center justify-center", style: { backgroundColor: headerAvatarColor }, children: jsxRuntime.jsx(Icon, { icon: headerIcon, width: 20, height: 20, style: { color: headerIconColor || 'white' } }) })), jsxRuntime.jsxs("div", { className: "flex-1 min-w-0", children: [jsxRuntime.jsx("h3", { className: "font-semibold text-lg truncate", children: headerTitle }), jsxRuntime.jsx("p", { className: "text-white/80 text-sm truncate", children: headerDescription })] }), maximizeToggle && (jsxRuntime.jsx("button", { onClick: handleToggleMaximize, className: "text-white/70 hover:text-white transition-all duration-200 flex-shrink-0 mr-2 hover:scale-110 active:scale-95", title: isMaximized ? 'Minimize' : 'Maximize', children: isMaximized ? jsxRuntime.jsx(Minimize, { size: 20 }) : jsxRuntime.jsx(Maximize, { size: 20 }) })), !forceOpen && (jsxRuntime.jsx("button", { onClick: handleCloseChat, className: "text-white/70 hover:text-white transition-all duration-200 flex-shrink-0 hover:scale-110 active:scale-95", children: jsxRuntime.jsx(X, { size: 20 }) }))] }), jsxRuntime.jsxs("div", { className: "flex-1 overflow-y-auto p-4 space-y-4 min-h-0", children: [messages.map((message) => (jsxRuntime.jsx("div", { className: `flex ${message.isOwn ? 'justify-end' : 'justify-start'} animate-in slide-in-from-bottom-2 duration-300`, children: jsxRuntime.jsxs("div", { className: `max-w-[75%] sm:max-w-xs lg:max-w-md flex ${message.isOwn ? 'flex-row-reverse' : 'flex-row'} items-end gap-2`, children: [((message.isOwn && messageUserAvatarVisibility) || (!message.isOwn && messageAssistantAvatarVisibility)) && (jsxRuntime.jsx("div", { className: "w-8 h-8 rounded-full flex items-center justify-center flex-shrink-0", style: {
2275
- backgroundColor: message.isOwn ? messageUserAvatarColor : messageAssistantAvatarColor
2276
- }, children: jsxRuntime.jsx(Icon, { icon: message.isOwn ? messageUserAvatarIcon : messageAssistantAvatarIcon, width: 16, height: 16, className: "text-white" }) })), jsxRuntime.jsxs("div", { className: "flex flex-col", children: [((message.isOwn && messageUserName) || (!message.isOwn && messageAssistantName)) && (jsxRuntime.jsx("div", { className: "text-xs text-gray-500 mb-1 px-3", children: message.isOwn ? messageUserName : messageAssistantName })), jsxRuntime.jsxs("div", { className: `px-4 py-2 rounded-2xl shadow-sm transition-all duration-200 hover:shadow-md break-words ${message.isOwn
2277
- ? 'text-white rounded-br-md'
2278
- : 'text-gray-800 rounded-bl-md hover:bg-gray-50'}`, style: message.isOwn ? {
2279
- background: getUserMessageBackground()
2280
- } : {
2281
- backgroundColor: messageAssistantColor
2282
- }, children: [jsxRuntime.jsx("p", { className: "text-sm leading-relaxed", children: message.text }), messageTimestamps && (jsxRuntime.jsx("div", { className: `text-xs mt-1 ${message.isOwn ? 'text-white/70' : 'text-gray-500'}`, children: formatTime(message.timestamp) }))] })] })] }) }, message.id))), isTyping && (jsxRuntime.jsx("div", { className: "flex justify-start animate-in slide-in-from-bottom-2 duration-300", children: jsxRuntime.jsxs("div", { className: "flex items-end gap-2", children: [messageAssistantAvatarVisibility && (jsxRuntime.jsx("div", { className: "w-8 h-8 rounded-full flex items-center justify-center flex-shrink-0", style: { backgroundColor: messageAssistantAvatarColor }, children: jsxRuntime.jsx(Icon, { icon: messageAssistantAvatarIcon, width: 16, height: 16, className: "text-white" }) })), jsxRuntime.jsx("div", { className: "px-4 py-2 rounded-2xl rounded-bl-md", style: { backgroundColor: messageAssistantColor }, children: jsxRuntime.jsxs("div", { className: "flex space-x-1", children: [jsxRuntime.jsx("div", { className: "w-2 h-2 bg-gray-400 rounded-full animate-pulse" }), jsxRuntime.jsx("div", { className: "w-2 h-2 bg-gray-400 rounded-full animate-pulse", style: { animationDelay: '0.2s' } }), jsxRuntime.jsx("div", { className: "w-2 h-2 bg-gray-400 rounded-full animate-pulse", style: { animationDelay: '0.4s' } })] }) })] }) })), jsxRuntime.jsx("div", { ref: messagesEndRef })] }), jsxRuntime.jsx("div", { className: "border-t border-gray-200 p-4 flex-shrink-0", children: jsxRuntime.jsxs("div", { className: "flex gap-2 items-end", children: [jsxRuntime.jsx("textarea", { value: newMessage, onChange: (e) => setNewMessage(e.target.value), onKeyPress: handleKeyPress, placeholder: isTyping ? 'Assistant is responding...' : inputPlaceholder, disabled: isChatDisabled, className: "flex-1 resize-none border border-gray-300 rounded-2xl px-4 py-3 focus:outline-none focus:ring-2 focus:border-transparent transition-all duration-200 max-h-32 min-h-[48px] text-sm disabled:opacity-50 disabled:cursor-not-allowed", style: {
2283
- '--tw-ring-color': inputOutlineColor,
2284
- '--tw-ring-opacity': '1'
2285
- }, rows: 1 }), jsxRuntime.jsx("button", { onClick: handleSendMessage, disabled: !newMessage.trim() || isTyping || isChatDisabled, className: "text-white p-3 rounded-2xl transition-all duration-200 transform hover:scale-105 active:scale-95 disabled:scale-100 disabled:cursor-not-allowed shadow-lg hover:shadow-xl flex-shrink-0", style: {
2286
- background: getSendButtonBackground()
2287
- }, children: jsxRuntime.jsx(Icon, { icon: sendButtonIcon, width: 20, height: 20 }) })] }) })] })] }));
2288
- };
2289
-
2290
- exports.BlumessageChat = ChatComponent;
2291
- //# sourceMappingURL=index.js.map
1
+ export { BlumessageChat } from './BlumessageChat';