quikchat 1.1.16 → 1.2.4

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.
Files changed (42) hide show
  1. package/README.md +160 -354
  2. package/dist/build-manifest.json +157 -0
  3. package/dist/quikchat-md-full.cjs.js +2742 -0
  4. package/dist/quikchat-md-full.cjs.js.map +1 -0
  5. package/dist/quikchat-md-full.cjs.min.js +10 -0
  6. package/dist/quikchat-md-full.cjs.min.js.map +1 -0
  7. package/dist/quikchat-md-full.esm.js +2740 -0
  8. package/dist/quikchat-md-full.esm.js.map +1 -0
  9. package/dist/quikchat-md-full.esm.min.js +10 -0
  10. package/dist/quikchat-md-full.esm.min.js.map +1 -0
  11. package/dist/quikchat-md-full.umd.js +2748 -0
  12. package/dist/quikchat-md-full.umd.js.map +1 -0
  13. package/dist/quikchat-md-full.umd.min.js +10 -0
  14. package/dist/quikchat-md-full.umd.min.js.map +1 -0
  15. package/dist/quikchat-md.cjs.js +1641 -0
  16. package/dist/quikchat-md.cjs.js.map +1 -0
  17. package/dist/quikchat-md.cjs.min.js +8 -0
  18. package/dist/quikchat-md.cjs.min.js.map +1 -0
  19. package/dist/quikchat-md.esm.js +1639 -0
  20. package/dist/quikchat-md.esm.js.map +1 -0
  21. package/dist/quikchat-md.esm.min.js +8 -0
  22. package/dist/quikchat-md.esm.min.js.map +1 -0
  23. package/dist/quikchat-md.umd.js +1647 -0
  24. package/dist/quikchat-md.umd.js.map +1 -0
  25. package/dist/quikchat-md.umd.min.js +8 -0
  26. package/dist/quikchat-md.umd.min.js.map +1 -0
  27. package/dist/quikchat.cjs.js +449 -1421
  28. package/dist/quikchat.cjs.js.map +1 -1
  29. package/dist/quikchat.cjs.min.js +1 -1
  30. package/dist/quikchat.cjs.min.js.map +1 -1
  31. package/dist/quikchat.css +753 -226
  32. package/dist/quikchat.esm.js +449 -1421
  33. package/dist/quikchat.esm.js.map +1 -1
  34. package/dist/quikchat.esm.min.js +1 -1
  35. package/dist/quikchat.esm.min.js.map +1 -1
  36. package/dist/quikchat.min.css +1 -1
  37. package/dist/quikchat.umd.js +449 -1421
  38. package/dist/quikchat.umd.js.map +1 -1
  39. package/dist/quikchat.umd.min.js +1 -1
  40. package/dist/quikchat.umd.min.js.map +1 -1
  41. package/package.json +59 -34
  42. package/dist/quikchat.d.ts +0 -194
@@ -0,0 +1,2740 @@
1
+ function _arrayLikeToArray(r, a) {
2
+ (null == a || a > r.length) && (a = r.length);
3
+ for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e];
4
+ return n;
5
+ }
6
+ function _arrayWithoutHoles(r) {
7
+ if (Array.isArray(r)) return _arrayLikeToArray(r);
8
+ }
9
+ function _assertThisInitialized(e) {
10
+ if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
11
+ return e;
12
+ }
13
+ function asyncGeneratorStep(n, t, e, r, o, a, c) {
14
+ try {
15
+ var i = n[a](c),
16
+ u = i.value;
17
+ } catch (n) {
18
+ return void e(n);
19
+ }
20
+ i.done ? t(u) : Promise.resolve(u).then(r, o);
21
+ }
22
+ function _asyncToGenerator(n) {
23
+ return function () {
24
+ var t = this,
25
+ e = arguments;
26
+ return new Promise(function (r, o) {
27
+ var a = n.apply(t, e);
28
+ function _next(n) {
29
+ asyncGeneratorStep(a, r, o, _next, _throw, "next", n);
30
+ }
31
+ function _throw(n) {
32
+ asyncGeneratorStep(a, r, o, _next, _throw, "throw", n);
33
+ }
34
+ _next(void 0);
35
+ });
36
+ };
37
+ }
38
+ function _callSuper(t, o, e) {
39
+ return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e));
40
+ }
41
+ function _classCallCheck(a, n) {
42
+ if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function");
43
+ }
44
+ function _defineProperties(e, r) {
45
+ for (var t = 0; t < r.length; t++) {
46
+ var o = r[t];
47
+ o.enumerable = o.enumerable || false, o.configurable = true, "value" in o && (o.writable = true), Object.defineProperty(e, _toPropertyKey(o.key), o);
48
+ }
49
+ }
50
+ function _createClass(e, r, t) {
51
+ return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", {
52
+ writable: false
53
+ }), e;
54
+ }
55
+ function _createForOfIteratorHelper(r, e) {
56
+ var t = "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"];
57
+ if (!t) {
58
+ if (Array.isArray(r) || (t = _unsupportedIterableToArray(r)) || e) {
59
+ t && (r = t);
60
+ var n = 0,
61
+ F = function () {};
62
+ return {
63
+ s: F,
64
+ n: function () {
65
+ return n >= r.length ? {
66
+ done: true
67
+ } : {
68
+ done: false,
69
+ value: r[n++]
70
+ };
71
+ },
72
+ e: function (r) {
73
+ throw r;
74
+ },
75
+ f: F
76
+ };
77
+ }
78
+ throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
79
+ }
80
+ var o,
81
+ a = true,
82
+ u = false;
83
+ return {
84
+ s: function () {
85
+ t = t.call(r);
86
+ },
87
+ n: function () {
88
+ var r = t.next();
89
+ return a = r.done, r;
90
+ },
91
+ e: function (r) {
92
+ u = true, o = r;
93
+ },
94
+ f: function () {
95
+ try {
96
+ a || null == t.return || t.return();
97
+ } finally {
98
+ if (u) throw o;
99
+ }
100
+ }
101
+ };
102
+ }
103
+ function _defineProperty(e, r, t) {
104
+ return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, {
105
+ value: t,
106
+ enumerable: true,
107
+ configurable: true,
108
+ writable: true
109
+ }) : e[r] = t, e;
110
+ }
111
+ function _get() {
112
+ return _get = "undefined" != typeof Reflect && Reflect.get ? Reflect.get.bind() : function (e, t, r) {
113
+ var p = _superPropBase(e, t);
114
+ if (p) {
115
+ var n = Object.getOwnPropertyDescriptor(p, t);
116
+ return n.get ? n.get.call(arguments.length < 3 ? e : r) : n.value;
117
+ }
118
+ }, _get.apply(null, arguments);
119
+ }
120
+ function _getPrototypeOf(t) {
121
+ return _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) {
122
+ return t.__proto__ || Object.getPrototypeOf(t);
123
+ }, _getPrototypeOf(t);
124
+ }
125
+ function _inherits(t, e) {
126
+ if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function");
127
+ t.prototype = Object.create(e && e.prototype, {
128
+ constructor: {
129
+ value: t,
130
+ writable: true,
131
+ configurable: true
132
+ }
133
+ }), Object.defineProperty(t, "prototype", {
134
+ writable: false
135
+ }), e && _setPrototypeOf(t, e);
136
+ }
137
+ function _isNativeReflectConstruct() {
138
+ try {
139
+ var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {}));
140
+ } catch (t) {}
141
+ return (_isNativeReflectConstruct = function () {
142
+ return !!t;
143
+ })();
144
+ }
145
+ function _iterableToArray(r) {
146
+ if ("undefined" != typeof Symbol && null != r[Symbol.iterator] || null != r["@@iterator"]) return Array.from(r);
147
+ }
148
+ function _nonIterableSpread() {
149
+ throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
150
+ }
151
+ function ownKeys(e, r) {
152
+ var t = Object.keys(e);
153
+ if (Object.getOwnPropertySymbols) {
154
+ var o = Object.getOwnPropertySymbols(e);
155
+ r && (o = o.filter(function (r) {
156
+ return Object.getOwnPropertyDescriptor(e, r).enumerable;
157
+ })), t.push.apply(t, o);
158
+ }
159
+ return t;
160
+ }
161
+ function _objectSpread2(e) {
162
+ for (var r = 1; r < arguments.length; r++) {
163
+ var t = null != arguments[r] ? arguments[r] : {};
164
+ r % 2 ? ownKeys(Object(t), true).forEach(function (r) {
165
+ _defineProperty(e, r, t[r]);
166
+ }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) {
167
+ Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r));
168
+ });
169
+ }
170
+ return e;
171
+ }
172
+ function _possibleConstructorReturn(t, e) {
173
+ if (e && ("object" == typeof e || "function" == typeof e)) return e;
174
+ if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined");
175
+ return _assertThisInitialized(t);
176
+ }
177
+ function _regenerator() {
178
+ /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/babel/babel/blob/main/packages/babel-helpers/LICENSE */
179
+ var e,
180
+ t,
181
+ r = "function" == typeof Symbol ? Symbol : {},
182
+ n = r.iterator || "@@iterator",
183
+ o = r.toStringTag || "@@toStringTag";
184
+ function i(r, n, o, i) {
185
+ var c = n && n.prototype instanceof Generator ? n : Generator,
186
+ u = Object.create(c.prototype);
187
+ return _regeneratorDefine(u, "_invoke", function (r, n, o) {
188
+ var i,
189
+ c,
190
+ u,
191
+ f = 0,
192
+ p = o || [],
193
+ y = false,
194
+ G = {
195
+ p: 0,
196
+ n: 0,
197
+ v: e,
198
+ a: d,
199
+ f: d.bind(e, 4),
200
+ d: function (t, r) {
201
+ return i = t, c = 0, u = e, G.n = r, a;
202
+ }
203
+ };
204
+ function d(r, n) {
205
+ for (c = r, u = n, t = 0; !y && f && !o && t < p.length; t++) {
206
+ var o,
207
+ i = p[t],
208
+ d = G.p,
209
+ l = i[2];
210
+ r > 3 ? (o = l === n) && (u = i[(c = i[4]) ? 5 : (c = 3, 3)], i[4] = i[5] = e) : i[0] <= d && ((o = r < 2 && d < i[1]) ? (c = 0, G.v = n, G.n = i[1]) : d < l && (o = r < 3 || i[0] > n || n > l) && (i[4] = r, i[5] = n, G.n = l, c = 0));
211
+ }
212
+ if (o || r > 1) return a;
213
+ throw y = true, n;
214
+ }
215
+ return function (o, p, l) {
216
+ if (f > 1) throw TypeError("Generator is already running");
217
+ for (y && 1 === p && d(p, l), c = p, u = l; (t = c < 2 ? e : u) || !y;) {
218
+ i || (c ? c < 3 ? (c > 1 && (G.n = -1), d(c, u)) : G.n = u : G.v = u);
219
+ try {
220
+ if (f = 2, i) {
221
+ if (c || (o = "next"), t = i[o]) {
222
+ if (!(t = t.call(i, u))) throw TypeError("iterator result is not an object");
223
+ if (!t.done) return t;
224
+ u = t.value, c < 2 && (c = 0);
225
+ } else 1 === c && (t = i.return) && t.call(i), c < 2 && (u = TypeError("The iterator does not provide a '" + o + "' method"), c = 1);
226
+ i = e;
227
+ } else if ((t = (y = G.n < 0) ? u : r.call(n, G)) !== a) break;
228
+ } catch (t) {
229
+ i = e, c = 1, u = t;
230
+ } finally {
231
+ f = 1;
232
+ }
233
+ }
234
+ return {
235
+ value: t,
236
+ done: y
237
+ };
238
+ };
239
+ }(r, o, i), true), u;
240
+ }
241
+ var a = {};
242
+ function Generator() {}
243
+ function GeneratorFunction() {}
244
+ function GeneratorFunctionPrototype() {}
245
+ t = Object.getPrototypeOf;
246
+ var c = [][n] ? t(t([][n]())) : (_regeneratorDefine(t = {}, n, function () {
247
+ return this;
248
+ }), t),
249
+ u = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(c);
250
+ function f(e) {
251
+ return Object.setPrototypeOf ? Object.setPrototypeOf(e, GeneratorFunctionPrototype) : (e.__proto__ = GeneratorFunctionPrototype, _regeneratorDefine(e, o, "GeneratorFunction")), e.prototype = Object.create(u), e;
252
+ }
253
+ return GeneratorFunction.prototype = GeneratorFunctionPrototype, _regeneratorDefine(u, "constructor", GeneratorFunctionPrototype), _regeneratorDefine(GeneratorFunctionPrototype, "constructor", GeneratorFunction), GeneratorFunction.displayName = "GeneratorFunction", _regeneratorDefine(GeneratorFunctionPrototype, o, "GeneratorFunction"), _regeneratorDefine(u), _regeneratorDefine(u, o, "Generator"), _regeneratorDefine(u, n, function () {
254
+ return this;
255
+ }), _regeneratorDefine(u, "toString", function () {
256
+ return "[object Generator]";
257
+ }), (_regenerator = function () {
258
+ return {
259
+ w: i,
260
+ m: f
261
+ };
262
+ })();
263
+ }
264
+ function _regeneratorDefine(e, r, n, t) {
265
+ var i = Object.defineProperty;
266
+ try {
267
+ i({}, "", {});
268
+ } catch (e) {
269
+ i = 0;
270
+ }
271
+ _regeneratorDefine = function (e, r, n, t) {
272
+ function o(r, n) {
273
+ _regeneratorDefine(e, r, function (e) {
274
+ return this._invoke(r, n, e);
275
+ });
276
+ }
277
+ r ? i ? i(e, r, {
278
+ value: n,
279
+ enumerable: !t,
280
+ configurable: !t,
281
+ writable: !t
282
+ }) : e[r] = n : (o("next", 0), o("throw", 1), o("return", 2));
283
+ }, _regeneratorDefine(e, r, n, t);
284
+ }
285
+ function _setPrototypeOf(t, e) {
286
+ return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) {
287
+ return t.__proto__ = e, t;
288
+ }, _setPrototypeOf(t, e);
289
+ }
290
+ function _superPropBase(t, o) {
291
+ for (; !{}.hasOwnProperty.call(t, o) && null !== (t = _getPrototypeOf(t)););
292
+ return t;
293
+ }
294
+ function _superPropGet(t, o, e, r) {
295
+ var p = _get(_getPrototypeOf(t.prototype ), o, e);
296
+ return 2 & r && "function" == typeof p ? function (t) {
297
+ return p.apply(e, t);
298
+ } : p;
299
+ }
300
+ function _toConsumableArray(r) {
301
+ return _arrayWithoutHoles(r) || _iterableToArray(r) || _unsupportedIterableToArray(r) || _nonIterableSpread();
302
+ }
303
+ function _toPrimitive(t, r) {
304
+ if ("object" != typeof t || !t) return t;
305
+ var e = t[Symbol.toPrimitive];
306
+ if (void 0 !== e) {
307
+ var i = e.call(t, r);
308
+ if ("object" != typeof i) return i;
309
+ throw new TypeError("@@toPrimitive must return a primitive value.");
310
+ }
311
+ return (String )(t);
312
+ }
313
+ function _toPropertyKey(t) {
314
+ var i = _toPrimitive(t, "string");
315
+ return "symbol" == typeof i ? i : i + "";
316
+ }
317
+ function _unsupportedIterableToArray(r, a) {
318
+ if (r) {
319
+ if ("string" == typeof r) return _arrayLikeToArray(r, a);
320
+ var t = {}.toString.call(r).slice(8, -1);
321
+ return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0;
322
+ }
323
+ }
324
+
325
+ var quikchat = /*#__PURE__*/function () {
326
+ /**
327
+ *
328
+ * @param string or DOM element parentElement
329
+ * @param {*} meta
330
+ */
331
+ function quikchat(parentElement) {
332
+ var onSend = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : function () {};
333
+ var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
334
+ _classCallCheck(this, quikchat);
335
+ var defaultOpts = {
336
+ theme: 'quikchat-theme-light',
337
+ trackHistory: true,
338
+ showTimestamps: false,
339
+ titleArea: {
340
+ title: "Chat",
341
+ show: false,
342
+ align: "center"
343
+ },
344
+ messagesArea: {
345
+ alternating: true
346
+ }
347
+ };
348
+ var meta = _objectSpread2(_objectSpread2({}, defaultOpts), options); // merge options with defaults
349
+
350
+ if (typeof parentElement === 'string') {
351
+ parentElement = document.querySelector(parentElement);
352
+ }
353
+ this._parentElement = parentElement;
354
+ this._theme = meta.theme;
355
+ this._onSend = onSend ? onSend : function () {}; // call back function for onSend
356
+ this._messageFormatter = meta.messageFormatter || null;
357
+ this._sanitize = meta.sanitize || false;
358
+ this._createWidget();
359
+ // title area
360
+ if (meta.titleArea) {
361
+ this.titleAreaSetContents(meta.titleArea.title, meta.titleArea.align);
362
+ if (meta.titleArea.show === true) {
363
+ this.titleAreaShow();
364
+ } else {
365
+ this.titleAreaHide();
366
+ }
367
+ }
368
+ // messages area
369
+ if (meta.messagesArea) {
370
+ this.messagesAreaAlternateColors(meta.messagesArea.alternating);
371
+ }
372
+ // timestamps
373
+ if (meta.showTimestamps) {
374
+ this.messagesAreaShowTimestamps(true);
375
+ }
376
+ // direction (ltr/rtl)
377
+ if (meta.direction) {
378
+ this.setDirection(meta.direction);
379
+ }
380
+ // plumbing
381
+ this._attachEventListeners();
382
+ this.trackHistory = meta.trackHistory !== false;
383
+ this._historyLimit = 10000000;
384
+ this._history = [];
385
+ }
386
+ return _createClass(quikchat, [{
387
+ key: "_createWidget",
388
+ value: function _createWidget() {
389
+ var widgetHTML = "\n <div class=\"quikchat-base ".concat(this.theme, "\">\n <div class=\"quikchat-title-area\"></div>\n <div class=\"quikchat-messages-wrapper\"><div class=\"quikchat-messages-area\" role=\"log\" aria-live=\"polite\" aria-label=\"Chat messages\"></div><button class=\"quikchat-scroll-bottom\" aria-label=\"Scroll to bottom\"></button></div>\n <div class=\"quikchat-input-area\">\n <textarea class=\"quikchat-input-textbox\" rows=\"1\" aria-label=\"Type a message\"></textarea>\n <button class=\"quikchat-input-send-btn\">Send</button>\n </div>\n </div>\n ");
390
+ this._parentElement.innerHTML = widgetHTML;
391
+ this._chatWidget = this._parentElement.querySelector('.quikchat-base');
392
+ this._titleArea = this._chatWidget.querySelector('.quikchat-title-area');
393
+ this._messagesWrapper = this._chatWidget.querySelector('.quikchat-messages-wrapper');
394
+ this._messagesArea = this._chatWidget.querySelector('.quikchat-messages-area');
395
+ this._scrollBottomBtn = this._messagesWrapper.querySelector('.quikchat-scroll-bottom');
396
+ this._inputArea = this._chatWidget.querySelector('.quikchat-input-area');
397
+ this._textEntry = this._inputArea.querySelector('.quikchat-input-textbox');
398
+ this._sendButton = this._inputArea.querySelector('.quikchat-input-send-btn');
399
+ this.msgid = 0;
400
+ }
401
+
402
+ /**
403
+ * Attach event listeners to the widget
404
+ */
405
+ }, {
406
+ key: "_attachEventListeners",
407
+ value: function _attachEventListeners() {
408
+ var _this = this;
409
+ this._sendButton.addEventListener('click', function () {
410
+ var text = _this._textEntry.value.trim();
411
+ if (text === '') return;
412
+ _this._onSend(_this, text);
413
+ });
414
+ this._textEntry.addEventListener('keydown', function (event) {
415
+ // Check if Shift + Enter is pressed
416
+ if (event.shiftKey && event.keyCode === 13) {
417
+ event.preventDefault();
418
+ var text = _this._textEntry.value.trim();
419
+ if (text === '') return;
420
+ _this._onSend(_this, text);
421
+ }
422
+ });
423
+
424
+ // Auto-grow textarea
425
+ this._textEntry.addEventListener('input', function () {
426
+ return _this._autoGrowTextarea();
427
+ });
428
+ this._messagesArea.addEventListener('scroll', function () {
429
+ var _this$_messagesArea = _this._messagesArea,
430
+ scrollTop = _this$_messagesArea.scrollTop,
431
+ scrollHeight = _this$_messagesArea.scrollHeight,
432
+ clientHeight = _this$_messagesArea.clientHeight;
433
+ _this.userScrolledUp = scrollTop + clientHeight < scrollHeight - 1;
434
+ _this._updateScrollBottomBtn();
435
+ });
436
+
437
+ // Scroll-to-bottom button
438
+ this._scrollBottomBtn.addEventListener('click', function () {
439
+ return _this.scrollToBottom();
440
+ });
441
+
442
+ // Ctrl+End to scroll to bottom
443
+ this._chatWidget.addEventListener('keydown', function (event) {
444
+ if (event.ctrlKey && event.key === 'End') {
445
+ event.preventDefault();
446
+ _this.scrollToBottom();
447
+ }
448
+ });
449
+
450
+ // Use ResizeObserver to detect parent container resize
451
+ if (typeof ResizeObserver !== 'undefined') {
452
+ this._resizeObserver = new ResizeObserver(function () {
453
+ return _this._handleContainerResize();
454
+ });
455
+ this._resizeObserver.observe(this._parentElement);
456
+ }
457
+ }
458
+
459
+ // set the onSend function callback.
460
+ }, {
461
+ key: "setCallbackOnSend",
462
+ value: function setCallbackOnSend(callback) {
463
+ this._onSend = callback;
464
+ }
465
+ // set a callback for everytime a message is added (listener)
466
+ }, {
467
+ key: "setCallbackonMessageAdded",
468
+ value: function setCallbackonMessageAdded(callback) {
469
+ this._onMessageAdded = callback;
470
+ }
471
+ }, {
472
+ key: "setCallbackonMessageAppend",
473
+ value: function setCallbackonMessageAppend(callback) {
474
+ this._onMessageAppend = callback;
475
+ }
476
+ }, {
477
+ key: "setCallbackonMessageReplace",
478
+ value: function setCallbackonMessageReplace(callback) {
479
+ this._onMessageReplace = callback;
480
+ }
481
+ }, {
482
+ key: "setCallbackonMessageDelete",
483
+ value: function setCallbackonMessageDelete(callback) {
484
+ this._onMessageDelete = callback;
485
+ }
486
+
487
+ // Public methods
488
+ }, {
489
+ key: "titleAreaToggle",
490
+ value: function titleAreaToggle() {
491
+ if (this._titleArea.style.display === 'none') {
492
+ this.titleAreaShow();
493
+ } else {
494
+ this.titleAreaHide();
495
+ }
496
+ }
497
+ }, {
498
+ key: "titleAreaShow",
499
+ value: function titleAreaShow() {
500
+ this._titleArea.style.display = '';
501
+ }
502
+ }, {
503
+ key: "titleAreaHide",
504
+ value: function titleAreaHide() {
505
+ this._titleArea.style.display = 'none';
506
+ }
507
+ }, {
508
+ key: "titleAreaSetContents",
509
+ value: function titleAreaSetContents(title) {
510
+ var align = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'center';
511
+ this._titleArea.innerHTML = title;
512
+ this._titleArea.style.textAlign = align;
513
+ }
514
+ }, {
515
+ key: "titleAreaGetContents",
516
+ value: function titleAreaGetContents() {
517
+ return this._titleArea.innerHTML;
518
+ }
519
+ }, {
520
+ key: "inputAreaToggle",
521
+ value: function inputAreaToggle() {
522
+ if (this._inputArea.style.display === 'none') {
523
+ this.inputAreaShow();
524
+ } else {
525
+ this.inputAreaHide();
526
+ }
527
+ }
528
+ }, {
529
+ key: "inputAreaShow",
530
+ value: function inputAreaShow() {
531
+ this._inputArea.style.display = '';
532
+ }
533
+ }, {
534
+ key: "inputAreaHide",
535
+ value: function inputAreaHide() {
536
+ this._inputArea.style.display = 'none';
537
+ }
538
+ }, {
539
+ key: "inputAreaSetEnabled",
540
+ value: function inputAreaSetEnabled(enabled) {
541
+ this._textEntry.disabled = !enabled;
542
+ this._sendButton.disabled = !enabled;
543
+ }
544
+ }, {
545
+ key: "inputAreaSetButtonText",
546
+ value: function inputAreaSetButtonText(text) {
547
+ this._sendButton.textContent = text;
548
+ }
549
+ }, {
550
+ key: "inputAreaGetButtonText",
551
+ value: function inputAreaGetButtonText() {
552
+ return this._sendButton.textContent;
553
+ }
554
+ }, {
555
+ key: "setDirection",
556
+ value: function setDirection(dir) {
557
+ var d = dir === 'rtl' ? 'rtl' : 'ltr';
558
+ this._chatWidget.setAttribute('dir', d);
559
+ if (d === 'rtl') {
560
+ this._chatWidget.classList.add('quikchat-rtl');
561
+ } else {
562
+ this._chatWidget.classList.remove('quikchat-rtl');
563
+ }
564
+ }
565
+ }, {
566
+ key: "getDirection",
567
+ value: function getDirection() {
568
+ return this._chatWidget.getAttribute('dir') || 'ltr';
569
+ }
570
+ }, {
571
+ key: "_handleContainerResize",
572
+ value: function _handleContainerResize() {
573
+ // Layout is handled by CSS flexbox — no JS height calculation needed.
574
+ // This hook exists for future use or custom resize callbacks.
575
+ }
576
+ }, {
577
+ key: "scrollToBottom",
578
+ value: function scrollToBottom() {
579
+ this._messagesArea.scrollTop = this._messagesArea.scrollHeight;
580
+ this.userScrolledUp = false;
581
+ this._updateScrollBottomBtn();
582
+ }
583
+ }, {
584
+ key: "_updateScrollBottomBtn",
585
+ value: function _updateScrollBottomBtn() {
586
+ if (this.userScrolledUp) {
587
+ this._scrollBottomBtn.classList.add('quikchat-scroll-bottom-visible');
588
+ } else {
589
+ this._scrollBottomBtn.classList.remove('quikchat-scroll-bottom-visible');
590
+ }
591
+ }
592
+ }, {
593
+ key: "_autoGrowTextarea",
594
+ value: function _autoGrowTextarea() {
595
+ var el = this._textEntry;
596
+ el.style.height = 'auto';
597
+ var maxHeight = parseInt(getComputedStyle(el).getPropertyValue('--quikchat-input-max-height')) || 120;
598
+ el.style.height = Math.min(el.scrollHeight, maxHeight) + 'px';
599
+ el.style.overflowY = el.scrollHeight > maxHeight ? 'auto' : 'hidden';
600
+ }
601
+ }, {
602
+ key: "_formatTimestamp",
603
+ value: function _formatTimestamp(isoString) {
604
+ var d = new Date(isoString);
605
+ var h = d.getHours();
606
+ var m = String(d.getMinutes()).padStart(2, '0');
607
+ var ampm = h >= 12 ? 'PM' : 'AM';
608
+ var h12 = h % 12 || 12;
609
+ return h12 + ':' + m + ' ' + ampm;
610
+ }
611
+ }, {
612
+ key: "messagesAreaShowTimestamps",
613
+ value: function messagesAreaShowTimestamps(show) {
614
+ if (show) {
615
+ this._messagesArea.classList.add('quikchat-show-timestamps');
616
+ } else {
617
+ this._messagesArea.classList.remove('quikchat-show-timestamps');
618
+ }
619
+ }
620
+ }, {
621
+ key: "messagesAreaShowTimestampsGet",
622
+ value: function messagesAreaShowTimestampsGet() {
623
+ return this._messagesArea.classList.contains('quikchat-show-timestamps');
624
+ }
625
+ }, {
626
+ key: "messagesAreaShowTimestampsToggle",
627
+ value: function messagesAreaShowTimestampsToggle() {
628
+ this._messagesArea.classList.toggle('quikchat-show-timestamps');
629
+ }
630
+ }, {
631
+ key: "_escapeHTML",
632
+ value: function _escapeHTML(str) {
633
+ var div = document.createElement('div');
634
+ div.textContent = str;
635
+ return div.innerHTML;
636
+ }
637
+ }, {
638
+ key: "_processContent",
639
+ value: function _processContent(content) {
640
+ if (this._sanitize === true) {
641
+ content = this._escapeHTML(content);
642
+ } else if (typeof this._sanitize === 'function') {
643
+ content = this._sanitize(content);
644
+ }
645
+ if (this._messageFormatter) {
646
+ content = this._messageFormatter(content);
647
+ }
648
+ return content;
649
+ }
650
+
651
+ //messagesArea functions
652
+ }, {
653
+ key: "messagesAreaAlternateColors",
654
+ value: function messagesAreaAlternateColors() {
655
+ var alt = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : true;
656
+ if (alt) {
657
+ this._messagesArea.classList.add('quikchat-messages-area-alt');
658
+ } else {
659
+ this._messagesArea.classList.remove('quikchat-messages-area-alt');
660
+ }
661
+ return alt === true;
662
+ }
663
+ }, {
664
+ key: "messagesAreaAlternateColorsToggle",
665
+ value: function messagesAreaAlternateColorsToggle() {
666
+ this._messagesArea.classList.toggle('quikchat-messages-area-alt');
667
+ }
668
+ }, {
669
+ key: "messagesAreaAlternateColorsGet",
670
+ value: function messagesAreaAlternateColorsGet() {
671
+ return this._messagesArea.classList.contains('quikchat-messages-area-alt');
672
+ }
673
+ // message functions
674
+ }, {
675
+ key: "messageAddFull",
676
+ value: function messageAddFull() {
677
+ var input = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {
678
+ content: "",
679
+ userString: "user",
680
+ align: "right",
681
+ role: "user",
682
+ userID: -1
683
+ };
684
+ var msgid = this.msgid;
685
+ var messageDiv = document.createElement('div');
686
+ var msgidClass = 'quikchat-msgid-' + String(msgid).padStart(10, '0');
687
+ messageDiv.classList.add('quikchat-message', msgidClass);
688
+ messageDiv.classList.add('quikchat-role-' + (input.role || 'user'));
689
+ messageDiv.classList.add('quikchat-align-' + (input.align || 'right'));
690
+ this.msgid++;
691
+ messageDiv.classList.add(this._messagesArea.children.length % 2 === 1 ? 'quikchat-message-1' : 'quikchat-message-2');
692
+
693
+ // Visibility: default true, hidden messages get display:none
694
+ var visible = input.visible !== false;
695
+ if (!visible) {
696
+ messageDiv.style.display = 'none';
697
+ }
698
+
699
+ // Tags: array of strings for group-based visibility control
700
+ var tags = Array.isArray(input.tags) ? input.tags.slice() : [];
701
+ var userDiv = document.createElement('div');
702
+ userDiv.classList.add('quikchat-user-label');
703
+ userDiv.style.textAlign = input.align;
704
+ userDiv.innerHTML = input.userString;
705
+ var contentDiv = document.createElement('div');
706
+ contentDiv.classList.add('quikchat-message-content');
707
+ contentDiv.style.textAlign = input.align;
708
+ contentDiv.innerHTML = this._processContent(input.content);
709
+ var timestamp = new Date().toISOString();
710
+ var timestampSpan = document.createElement('span');
711
+ timestampSpan.classList.add('quikchat-timestamp');
712
+ timestampSpan.textContent = this._formatTimestamp(timestamp);
713
+ messageDiv.appendChild(userDiv);
714
+ messageDiv.appendChild(contentDiv);
715
+ messageDiv.appendChild(timestampSpan);
716
+ this._messagesArea.appendChild(messageDiv);
717
+
718
+ // Scroll to the last message only if the user is not actively scrolling up
719
+ if (!this.userScrolledUp) {
720
+ this._messagesArea.scrollTop = this._messagesArea.scrollHeight;
721
+ }
722
+ this._textEntry.value = '';
723
+ this._autoGrowTextarea();
724
+ var updatedtime = timestamp;
725
+ if (this.trackHistory) {
726
+ this._history.push(_objectSpread2(_objectSpread2({
727
+ msgid: msgid
728
+ }, input), {}, {
729
+ visible: visible,
730
+ tags: tags,
731
+ timestamp: timestamp,
732
+ updatedtime: updatedtime,
733
+ messageDiv: messageDiv
734
+ }));
735
+ if (this._history.length > this._historyLimit) {
736
+ this._history.shift();
737
+ }
738
+ }
739
+ if (this._onMessageAdded) {
740
+ this._onMessageAdded(this, msgid);
741
+ }
742
+ return msgid;
743
+ }
744
+ }, {
745
+ key: "messageAddNew",
746
+ value: function messageAddNew() {
747
+ var content = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : "";
748
+ var userString = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : "user";
749
+ var align = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : "right";
750
+ var role = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : "user";
751
+ return this.messageAddFull({
752
+ content: content,
753
+ userString: userString,
754
+ align: align,
755
+ role: role
756
+ });
757
+ }
758
+ }, {
759
+ key: "messageRemove",
760
+ value: function messageRemove(n) {
761
+ var success = false;
762
+ try {
763
+ this._messagesArea.removeChild(this._messagesArea.querySelector(".quikchat-msgid-".concat(String(n).padStart(10, '0'))));
764
+ success = true;
765
+ } catch (_error) {
766
+ // Message ID not found
767
+ }
768
+ if (success) {
769
+ this._history.splice(this._history.findIndex(function (item) {
770
+ return item.msgid === n;
771
+ }), 1);
772
+ if (this._onMessageDelete) {
773
+ this._onMessageDelete(this, n);
774
+ }
775
+ }
776
+ return success;
777
+ }
778
+ /* returns the message html object from the DOM
779
+ */
780
+ }, {
781
+ key: "messageGetDOMObject",
782
+ value: function messageGetDOMObject(n) {
783
+ var msg = null;
784
+ try {
785
+ msg = this._messagesArea.querySelector(".quikchat-msgid-".concat(String(n).padStart(10, '0')));
786
+ } catch (_error) {
787
+ // Message ID not found
788
+ }
789
+ return msg;
790
+ }
791
+ /* returns the message content only
792
+ */
793
+ }, {
794
+ key: "messageGetContent",
795
+ value: function messageGetContent(n) {
796
+ var content = "";
797
+ try {
798
+ content = this._history.filter(function (item) {
799
+ return item.msgid === n;
800
+ })[0].content;
801
+ } catch (_error) {
802
+ // Message ID not found
803
+ }
804
+ return content;
805
+ }
806
+ }, {
807
+ key: "messageSetVisible",
808
+ value: function messageSetVisible(n, visible) {
809
+ var msgEl = this.messageGetDOMObject(n);
810
+ if (!msgEl) return false;
811
+ msgEl.style.display = visible ? '' : 'none';
812
+ var item = this._history.find(function (entry) {
813
+ return entry.msgid === n;
814
+ });
815
+ if (item) item.visible = visible;
816
+ return true;
817
+ }
818
+ }, {
819
+ key: "messageGetVisible",
820
+ value: function messageGetVisible(n) {
821
+ var item = this._history.find(function (entry) {
822
+ return entry.msgid === n;
823
+ });
824
+ return item ? item.visible !== false : false;
825
+ }
826
+ }, {
827
+ key: "messageToggleVisible",
828
+ value: function messageToggleVisible(n) {
829
+ var current = this.messageGetVisible(n);
830
+ return this.messageSetVisible(n, !current);
831
+ }
832
+ }, {
833
+ key: "messageSetVisibleByTag",
834
+ value: function messageSetVisibleByTag(tag, visible) {
835
+ var count = 0;
836
+ var _iterator = _createForOfIteratorHelper(this._history),
837
+ _step;
838
+ try {
839
+ for (_iterator.s(); !(_step = _iterator.n()).done;) {
840
+ var item = _step.value;
841
+ if (item.tags && item.tags.includes(tag)) {
842
+ this.messageSetVisible(item.msgid, visible);
843
+ count++;
844
+ }
845
+ }
846
+ } catch (err) {
847
+ _iterator.e(err);
848
+ } finally {
849
+ _iterator.f();
850
+ }
851
+ return count;
852
+ }
853
+ }, {
854
+ key: "messageGetTags",
855
+ value: function messageGetTags(n) {
856
+ var item = this._history.find(function (entry) {
857
+ return entry.msgid === n;
858
+ });
859
+ return item && item.tags ? item.tags.slice() : [];
860
+ }
861
+ }, {
862
+ key: "messageSetTags",
863
+ value: function messageSetTags(n, tags) {
864
+ var item = this._history.find(function (entry) {
865
+ return entry.msgid === n;
866
+ });
867
+ if (!item) return false;
868
+ item.tags = Array.isArray(tags) ? tags.slice() : [];
869
+ return true;
870
+ }
871
+
872
+ /* append message to the message content
873
+ */
874
+ }, {
875
+ key: "messageAppendContent",
876
+ value: function messageAppendContent(n, content) {
877
+ var success = false;
878
+ try {
879
+ var msgEl = this._messagesArea.querySelector(".quikchat-msgid-".concat(String(n).padStart(10, '0')));
880
+ var item = this._history.filter(function (entry) {
881
+ return entry.msgid === n;
882
+ })[0];
883
+ item.content += content;
884
+ item.updatedtime = new Date().toISOString();
885
+ msgEl.querySelector('.quikchat-message-content').innerHTML = this._processContent(item.content);
886
+ msgEl.classList.remove('quikchat-typing');
887
+ success = true;
888
+ if (!this.userScrolledUp) {
889
+ this._messagesArea.scrollTop = this._messagesArea.scrollHeight;
890
+ }
891
+ if (this._onMessageAppend) {
892
+ this._onMessageAppend(this, n, content);
893
+ }
894
+ } catch (_error) {
895
+ // Message ID not found
896
+ }
897
+ return success;
898
+ }
899
+
900
+ /* replace message content
901
+ */
902
+ }, {
903
+ key: "messageReplaceContent",
904
+ value: function messageReplaceContent(n, content) {
905
+ var success = false;
906
+ try {
907
+ var msgEl = this._messagesArea.querySelector(".quikchat-msgid-".concat(String(n).padStart(10, '0')));
908
+ var item = this._history.filter(function (entry) {
909
+ return entry.msgid === n;
910
+ })[0];
911
+ item.content = content;
912
+ item.updatedtime = new Date().toISOString();
913
+ msgEl.querySelector('.quikchat-message-content').innerHTML = this._processContent(content);
914
+ msgEl.classList.remove('quikchat-typing');
915
+ success = true;
916
+ if (!this.userScrolledUp) {
917
+ this._messagesArea.scrollTop = this._messagesArea.scrollHeight;
918
+ }
919
+ if (this._onMessageReplace) {
920
+ this._onMessageReplace(this, n, content);
921
+ }
922
+ } catch (_error) {
923
+ // Message ID not found
924
+ }
925
+ return success;
926
+ }
927
+ }, {
928
+ key: "messageAddTypingIndicator",
929
+ value: function messageAddTypingIndicator() {
930
+ var userString = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : '';
931
+ var align = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'left';
932
+ var msgid = this.messageAddFull({
933
+ content: '',
934
+ userString: userString,
935
+ align: align,
936
+ role: 'assistant'
937
+ });
938
+ var msgEl = this.messageGetDOMObject(msgid);
939
+ msgEl.classList.add('quikchat-typing');
940
+ var contentDiv = msgEl.querySelector('.quikchat-message-content');
941
+ contentDiv.innerHTML = '<span class="quikchat-typing-dots"><span>.</span><span>.</span><span>.</span></span>';
942
+ return msgid;
943
+ }
944
+ }, {
945
+ key: "setMessageFormatter",
946
+ value: function setMessageFormatter(formatter) {
947
+ this._messageFormatter = formatter;
948
+ }
949
+ }, {
950
+ key: "setSanitize",
951
+ value: function setSanitize(sanitize) {
952
+ this._sanitize = sanitize;
953
+ }
954
+
955
+ // history functions
956
+ /**
957
+ *
958
+ * @param {*} n
959
+ * @param {*} m
960
+ * @returns array of history messages
961
+ */
962
+ }, {
963
+ key: "historyGet",
964
+ value: function historyGet(n, m) {
965
+ if (n === undefined) {
966
+ return this._history.slice();
967
+ }
968
+ if (m === undefined) {
969
+ if (n < 0) {
970
+ return this._history.slice(n);
971
+ }
972
+ return this._history.slice(n, n + 1);
973
+ }
974
+ return this._history.slice(n, m);
975
+ }
976
+ }, {
977
+ key: "historyClear",
978
+ value: function historyClear() {
979
+ this.msgid = 0;
980
+ this._history = [];
981
+ }
982
+ }, {
983
+ key: "historyGetLength",
984
+ value: function historyGetLength() {
985
+ return this._history.length;
986
+ }
987
+ }, {
988
+ key: "historyGetMessage",
989
+ value: function historyGetMessage(n) {
990
+ if (n >= 0 && n < this._history.length) {
991
+ return this._history[n];
992
+ }
993
+ return {};
994
+ }
995
+ }, {
996
+ key: "historyGetMessageContent",
997
+ value: function historyGetMessageContent(n) {
998
+ if (n >= 0 && n < this._history.length) {
999
+ return this._history[n].content;
1000
+ }
1001
+ return "";
1002
+ }
1003
+ }, {
1004
+ key: "historyExport",
1005
+ value: function historyExport() {
1006
+ return this._history.map(function (item) {
1007
+ return {
1008
+ msgid: item.msgid,
1009
+ content: item.content,
1010
+ userString: item.userString,
1011
+ align: item.align,
1012
+ role: item.role,
1013
+ userID: item.userID,
1014
+ visible: item.visible,
1015
+ tags: item.tags ? item.tags.slice() : [],
1016
+ timestamp: item.timestamp,
1017
+ updatedtime: item.updatedtime
1018
+ };
1019
+ });
1020
+ }
1021
+ }, {
1022
+ key: "historyImport",
1023
+ value: function historyImport(data) {
1024
+ // Clear existing messages from DOM and history
1025
+ this._messagesArea.innerHTML = '';
1026
+ this._history = [];
1027
+ this.msgid = 0;
1028
+ var _iterator2 = _createForOfIteratorHelper(data),
1029
+ _step2;
1030
+ try {
1031
+ for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {
1032
+ var entry = _step2.value;
1033
+ this.messageAddFull({
1034
+ content: entry.content || '',
1035
+ userString: entry.userString || 'user',
1036
+ align: entry.align || 'right',
1037
+ role: entry.role || 'user',
1038
+ userID: entry.userID,
1039
+ visible: entry.visible,
1040
+ tags: entry.tags
1041
+ });
1042
+ }
1043
+ } catch (err) {
1044
+ _iterator2.e(err);
1045
+ } finally {
1046
+ _iterator2.f();
1047
+ }
1048
+ }
1049
+ }, {
1050
+ key: "changeTheme",
1051
+ value: function changeTheme(newTheme) {
1052
+ this._chatWidget.classList.remove(this._theme);
1053
+ this._chatWidget.classList.add(newTheme);
1054
+ this._theme = newTheme;
1055
+ }
1056
+ }, {
1057
+ key: "theme",
1058
+ get: function get() {
1059
+ return this._theme;
1060
+ }
1061
+ }], [{
1062
+ key: "version",
1063
+ value: function version() {
1064
+ return {
1065
+ "version": "1.2.4",
1066
+ "license": "BSD-2",
1067
+ "url": "https://github/deftio/quikchat"
1068
+ };
1069
+ }
1070
+
1071
+ /**
1072
+ * quikchat.loremIpsum() - Generate a simple string of Lorem Ipsum text (sample typographer's text) of numChars in length.
1073
+ * borrowed from github.com/deftio/bitwrench.js
1074
+ * @param {number} numChars - The number of characters to generate (random btw 25 and 150 if undefined).
1075
+ * @param {number} [startSpot=0] - The starting index in the Lorem Ipsum text. If undefined, a random startSpot will be generated.
1076
+ * @param {boolean} [startWithCapitalLetter=true] - If true, capitalize the first character or inject a capital letter if the first character isn't a capital letter.
1077
+ *
1078
+ * @returns {string} A string of Lorem Ipsum text.
1079
+ *
1080
+ * @example
1081
+ * // Returns 200 characters of Lorem Ipsum starting from index 50
1082
+ * loremIpsum(200, 50);
1083
+ *
1084
+ * @example
1085
+ * //Returns a 200 Lorem Ipsum characters starting from a random index
1086
+ * loremIpsum(200);
1087
+ */
1088
+ }, {
1089
+ key: "loremIpsum",
1090
+ value: function loremIpsum(numChars) {
1091
+ var startSpot = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : undefined;
1092
+ var startWithCapitalLetter = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : true;
1093
+ var loremText = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. ";
1094
+ if (typeof numChars !== "number") {
1095
+ numChars = Math.floor(Math.random() * 126) + 25;
1096
+ }
1097
+ if (startSpot === undefined) {
1098
+ startSpot = Math.floor(Math.random() * loremText.length);
1099
+ }
1100
+ startSpot = startSpot % loremText.length;
1101
+
1102
+ // Move startSpot to the next non-whitespace and non-punctuation character
1103
+ while (loremText[startSpot] === ' ' || /[.,:;!?]/.test(loremText[startSpot])) {
1104
+ startSpot = (startSpot + 1) % loremText.length;
1105
+ }
1106
+ var l = loremText.substring(startSpot) + loremText.substring(0, startSpot);
1107
+ var s = "";
1108
+ while (numChars > 0) {
1109
+ s += numChars < l.length ? l.substring(0, numChars) : l;
1110
+ numChars -= l.length;
1111
+ }
1112
+ if (s[s.length - 1] === " ") {
1113
+ s = s.substring(0, s.length - 1) + "."; // always end on non-whitespace. "." was chosen arbitrarily.
1114
+ }
1115
+ if (startWithCapitalLetter) {
1116
+ s = s[0].toUpperCase() + s.substring(1);
1117
+ }
1118
+ return s;
1119
+ }
1120
+ }]);
1121
+ }();
1122
+
1123
+ /**
1124
+ * quikdown_bd - Bidirectional Markdown Parser
1125
+ * @version 1.1.1
1126
+ * @license BSD-2-Clause
1127
+ * @copyright DeftIO 2025
1128
+ */
1129
+ /**
1130
+ * quikdown - A minimal markdown parser optimized for chat/LLM output
1131
+ * Supports tables, code blocks, lists, and common formatting
1132
+ * @param {string} markdown - The markdown source text
1133
+ * @param {Object} options - Optional configuration object
1134
+ * @param {Function} options.fence_plugin - Custom renderer for fenced code blocks
1135
+ * (content, fence_string) => html string
1136
+ * @param {boolean} options.inline_styles - If true, uses inline styles instead of classes
1137
+ * @param {boolean} options.bidirectional - If true, adds data-qd attributes for source tracking
1138
+ * @param {boolean} options.lazy_linefeeds - If true, single newlines become <br> tags
1139
+ * @returns {string} - The rendered HTML
1140
+ */
1141
+
1142
+ // Version will be injected at build time
1143
+ const quikdownVersion = '1.1.1';
1144
+
1145
+ // Constants for reuse
1146
+ const CLASS_PREFIX = 'quikdown-';
1147
+ const PLACEHOLDER_CB = '§CB';
1148
+ const PLACEHOLDER_IC = '§IC';
1149
+
1150
+ // Escape map at module level
1151
+ const ESC_MAP = {'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'};
1152
+
1153
+ // Single source of truth for all style definitions - optimized
1154
+ const QUIKDOWN_STYLES = {
1155
+ h1: 'font-size:2em;font-weight:600;margin:.67em 0;text-align:left',
1156
+ h2: 'font-size:1.5em;font-weight:600;margin:.83em 0',
1157
+ h3: 'font-size:1.25em;font-weight:600;margin:1em 0',
1158
+ h4: 'font-size:1em;font-weight:600;margin:1.33em 0',
1159
+ h5: 'font-size:.875em;font-weight:600;margin:1.67em 0',
1160
+ h6: 'font-size:.85em;font-weight:600;margin:2em 0',
1161
+ pre: 'background:#f4f4f4;padding:10px;border-radius:4px;overflow-x:auto;margin:1em 0',
1162
+ code: 'background:#f0f0f0;padding:2px 4px;border-radius:3px;font-family:monospace',
1163
+ blockquote: 'border-left:4px solid #ddd;margin-left:0;padding-left:1em',
1164
+ table: 'border-collapse:collapse;width:100%;margin:1em 0',
1165
+ th: 'border:1px solid #ddd;padding:8px;background-color:#f2f2f2;font-weight:bold;text-align:left',
1166
+ td: 'border:1px solid #ddd;padding:8px;text-align:left',
1167
+ hr: 'border:none;border-top:1px solid #ddd;margin:1em 0',
1168
+ img: 'max-width:100%;height:auto',
1169
+ a: 'color:#06c;text-decoration:underline',
1170
+ strong: 'font-weight:bold',
1171
+ em: 'font-style:italic',
1172
+ del: 'text-decoration:line-through',
1173
+ ul: 'margin:.5em 0;padding-left:2em',
1174
+ ol: 'margin:.5em 0;padding-left:2em',
1175
+ li: 'margin:.25em 0',
1176
+ // Task list specific styles
1177
+ 'task-item': 'list-style:none',
1178
+ 'task-checkbox': 'margin-right:.5em'
1179
+ };
1180
+
1181
+ // Factory function to create getAttr for a given context
1182
+ function createGetAttr(inline_styles, styles) {
1183
+ return function(tag, additionalStyle = '') {
1184
+ if (inline_styles) {
1185
+ let style = styles[tag];
1186
+ if (!style && !additionalStyle) return '';
1187
+
1188
+ // Remove default text-align if we're adding a different alignment
1189
+ if (additionalStyle && additionalStyle.includes('text-align') && style && style.includes('text-align')) {
1190
+ style = style.replace(/text-align:[^;]+;?/, '').trim();
1191
+ if (style && !style.endsWith(';')) style += ';';
1192
+ }
1193
+
1194
+ /* istanbul ignore next - defensive: additionalStyle without style doesn't occur with current tags */
1195
+ const fullStyle = additionalStyle ? (style ? `${style}${additionalStyle}` : additionalStyle) : style;
1196
+ return ` style="${fullStyle}"`;
1197
+ } else {
1198
+ const classAttr = ` class="${CLASS_PREFIX}${tag}"`;
1199
+ // Apply inline styles for alignment even when using CSS classes
1200
+ if (additionalStyle) {
1201
+ return `${classAttr} style="${additionalStyle}"`;
1202
+ }
1203
+ return classAttr;
1204
+ }
1205
+ };
1206
+ }
1207
+
1208
+ function quikdown(markdown, options = {}) {
1209
+ if (!markdown || typeof markdown !== 'string') {
1210
+ return '';
1211
+ }
1212
+
1213
+ const { fence_plugin, inline_styles = false, bidirectional = false, lazy_linefeeds = false } = options;
1214
+ const styles = QUIKDOWN_STYLES; // Use module-level styles
1215
+ const getAttr = createGetAttr(inline_styles, styles); // Create getAttr once
1216
+
1217
+ // Escape HTML entities to prevent XSS
1218
+ function escapeHtml(text) {
1219
+ return text.replace(/[&<>"']/g, m => ESC_MAP[m]);
1220
+ }
1221
+
1222
+ // Helper to add data-qd attributes for bidirectional support
1223
+ const dataQd = bidirectional ? (marker) => ` data-qd="${escapeHtml(marker)}"` : () => '';
1224
+
1225
+ // Sanitize URLs to prevent XSS attacks
1226
+ function sanitizeUrl(url, allowUnsafe = false) {
1227
+ /* istanbul ignore next - defensive programming, regex ensures url is never empty */
1228
+ if (!url) return '';
1229
+
1230
+ // If unsafe URLs are explicitly allowed, return as-is
1231
+ if (allowUnsafe) return url;
1232
+
1233
+ const trimmedUrl = url.trim();
1234
+ const lowerUrl = trimmedUrl.toLowerCase();
1235
+
1236
+ // Block dangerous protocols
1237
+ const dangerousProtocols = ['javascript:', 'vbscript:', 'data:'];
1238
+
1239
+ for (const protocol of dangerousProtocols) {
1240
+ if (lowerUrl.startsWith(protocol)) {
1241
+ // Exception: Allow data:image/* for images
1242
+ if (protocol === 'data:' && lowerUrl.startsWith('data:image/')) {
1243
+ return trimmedUrl;
1244
+ }
1245
+ // Return safe empty link for dangerous protocols
1246
+ return '#';
1247
+ }
1248
+ }
1249
+
1250
+ return trimmedUrl;
1251
+ }
1252
+
1253
+ // Process the markdown in phases
1254
+ let html = markdown;
1255
+
1256
+ // Phase 1: Extract and protect code blocks and inline code
1257
+ const codeBlocks = [];
1258
+ const inlineCodes = [];
1259
+
1260
+ // Extract fenced code blocks first (supports both ``` and ~~~)
1261
+ // Match paired fences - ``` with ``` and ~~~ with ~~~
1262
+ // Fence must be at start of line
1263
+ html = html.replace(/^(```|~~~)([^\n]*)\n([\s\S]*?)^\1$/gm, (match, fence, lang, code) => {
1264
+ const placeholder = `${PLACEHOLDER_CB}${codeBlocks.length}§`;
1265
+
1266
+ // Trim the language specification
1267
+ const langTrimmed = lang ? lang.trim() : '';
1268
+
1269
+ // If custom fence plugin is provided, use it (v1.1.0: object format required)
1270
+ if (fence_plugin && fence_plugin.render && typeof fence_plugin.render === 'function') {
1271
+ codeBlocks.push({
1272
+ lang: langTrimmed,
1273
+ code: code.trimEnd(),
1274
+ custom: true,
1275
+ fence: fence,
1276
+ hasReverse: !!fence_plugin.reverse
1277
+ });
1278
+ } else {
1279
+ codeBlocks.push({
1280
+ lang: langTrimmed,
1281
+ code: escapeHtml(code.trimEnd()),
1282
+ custom: false,
1283
+ fence: fence
1284
+ });
1285
+ }
1286
+ return placeholder;
1287
+ });
1288
+
1289
+ // Extract inline code
1290
+ html = html.replace(/`([^`]+)`/g, (match, code) => {
1291
+ const placeholder = `${PLACEHOLDER_IC}${inlineCodes.length}§`;
1292
+ inlineCodes.push(escapeHtml(code));
1293
+ return placeholder;
1294
+ });
1295
+
1296
+ // Now escape HTML in the rest of the content
1297
+ html = escapeHtml(html);
1298
+
1299
+ // Phase 2: Process block elements
1300
+
1301
+ // Process tables
1302
+ html = processTable(html, getAttr);
1303
+
1304
+ // Process headings (supports optional trailing #'s)
1305
+ html = html.replace(/^(#{1,6})\s+(.+?)\s*#*$/gm, (match, hashes, content) => {
1306
+ const level = hashes.length;
1307
+ return `<h${level}${getAttr('h' + level)}${dataQd(hashes)}>${content}</h${level}>`;
1308
+ });
1309
+
1310
+ // Process blockquotes (must handle escaped > since we already escaped HTML)
1311
+ html = html.replace(/^&gt;\s+(.+)$/gm, `<blockquote${getAttr('blockquote')}>$1</blockquote>`);
1312
+ // Merge consecutive blockquotes
1313
+ html = html.replace(/<\/blockquote>\n<blockquote>/g, '\n');
1314
+
1315
+ // Process horizontal rules (allow trailing spaces)
1316
+ html = html.replace(/^---+\s*$/gm, `<hr${getAttr('hr')}>`);
1317
+
1318
+ // Process lists
1319
+ html = processLists(html, getAttr, inline_styles, bidirectional);
1320
+
1321
+ // Phase 3: Process inline elements
1322
+
1323
+ // Images (must come before links, with URL sanitization)
1324
+ html = html.replace(/!\[([^\]]*)\]\(([^)]+)\)/g, (match, alt, src) => {
1325
+ const sanitizedSrc = sanitizeUrl(src, options.allow_unsafe_urls);
1326
+ const altAttr = bidirectional && alt ? ` data-qd-alt="${escapeHtml(alt)}"` : '';
1327
+ const srcAttr = bidirectional ? ` data-qd-src="${escapeHtml(src)}"` : '';
1328
+ return `<img${getAttr('img')} src="${sanitizedSrc}" alt="${alt}"${altAttr}${srcAttr}${dataQd('!')}>`;
1329
+ });
1330
+
1331
+ // Links (with URL sanitization)
1332
+ html = html.replace(/\[([^\]]+)\]\(([^)]+)\)/g, (match, text, href) => {
1333
+ // Sanitize URL to prevent XSS
1334
+ const sanitizedHref = sanitizeUrl(href, options.allow_unsafe_urls);
1335
+ const isExternal = /^https?:\/\//i.test(sanitizedHref);
1336
+ const rel = isExternal ? ' rel="noopener noreferrer"' : '';
1337
+ const textAttr = bidirectional ? ` data-qd-text="${escapeHtml(text)}"` : '';
1338
+ return `<a${getAttr('a')} href="${sanitizedHref}"${rel}${textAttr}${dataQd('[')}>${text}</a>`;
1339
+ });
1340
+
1341
+ // Autolinks - convert bare URLs to clickable links
1342
+ html = html.replace(/(^|\s)(https?:\/\/[^\s<]+)/g, (match, prefix, url) => {
1343
+ const sanitizedUrl = sanitizeUrl(url, options.allow_unsafe_urls);
1344
+ return `${prefix}<a${getAttr('a')} href="${sanitizedUrl}" rel="noopener noreferrer">${url}</a>`;
1345
+ });
1346
+
1347
+ // Process inline formatting (bold, italic, strikethrough)
1348
+ const inlinePatterns = [
1349
+ [/\*\*(.+?)\*\*/g, 'strong', '**'],
1350
+ [/__(.+?)__/g, 'strong', '__'],
1351
+ [/(?<!\*)\*(?!\*)(.+?)(?<!\*)\*(?!\*)/g, 'em', '*'],
1352
+ [/(?<!_)_(?!_)(.+?)(?<!_)_(?!_)/g, 'em', '_'],
1353
+ [/~~(.+?)~~/g, 'del', '~~']
1354
+ ];
1355
+
1356
+ inlinePatterns.forEach(([pattern, tag, marker]) => {
1357
+ html = html.replace(pattern, `<${tag}${getAttr(tag)}${dataQd(marker)}>$1</${tag}>`);
1358
+ });
1359
+
1360
+ // Line breaks
1361
+ if (lazy_linefeeds) {
1362
+ // Lazy linefeeds: single newline becomes <br> (except between paragraphs and after/before block elements)
1363
+ const blocks = [];
1364
+ let bi = 0;
1365
+
1366
+ // Protect tables and lists
1367
+ html = html.replace(/<(table|[uo]l)[^>]*>[\s\S]*?<\/\1>/g, m => {
1368
+ blocks[bi] = m;
1369
+ return `§B${bi++}§`;
1370
+ });
1371
+
1372
+ // Handle paragraphs and block elements
1373
+ html = html.replace(/\n\n+/g, '§P§')
1374
+ // After block elements
1375
+ .replace(/(<\/(?:h[1-6]|blockquote|pre)>)\n/g, '$1§N§')
1376
+ .replace(/(<(?:h[1-6]|blockquote|pre|hr)[^>]*>)\n/g, '$1§N§')
1377
+ // Before block elements
1378
+ .replace(/\n(<(?:h[1-6]|blockquote|pre|hr)[^>]*>)/g, '§N§$1')
1379
+ .replace(/\n(§B\d+§)/g, '§N§$1')
1380
+ .replace(/(§B\d+§)\n/g, '$1§N§')
1381
+ // Convert remaining newlines
1382
+ .replace(/\n/g, `<br${getAttr('br')}>`)
1383
+ // Restore
1384
+ .replace(/§N§/g, '\n')
1385
+ .replace(/§P§/g, '</p><p>');
1386
+
1387
+ // Restore protected blocks
1388
+ blocks.forEach((b, i) => html = html.replace(`§B${i}§`, b));
1389
+
1390
+ html = '<p>' + html + '</p>';
1391
+ } else {
1392
+ // Standard: two spaces at end of line for line breaks
1393
+ html = html.replace(/ $/gm, `<br${getAttr('br')}>`);
1394
+
1395
+ // Paragraphs (double newlines)
1396
+ // Don't add </p> after block elements (they're not in paragraphs)
1397
+ html = html.replace(/\n\n+/g, (match, offset) => {
1398
+ // Check if we're after a block element closing tag
1399
+ const before = html.substring(0, offset);
1400
+ if (before.match(/<\/(h[1-6]|blockquote|ul|ol|table|pre|hr)>$/)) {
1401
+ return '<p>'; // Just open a new paragraph
1402
+ }
1403
+ return '</p><p>'; // Normal paragraph break
1404
+ });
1405
+ html = '<p>' + html + '</p>';
1406
+ }
1407
+
1408
+ // Clean up empty paragraphs and unwrap block elements
1409
+ const cleanupPatterns = [
1410
+ [/<p><\/p>/g, ''],
1411
+ [/<p>(<h[1-6][^>]*>)/g, '$1'],
1412
+ [/(<\/h[1-6]>)<\/p>/g, '$1'],
1413
+ [/<p>(<blockquote[^>]*>)/g, '$1'],
1414
+ [/(<\/blockquote>)<\/p>/g, '$1'],
1415
+ [/<p>(<ul[^>]*>|<ol[^>]*>)/g, '$1'],
1416
+ [/(<\/ul>|<\/ol>)<\/p>/g, '$1'],
1417
+ [/<p>(<hr[^>]*>)<\/p>/g, '$1'],
1418
+ [/<p>(<table[^>]*>)/g, '$1'],
1419
+ [/(<\/table>)<\/p>/g, '$1'],
1420
+ [/<p>(<pre[^>]*>)/g, '$1'],
1421
+ [/(<\/pre>)<\/p>/g, '$1'],
1422
+ [new RegExp(`<p>(${PLACEHOLDER_CB}\\d+§)<\/p>`, 'g'), '$1']
1423
+ ];
1424
+
1425
+ cleanupPatterns.forEach(([pattern, replacement]) => {
1426
+ html = html.replace(pattern, replacement);
1427
+ });
1428
+
1429
+ // Fix orphaned closing </p> tags after block elements
1430
+ // When a paragraph follows a block element, ensure it has opening <p>
1431
+ html = html.replace(/(<\/(?:h[1-6]|blockquote|ul|ol|table|pre|hr)>)\n([^<])/g, '$1\n<p>$2');
1432
+
1433
+ // Phase 4: Restore code blocks and inline code
1434
+
1435
+ // Restore code blocks
1436
+ codeBlocks.forEach((block, i) => {
1437
+ let replacement;
1438
+
1439
+ if (block.custom && fence_plugin && fence_plugin.render) {
1440
+ // Use custom fence plugin (v1.1.0: object format with render function)
1441
+ replacement = fence_plugin.render(block.code, block.lang);
1442
+
1443
+ // If plugin returns undefined, fall back to default rendering
1444
+ if (replacement === undefined) {
1445
+ const langClass = !inline_styles && block.lang ? ` class="language-${block.lang}"` : '';
1446
+ const codeAttr = inline_styles ? getAttr('code') : langClass;
1447
+ const langAttr = bidirectional && block.lang ? ` data-qd-lang="${escapeHtml(block.lang)}"` : '';
1448
+ const fenceAttr = bidirectional ? ` data-qd-fence="${escapeHtml(block.fence)}"` : '';
1449
+ replacement = `<pre${getAttr('pre')}${fenceAttr}${langAttr}><code${codeAttr}>${escapeHtml(block.code)}</code></pre>`;
1450
+ } else if (bidirectional) {
1451
+ // If bidirectional and plugin provided HTML, add data attributes for roundtrip
1452
+ replacement = replacement.replace(/^<(\w+)/,
1453
+ `<$1 data-qd-fence="${escapeHtml(block.fence)}" data-qd-lang="${escapeHtml(block.lang)}" data-qd-source="${escapeHtml(block.code)}"`);
1454
+ }
1455
+ } else {
1456
+ // Default rendering
1457
+ const langClass = !inline_styles && block.lang ? ` class="language-${block.lang}"` : '';
1458
+ const codeAttr = inline_styles ? getAttr('code') : langClass;
1459
+ const langAttr = bidirectional && block.lang ? ` data-qd-lang="${escapeHtml(block.lang)}"` : '';
1460
+ const fenceAttr = bidirectional ? ` data-qd-fence="${escapeHtml(block.fence)}"` : '';
1461
+ replacement = `<pre${getAttr('pre')}${fenceAttr}${langAttr}><code${codeAttr}>${block.code}</code></pre>`;
1462
+ }
1463
+
1464
+ const placeholder = `${PLACEHOLDER_CB}${i}§`;
1465
+ html = html.replace(placeholder, replacement);
1466
+ });
1467
+
1468
+ // Restore inline code
1469
+ inlineCodes.forEach((code, i) => {
1470
+ const placeholder = `${PLACEHOLDER_IC}${i}§`;
1471
+ html = html.replace(placeholder, `<code${getAttr('code')}${dataQd('`')}>${code}</code>`);
1472
+ });
1473
+
1474
+ return html.trim();
1475
+ }
1476
+
1477
+ /**
1478
+ * Process inline markdown formatting
1479
+ */
1480
+ function processInlineMarkdown(text, getAttr) {
1481
+
1482
+ // Process inline formatting patterns
1483
+ const patterns = [
1484
+ [/\*\*(.+?)\*\*/g, 'strong'],
1485
+ [/__(.+?)__/g, 'strong'],
1486
+ [/(?<!\*)\*(?!\*)(.+?)(?<!\*)\*(?!\*)/g, 'em'],
1487
+ [/(?<!_)_(?!_)(.+?)(?<!_)_(?!_)/g, 'em'],
1488
+ [/~~(.+?)~~/g, 'del'],
1489
+ [/`([^`]+)`/g, 'code']
1490
+ ];
1491
+
1492
+ patterns.forEach(([pattern, tag]) => {
1493
+ text = text.replace(pattern, `<${tag}${getAttr(tag)}>$1</${tag}>`);
1494
+ });
1495
+
1496
+ return text;
1497
+ }
1498
+
1499
+ /**
1500
+ * Process markdown tables
1501
+ */
1502
+ function processTable(text, getAttr) {
1503
+ const lines = text.split('\n');
1504
+ const result = [];
1505
+ let inTable = false;
1506
+ let tableLines = [];
1507
+
1508
+ for (let i = 0; i < lines.length; i++) {
1509
+ const line = lines[i].trim();
1510
+
1511
+ // Check if this line looks like a table row (with or without trailing |)
1512
+ if (line.includes('|') && (line.startsWith('|') || /[^\\|]/.test(line))) {
1513
+ if (!inTable) {
1514
+ inTable = true;
1515
+ tableLines = [];
1516
+ }
1517
+ tableLines.push(line);
1518
+ } else {
1519
+ // Not a table line
1520
+ if (inTable) {
1521
+ // Process the accumulated table
1522
+ const tableHtml = buildTable(tableLines, getAttr);
1523
+ if (tableHtml) {
1524
+ result.push(tableHtml);
1525
+ } else {
1526
+ // Not a valid table, restore original lines
1527
+ result.push(...tableLines);
1528
+ }
1529
+ inTable = false;
1530
+ tableLines = [];
1531
+ }
1532
+ result.push(lines[i]);
1533
+ }
1534
+ }
1535
+
1536
+ // Handle table at end of text
1537
+ if (inTable && tableLines.length > 0) {
1538
+ const tableHtml = buildTable(tableLines, getAttr);
1539
+ if (tableHtml) {
1540
+ result.push(tableHtml);
1541
+ } else {
1542
+ result.push(...tableLines);
1543
+ }
1544
+ }
1545
+
1546
+ return result.join('\n');
1547
+ }
1548
+
1549
+ /**
1550
+ * Build an HTML table from markdown table lines
1551
+ */
1552
+ function buildTable(lines, getAttr) {
1553
+
1554
+ if (lines.length < 2) return null;
1555
+
1556
+ // Check for separator line (second line should be the separator)
1557
+ let separatorIndex = -1;
1558
+ for (let i = 1; i < lines.length; i++) {
1559
+ // Support separator with or without leading/trailing pipes
1560
+ if (/^\|?[\s\-:|]+\|?$/.test(lines[i]) && lines[i].includes('-')) {
1561
+ separatorIndex = i;
1562
+ break;
1563
+ }
1564
+ }
1565
+
1566
+ if (separatorIndex === -1) return null;
1567
+
1568
+ const headerLines = lines.slice(0, separatorIndex);
1569
+ const bodyLines = lines.slice(separatorIndex + 1);
1570
+
1571
+ // Parse alignment from separator
1572
+ const separator = lines[separatorIndex];
1573
+ // Handle pipes at start/end or not
1574
+ const separatorCells = separator.trim().replace(/^\|/, '').replace(/\|$/, '').split('|');
1575
+ const alignments = separatorCells.map(cell => {
1576
+ const trimmed = cell.trim();
1577
+ if (trimmed.startsWith(':') && trimmed.endsWith(':')) return 'center';
1578
+ if (trimmed.endsWith(':')) return 'right';
1579
+ return 'left';
1580
+ });
1581
+
1582
+ let html = `<table${getAttr('table')}>\n`;
1583
+
1584
+ // Build header
1585
+ // Note: headerLines will always have length > 0 since separatorIndex starts from 1
1586
+ html += `<thead${getAttr('thead')}>\n`;
1587
+ headerLines.forEach(line => {
1588
+ html += `<tr${getAttr('tr')}>\n`;
1589
+ // Handle pipes at start/end or not
1590
+ const cells = line.trim().replace(/^\|/, '').replace(/\|$/, '').split('|');
1591
+ cells.forEach((cell, i) => {
1592
+ const alignStyle = alignments[i] && alignments[i] !== 'left' ? `text-align:${alignments[i]}` : '';
1593
+ const processedCell = processInlineMarkdown(cell.trim(), getAttr);
1594
+ html += `<th${getAttr('th', alignStyle)}>${processedCell}</th>\n`;
1595
+ });
1596
+ html += '</tr>\n';
1597
+ });
1598
+ html += '</thead>\n';
1599
+
1600
+ // Build body
1601
+ if (bodyLines.length > 0) {
1602
+ html += `<tbody${getAttr('tbody')}>\n`;
1603
+ bodyLines.forEach(line => {
1604
+ html += `<tr${getAttr('tr')}>\n`;
1605
+ // Handle pipes at start/end or not
1606
+ const cells = line.trim().replace(/^\|/, '').replace(/\|$/, '').split('|');
1607
+ cells.forEach((cell, i) => {
1608
+ const alignStyle = alignments[i] && alignments[i] !== 'left' ? `text-align:${alignments[i]}` : '';
1609
+ const processedCell = processInlineMarkdown(cell.trim(), getAttr);
1610
+ html += `<td${getAttr('td', alignStyle)}>${processedCell}</td>\n`;
1611
+ });
1612
+ html += '</tr>\n';
1613
+ });
1614
+ html += '</tbody>\n';
1615
+ }
1616
+
1617
+ html += '</table>';
1618
+ return html;
1619
+ }
1620
+
1621
+ /**
1622
+ * Process markdown lists (ordered and unordered)
1623
+ */
1624
+ function processLists(text, getAttr, inline_styles, bidirectional) {
1625
+
1626
+ const lines = text.split('\n');
1627
+ const result = [];
1628
+ let listStack = []; // Track nested lists
1629
+
1630
+ // Helper to escape HTML for data-qd attributes
1631
+ const escapeHtml = (text) => text.replace(/[&<>"']/g, m => ({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'})[m]);
1632
+ const dataQd = bidirectional ? (marker) => ` data-qd="${escapeHtml(marker)}"` : () => '';
1633
+
1634
+ for (let i = 0; i < lines.length; i++) {
1635
+ const line = lines[i];
1636
+ const match = line.match(/^(\s*)([*\-+]|\d+\.)\s+(.+)$/);
1637
+
1638
+ if (match) {
1639
+ const [, indent, marker, content] = match;
1640
+ const level = Math.floor(indent.length / 2);
1641
+ const isOrdered = /^\d+\./.test(marker);
1642
+ const listType = isOrdered ? 'ol' : 'ul';
1643
+
1644
+ // Check for task list items
1645
+ let listItemContent = content;
1646
+ let taskListClass = '';
1647
+ const taskMatch = content.match(/^\[([x ])\]\s+(.*)$/i);
1648
+ if (taskMatch && !isOrdered) {
1649
+ const [, checked, taskContent] = taskMatch;
1650
+ const isChecked = checked.toLowerCase() === 'x';
1651
+ const checkboxAttr = inline_styles
1652
+ ? ' style="margin-right:.5em"'
1653
+ : ` class="${CLASS_PREFIX}task-checkbox"`;
1654
+ listItemContent = `<input type="checkbox"${checkboxAttr}${isChecked ? ' checked' : ''} disabled> ${taskContent}`;
1655
+ taskListClass = inline_styles ? ' style="list-style:none"' : ` class="${CLASS_PREFIX}task-item"`;
1656
+ }
1657
+
1658
+ // Close deeper levels
1659
+ while (listStack.length > level + 1) {
1660
+ const list = listStack.pop();
1661
+ result.push(`</${list.type}>`);
1662
+ }
1663
+
1664
+ // Open new level if needed
1665
+ if (listStack.length === level) {
1666
+ // Need to open a new list
1667
+ listStack.push({ type: listType, level });
1668
+ result.push(`<${listType}${getAttr(listType)}>`);
1669
+ } else if (listStack.length === level + 1) {
1670
+ // Check if we need to switch list type
1671
+ const currentList = listStack[listStack.length - 1];
1672
+ if (currentList.type !== listType) {
1673
+ result.push(`</${currentList.type}>`);
1674
+ listStack.pop();
1675
+ listStack.push({ type: listType, level });
1676
+ result.push(`<${listType}${getAttr(listType)}>`);
1677
+ }
1678
+ }
1679
+
1680
+ const liAttr = taskListClass || getAttr('li');
1681
+ result.push(`<li${liAttr}${dataQd(marker)}>${listItemContent}</li>`);
1682
+ } else {
1683
+ // Not a list item, close all lists
1684
+ while (listStack.length > 0) {
1685
+ const list = listStack.pop();
1686
+ result.push(`</${list.type}>`);
1687
+ }
1688
+ result.push(line);
1689
+ }
1690
+ }
1691
+
1692
+ // Close any remaining lists
1693
+ while (listStack.length > 0) {
1694
+ const list = listStack.pop();
1695
+ result.push(`</${list.type}>`);
1696
+ }
1697
+
1698
+ return result.join('\n');
1699
+ }
1700
+
1701
+ /**
1702
+ * Emit CSS styles for quikdown elements
1703
+ * @param {string} prefix - Optional class prefix (default: 'quikdown-')
1704
+ * @param {string} theme - Optional theme: 'light' (default) or 'dark'
1705
+ * @returns {string} CSS string with quikdown styles
1706
+ */
1707
+ quikdown.emitStyles = function(prefix = 'quikdown-', theme = 'light') {
1708
+ const styles = QUIKDOWN_STYLES;
1709
+
1710
+ // Define theme color overrides
1711
+ const themeOverrides = {
1712
+ dark: {
1713
+ '#f4f4f4': '#2a2a2a', // pre background
1714
+ '#f0f0f0': '#2a2a2a', // code background
1715
+ '#f2f2f2': '#2a2a2a', // th background
1716
+ '#ddd': '#3a3a3a', // borders
1717
+ '#06c': '#6db3f2', // links
1718
+ _textColor: '#e0e0e0'
1719
+ },
1720
+ light: {
1721
+ _textColor: '#333' // Explicit text color for light theme
1722
+ }
1723
+ };
1724
+
1725
+ let css = '';
1726
+ for (const [tag, style] of Object.entries(styles)) {
1727
+ let themedStyle = style;
1728
+
1729
+ // Apply theme overrides if dark theme
1730
+ if (theme === 'dark' && themeOverrides.dark) {
1731
+ // Replace colors
1732
+ for (const [oldColor, newColor] of Object.entries(themeOverrides.dark)) {
1733
+ if (!oldColor.startsWith('_')) {
1734
+ themedStyle = themedStyle.replace(new RegExp(oldColor, 'g'), newColor);
1735
+ }
1736
+ }
1737
+
1738
+ // Add text color for certain elements in dark theme
1739
+ const needsTextColor = ['h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'td', 'li', 'blockquote'];
1740
+ if (needsTextColor.includes(tag)) {
1741
+ themedStyle += `;color:${themeOverrides.dark._textColor}`;
1742
+ }
1743
+ } else if (theme === 'light' && themeOverrides.light) {
1744
+ // Add explicit text color for light theme elements too
1745
+ const needsTextColor = ['h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'td', 'li', 'blockquote'];
1746
+ if (needsTextColor.includes(tag)) {
1747
+ themedStyle += `;color:${themeOverrides.light._textColor}`;
1748
+ }
1749
+ }
1750
+
1751
+ css += `.${prefix}${tag} { ${themedStyle} }\n`;
1752
+ }
1753
+
1754
+ return css;
1755
+ };
1756
+
1757
+ /**
1758
+ * Configure quikdown with options and return a function
1759
+ * @param {Object} options - Configuration options
1760
+ * @returns {Function} Configured quikdown function
1761
+ */
1762
+ quikdown.configure = function(options) {
1763
+ return function(markdown) {
1764
+ return quikdown(markdown, options);
1765
+ };
1766
+ };
1767
+
1768
+ /**
1769
+ * Version information
1770
+ */
1771
+ quikdown.version = quikdownVersion;
1772
+
1773
+ // Export for both CommonJS and ES6
1774
+ /* istanbul ignore next */
1775
+ if (typeof module !== 'undefined' && module.exports) {
1776
+ module.exports = quikdown;
1777
+ }
1778
+
1779
+ // For browser global
1780
+ /* istanbul ignore next */
1781
+ if (typeof window !== 'undefined') {
1782
+ window.quikdown = quikdown;
1783
+ }
1784
+
1785
+ /**
1786
+ * quikdown_bd - Bidirectional markdown/HTML converter
1787
+ * Extends core quikdown with HTML→Markdown conversion
1788
+ *
1789
+ * Uses data-qd attributes to preserve original markdown syntax
1790
+ * Enables HTML→Markdown conversion for quikdown-generated HTML
1791
+ */
1792
+
1793
+
1794
+ /**
1795
+ * Create bidirectional version by extending quikdown
1796
+ * This wraps quikdown and adds the toMarkdown method
1797
+ */
1798
+ function quikdown_bd(markdown, options = {}) {
1799
+ // Use core quikdown with bidirectional flag to add data-qd attributes
1800
+ return quikdown(markdown, { ...options, bidirectional: true });
1801
+ }
1802
+
1803
+ // Copy all properties and methods from quikdown (including version)
1804
+ Object.keys(quikdown).forEach(key => {
1805
+ quikdown_bd[key] = quikdown[key];
1806
+ });
1807
+
1808
+ // Add the toMarkdown method for HTML→Markdown conversion
1809
+ quikdown_bd.toMarkdown = function(htmlOrElement, options = {}) {
1810
+ // Accept either HTML string or DOM element
1811
+ let container;
1812
+ if (typeof htmlOrElement === 'string') {
1813
+ container = document.createElement('div');
1814
+ container.innerHTML = htmlOrElement;
1815
+ } else if (htmlOrElement instanceof Element) {
1816
+ /* istanbul ignore next - browser-only code path, not testable in jsdom */
1817
+ container = htmlOrElement;
1818
+ } else {
1819
+ return '';
1820
+ }
1821
+
1822
+ // Walk the DOM tree and reconstruct markdown
1823
+ function walkNode(node, parentContext = {}) {
1824
+ if (node.nodeType === Node.TEXT_NODE) {
1825
+ // Return text content, preserving whitespace where needed
1826
+ return node.textContent;
1827
+ }
1828
+
1829
+ if (node.nodeType !== Node.ELEMENT_NODE) {
1830
+ return '';
1831
+ }
1832
+
1833
+ const tag = node.tagName.toLowerCase();
1834
+ const dataQd = node.getAttribute('data-qd');
1835
+
1836
+ // Process children with context
1837
+ let childContent = '';
1838
+ for (let child of node.childNodes) {
1839
+ childContent += walkNode(child, { parentTag: tag, ...parentContext });
1840
+ }
1841
+
1842
+ // Determine markdown based on element and attributes
1843
+ switch (tag) {
1844
+ case 'h1':
1845
+ case 'h2':
1846
+ case 'h3':
1847
+ case 'h4':
1848
+ case 'h5':
1849
+ case 'h6':
1850
+ const level = parseInt(tag[1]);
1851
+ const prefix = dataQd || '#'.repeat(level);
1852
+ return `${prefix} ${childContent.trim()}\n\n`;
1853
+
1854
+ case 'strong':
1855
+ case 'b':
1856
+ if (!childContent) return ''; // Don't add markers for empty content
1857
+ const boldMarker = dataQd || '**';
1858
+ return `${boldMarker}${childContent}${boldMarker}`;
1859
+
1860
+ case 'em':
1861
+ case 'i':
1862
+ if (!childContent) return ''; // Don't add markers for empty content
1863
+ const emMarker = dataQd || '*';
1864
+ return `${emMarker}${childContent}${emMarker}`;
1865
+
1866
+ case 'del':
1867
+ case 's':
1868
+ case 'strike':
1869
+ if (!childContent) return ''; // Don't add markers for empty content
1870
+ const delMarker = dataQd || '~~';
1871
+ return `${delMarker}${childContent}${delMarker}`;
1872
+
1873
+ case 'code':
1874
+ // Note: code inside pre is handled directly by the pre case using querySelector
1875
+ if (!childContent) return ''; // Don't add markers for empty content
1876
+ const codeMarker = dataQd || '`';
1877
+ return `${codeMarker}${childContent}${codeMarker}`;
1878
+
1879
+ case 'pre':
1880
+ const fence = node.getAttribute('data-qd-fence') || dataQd || '```';
1881
+ const lang = node.getAttribute('data-qd-lang') || '';
1882
+
1883
+ // Check if this was created by a fence plugin with reverse handler
1884
+ if (options.fence_plugin && options.fence_plugin.reverse && lang) {
1885
+ try {
1886
+ const result = options.fence_plugin.reverse(node);
1887
+ if (result && result.content) {
1888
+ const fenceMarker = result.fence || fence;
1889
+ const langStr = result.lang || lang;
1890
+ return `${fenceMarker}${langStr}\n${result.content}\n${fenceMarker}\n\n`;
1891
+ }
1892
+ } catch (err) {
1893
+ console.warn('Fence reverse handler error:', err);
1894
+ // Fall through to default handling
1895
+ }
1896
+ }
1897
+
1898
+ // Fallback: use data-qd-source if available
1899
+ const source = node.getAttribute('data-qd-source');
1900
+ if (source) {
1901
+ return `${fence}${lang}\n${source}\n${fence}\n\n`;
1902
+ }
1903
+
1904
+ // Final fallback: extract text content
1905
+ const codeEl = node.querySelector('code');
1906
+ const codeContent = codeEl ? codeEl.textContent : childContent;
1907
+ return `${fence}${lang}\n${codeContent.trimEnd()}\n${fence}\n\n`;
1908
+
1909
+ case 'blockquote':
1910
+ const quoteMarker = dataQd || '>';
1911
+ const lines = childContent.trim().split('\n');
1912
+ return lines.map(line => `${quoteMarker} ${line}`).join('\n') + '\n\n';
1913
+
1914
+ case 'hr':
1915
+ const hrMarker = dataQd || '---';
1916
+ return `${hrMarker}\n\n`;
1917
+
1918
+ case 'br':
1919
+ const brMarker = dataQd || ' ';
1920
+ return `${brMarker}\n`;
1921
+
1922
+ case 'a':
1923
+ const linkText = node.getAttribute('data-qd-text') || childContent.trim();
1924
+ const href = node.getAttribute('href') || '';
1925
+ // Check for autolinks
1926
+ if (linkText === href && !dataQd) {
1927
+ return `<${href}>`;
1928
+ }
1929
+ return `[${linkText}](${href})`;
1930
+
1931
+ case 'img':
1932
+ const alt = node.getAttribute('data-qd-alt') || node.getAttribute('alt') || '';
1933
+ const src = node.getAttribute('data-qd-src') || node.getAttribute('src') || '';
1934
+ const imgMarker = dataQd || '!';
1935
+ return `${imgMarker}[${alt}](${src})`;
1936
+
1937
+ case 'ul':
1938
+ case 'ol':
1939
+ return walkList(node, tag === 'ol') + '\n';
1940
+
1941
+ case 'li':
1942
+ // Handled by list processor
1943
+ return childContent;
1944
+
1945
+ case 'table':
1946
+ return walkTable(node) + '\n\n';
1947
+
1948
+ case 'p':
1949
+ // Check if it's actually a paragraph or just a wrapper
1950
+ if (childContent.trim()) {
1951
+ // Check if paragraph ends with a line that's just whitespace
1952
+ // This indicates an intentional blank line before the next element
1953
+ const lines = childContent.split('\n');
1954
+ let content = childContent.trim();
1955
+
1956
+ // If the last line(s) are just whitespace, preserve one blank line
1957
+ if (lines.length > 1) {
1958
+ let trailingBlankLines = 0;
1959
+ for (let i = lines.length - 1; i >= 0; i--) {
1960
+ if (lines[i].trim() === '') {
1961
+ trailingBlankLines++;
1962
+ } else {
1963
+ break;
1964
+ }
1965
+ }
1966
+ if (trailingBlankLines > 0) {
1967
+ // Add a line with just a space, followed by single newline
1968
+ // The \n\n will be added below for paragraph separation
1969
+ content = content + '\n ';
1970
+ // Only add one newline since we're preserving the space line
1971
+ return content + '\n';
1972
+ }
1973
+ }
1974
+
1975
+ return content + '\n\n';
1976
+ }
1977
+ return '';
1978
+
1979
+ case 'div':
1980
+ // Check if this was created by a fence plugin with reverse handler
1981
+ const divLang = node.getAttribute('data-qd-lang');
1982
+ const divFence = node.getAttribute('data-qd-fence');
1983
+
1984
+ if (divLang && options.fence_plugin && options.fence_plugin.reverse) {
1985
+ try {
1986
+ const result = options.fence_plugin.reverse(node);
1987
+ if (result && result.content) {
1988
+ const fenceMarker = result.fence || divFence || '```';
1989
+ const langStr = result.lang || divLang;
1990
+ return `${fenceMarker}${langStr}\n${result.content}\n${fenceMarker}\n\n`;
1991
+ }
1992
+ } catch (err) {
1993
+ console.warn('Fence reverse handler error:', err);
1994
+ // Fall through to default handling
1995
+ }
1996
+ }
1997
+
1998
+ // Fallback: use data-qd-source if available
1999
+ const divSource = node.getAttribute('data-qd-source');
2000
+ if (divSource && divFence) {
2001
+ return `${divFence}${divLang || ''}\n${divSource}\n${divFence}\n\n`;
2002
+ }
2003
+
2004
+ // Check if it's a mermaid container
2005
+ if (node.classList && node.classList.contains('mermaid-container')) {
2006
+ const fence = node.getAttribute('data-qd-fence') || '```';
2007
+ const lang = node.getAttribute('data-qd-lang') || 'mermaid';
2008
+
2009
+ // First check for data-qd-source attribute on the container
2010
+ const source = node.getAttribute('data-qd-source');
2011
+ if (source) {
2012
+ // Decode HTML entities from the attribute (mainly &quot;)
2013
+ const temp = document.createElement('textarea');
2014
+ temp.innerHTML = source;
2015
+ const code = temp.value;
2016
+ return `${fence}${lang}\n${code}\n${fence}\n\n`;
2017
+ }
2018
+
2019
+ // Check for source on the pre.mermaid element
2020
+ const mermaidPre = node.querySelector('pre.mermaid');
2021
+ if (mermaidPre) {
2022
+ const preSource = mermaidPre.getAttribute('data-qd-source');
2023
+ if (preSource) {
2024
+ const temp = document.createElement('textarea');
2025
+ temp.innerHTML = preSource;
2026
+ const code = temp.value;
2027
+ return `${fence}${lang}\n${code}\n${fence}\n\n`;
2028
+ }
2029
+ }
2030
+
2031
+ // Fallback: Look for the legacy .mermaid-source element
2032
+ const sourceElement = node.querySelector('.mermaid-source');
2033
+ if (sourceElement) {
2034
+ // Decode HTML entities
2035
+ const temp = document.createElement('div');
2036
+ temp.innerHTML = sourceElement.innerHTML;
2037
+ const code = temp.textContent;
2038
+ return `${fence}${lang}\n${code}\n${fence}\n\n`;
2039
+ }
2040
+
2041
+ // Final fallback: try to extract from the mermaid element (unreliable after rendering)
2042
+ const mermaidElement = node.querySelector('.mermaid');
2043
+ if (mermaidElement && mermaidElement.textContent.includes('graph')) {
2044
+ return `${fence}${lang}\n${mermaidElement.textContent.trim()}\n${fence}\n\n`;
2045
+ }
2046
+ }
2047
+ // Check if it's a standalone mermaid diagram (legacy)
2048
+ if (node.classList && node.classList.contains('mermaid')) {
2049
+ const fence = node.getAttribute('data-qd-fence') || '```';
2050
+ const lang = node.getAttribute('data-qd-lang') || 'mermaid';
2051
+ const code = node.textContent.trim();
2052
+ return `${fence}${lang}\n${code}\n${fence}\n\n`;
2053
+ }
2054
+ // Pass through other divs
2055
+ return childContent;
2056
+
2057
+ case 'span':
2058
+ // Pass through container elements
2059
+ return childContent;
2060
+
2061
+ default:
2062
+ return childContent;
2063
+ }
2064
+ }
2065
+
2066
+ // Walk list elements
2067
+ function walkList(listNode, isOrdered, depth = 0) {
2068
+ let result = '';
2069
+ let index = 1;
2070
+ const indent = ' '.repeat(depth);
2071
+
2072
+ for (let child of listNode.children) {
2073
+ if (child.tagName !== 'LI') continue;
2074
+
2075
+ const dataQd = child.getAttribute('data-qd');
2076
+ let marker = dataQd || (isOrdered ? `${index}.` : '-');
2077
+
2078
+ // Check for task list checkbox
2079
+ const checkbox = child.querySelector('input[type="checkbox"]');
2080
+ if (checkbox) {
2081
+ const checked = checkbox.checked ? 'x' : ' ';
2082
+ marker = '-';
2083
+ // Get text without the checkbox
2084
+ let text = '';
2085
+ for (let node of child.childNodes) {
2086
+ if (node.nodeType === Node.TEXT_NODE) {
2087
+ text += node.textContent;
2088
+ } else if (node.tagName && node.tagName !== 'INPUT') {
2089
+ text += walkNode(node);
2090
+ }
2091
+ }
2092
+ result += `${indent}${marker} [${checked}] ${text.trim()}\n`;
2093
+ } else {
2094
+ let itemContent = '';
2095
+
2096
+ for (let node of child.childNodes) {
2097
+ if (node.tagName === 'UL' || node.tagName === 'OL') {
2098
+ itemContent += walkList(node, node.tagName === 'OL', depth + 1);
2099
+ } else {
2100
+ itemContent += walkNode(node);
2101
+ }
2102
+ }
2103
+
2104
+ result += `${indent}${marker} ${itemContent.trim()}\n`;
2105
+ }
2106
+
2107
+ index++;
2108
+ }
2109
+
2110
+ return result;
2111
+ }
2112
+
2113
+ // Walk table elements
2114
+ function walkTable(table) {
2115
+ let result = '';
2116
+ const alignData = table.getAttribute('data-qd-align');
2117
+ const alignments = alignData ? alignData.split(',') : [];
2118
+
2119
+ // Process header
2120
+ const thead = table.querySelector('thead');
2121
+ if (thead) {
2122
+ const headerRow = thead.querySelector('tr');
2123
+ if (headerRow) {
2124
+ const headers = [];
2125
+ for (let th of headerRow.querySelectorAll('th')) {
2126
+ headers.push(th.textContent.trim());
2127
+ }
2128
+ result += '| ' + headers.join(' | ') + ' |\n';
2129
+
2130
+ // Add separator with alignment
2131
+ const separators = headers.map((_, i) => {
2132
+ const align = alignments[i] || 'left';
2133
+ if (align === 'center') return ':---:';
2134
+ if (align === 'right') return '---:';
2135
+ return '---';
2136
+ });
2137
+ result += '| ' + separators.join(' | ') + ' |\n';
2138
+ }
2139
+ }
2140
+
2141
+ // Process body
2142
+ const tbody = table.querySelector('tbody');
2143
+ if (tbody) {
2144
+ for (let row of tbody.querySelectorAll('tr')) {
2145
+ const cells = [];
2146
+ for (let td of row.querySelectorAll('td')) {
2147
+ cells.push(td.textContent.trim());
2148
+ }
2149
+ if (cells.length > 0) {
2150
+ result += '| ' + cells.join(' | ') + ' |\n';
2151
+ }
2152
+ }
2153
+ }
2154
+
2155
+ return result.trim();
2156
+ }
2157
+
2158
+ // Process the DOM tree
2159
+ let markdown = walkNode(container);
2160
+
2161
+ // Clean up
2162
+ markdown = markdown.replace(/\n{3,}/g, '\n\n'); // Remove excessive newlines
2163
+ markdown = markdown.trim();
2164
+
2165
+ return markdown;
2166
+ };
2167
+
2168
+ // Override the configure method to return a bidirectional version
2169
+ quikdown_bd.configure = function(options) {
2170
+ return function(markdown) {
2171
+ return quikdown_bd(markdown, options);
2172
+ };
2173
+ };
2174
+
2175
+ // Set version
2176
+ // Version is already copied from quikdown via Object.keys loop
2177
+
2178
+ // Export for both module and browser
2179
+ /* istanbul ignore next */
2180
+ if (typeof module !== 'undefined' && module.exports) {
2181
+ module.exports = quikdown_bd;
2182
+ }
2183
+
2184
+ /* istanbul ignore next */
2185
+ if (typeof window !== 'undefined') {
2186
+ window.quikdown_bd = quikdown_bd;
2187
+ }
2188
+
2189
+ // CDN URLs for dynamic loading (same as quikdown editor uses)
2190
+ var CDN = {
2191
+ hljs: 'https://unpkg.com/@highlightjs/cdn-assets/highlight.min.js',
2192
+ hljsCSS: 'https://unpkg.com/@highlightjs/cdn-assets/styles/github.min.css',
2193
+ mathjax: 'https://cdn.jsdelivr.net/npm/mathjax@3.2.2/es5/tex-svg.js',
2194
+ mermaid: 'https://unpkg.com/mermaid/dist/mermaid.min.js',
2195
+ leaflet: 'https://unpkg.com/leaflet@1.9.4/dist/leaflet.js',
2196
+ leafletCSS: 'https://unpkg.com/leaflet@1.9.4/dist/leaflet.css',
2197
+ dompurify: 'https://unpkg.com/dompurify/dist/purify.min.js'
2198
+ };
2199
+
2200
+ // Load a script from CDN (cached — only loads once)
2201
+ var _loaded = {};
2202
+ function loadScript(src) {
2203
+ if (_loaded[src]) return _loaded[src];
2204
+ _loaded[src] = new Promise(function (resolve, reject) {
2205
+ var s = document.createElement('script');
2206
+ s.src = src;
2207
+ s.onload = function () {
2208
+ return resolve(true);
2209
+ };
2210
+ s.onerror = function () {
2211
+ _loaded[src] = null;
2212
+ reject(new Error('Failed to load: ' + src));
2213
+ };
2214
+ document.head.appendChild(s);
2215
+ });
2216
+ return _loaded[src];
2217
+ }
2218
+ function loadCSS(href) {
2219
+ if (_loaded[href]) return _loaded[href];
2220
+ _loaded[href] = new Promise(function (resolve) {
2221
+ var link = document.createElement('link');
2222
+ link.rel = 'stylesheet';
2223
+ link.href = href;
2224
+ link.onload = function () {
2225
+ return resolve(true);
2226
+ };
2227
+ document.head.appendChild(link);
2228
+ setTimeout(resolve, 1000); // CSS doesn't always fire onload
2229
+ });
2230
+ return _loaded[href];
2231
+ }
2232
+
2233
+ /**
2234
+ * Process fence blocks rendered by quikdown/bd.
2235
+ * Detects code blocks with language tags and renders them with the appropriate library.
2236
+ * Libraries are loaded from CDN on first use.
2237
+ */
2238
+ function postProcessMessage(_x) {
2239
+ return _postProcessMessage.apply(this, arguments);
2240
+ }
2241
+ /**
2242
+ * quikchat-md-full: batteries-included build.
2243
+ * Uses quikdown/bd for markdown parsing, then post-processes fence blocks
2244
+ * with dynamically loaded renderers (highlight.js, MathJax, Mermaid, Leaflet, etc.).
2245
+ */
2246
+ function _postProcessMessage() {
2247
+ _postProcessMessage = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee(el) {
2248
+ var codeBlocks, langSet, specialLangs, needsHljs, svgBlocks, htmlBlocks, _iterator, _step, _block2, _pre2, src, _container2, mathBlocks, hasInlineMath, mermaidBlocks, _iterator2, _step2, block, pre, container, mermaidId, _yield$window$mermaid, svg, geoBlocks, _iterator3, _step3, _block, _pre, geojson, _container, map, layer, tableBlocks, jsonBlocks, _t3, _t8, _t0;
2249
+ return _regenerator().w(function (_context) {
2250
+ while (1) switch (_context.p = _context.n) {
2251
+ case 0:
2252
+ if (el) {
2253
+ _context.n = 1;
2254
+ break;
2255
+ }
2256
+ return _context.a(2);
2257
+ case 1:
2258
+ // --- Syntax highlighting (highlight.js) ---
2259
+ codeBlocks = el.querySelectorAll('pre.quikdown-pre code[class*="language-"]');
2260
+ if (!(codeBlocks.length > 0)) {
2261
+ _context.n = 6;
2262
+ break;
2263
+ }
2264
+ langSet = new Set();
2265
+ codeBlocks.forEach(function (cb) {
2266
+ var match = cb.className.match(/language-(\S+)/);
2267
+ if (match) langSet.add(match[1]);
2268
+ });
2269
+
2270
+ // Skip languages handled by other renderers
2271
+ specialLangs = new Set(['svg', 'html', 'math', 'tex', 'latex', 'katex', 'mermaid', 'geojson', 'csv', 'tsv', 'psv', 'json', 'json5', 'stl']);
2272
+ needsHljs = _toConsumableArray(langSet).some(function (l) {
2273
+ return !specialLangs.has(l);
2274
+ });
2275
+ if (!(needsHljs && !window.hljs)) {
2276
+ _context.n = 5;
2277
+ break;
2278
+ }
2279
+ _context.p = 2;
2280
+ _context.n = 3;
2281
+ return Promise.all([loadScript(CDN.hljs), loadCSS(CDN.hljsCSS)]);
2282
+ case 3:
2283
+ _context.n = 5;
2284
+ break;
2285
+ case 4:
2286
+ _context.p = 4;
2287
+ _context.v;
2288
+ case 5:
2289
+ if (window.hljs) {
2290
+ codeBlocks.forEach(function (cb) {
2291
+ var match = cb.className.match(/language-(\S+)/);
2292
+ if (match && !specialLangs.has(match[1]) && !cb.classList.contains('hljs')) {
2293
+ window.hljs.highlightElement(cb);
2294
+ }
2295
+ });
2296
+ }
2297
+ case 6:
2298
+ // --- SVG (inline, no external lib) ---
2299
+ svgBlocks = el.querySelectorAll('pre.quikdown-pre[data-qd-lang="svg"], pre.quikdown-pre code.language-svg');
2300
+ svgBlocks.forEach(function (block) {
2301
+ var pre = block.closest('pre') || block;
2302
+ var code = pre.querySelector('code') || pre;
2303
+ var svgSource = code.textContent;
2304
+ try {
2305
+ var parser = new DOMParser();
2306
+ var doc = parser.parseFromString(svgSource, 'image/svg+xml');
2307
+ if (!doc.querySelector('parsererror')) {
2308
+ var svg = doc.documentElement;
2309
+ // Sanitize: remove scripts and event handlers
2310
+ svg.querySelectorAll('script').forEach(function (s) {
2311
+ return s.remove();
2312
+ });
2313
+ var walker = document.createTreeWalker(svg, NodeFilter.SHOW_ELEMENT);
2314
+ var node = walker.nextNode();
2315
+ while (node) {
2316
+ for (var i = node.attributes.length - 1; i >= 0; i--) {
2317
+ var attr = node.attributes[i];
2318
+ if (attr.name.startsWith('on') || attr.value.includes('javascript:')) {
2319
+ node.removeAttribute(attr.name);
2320
+ }
2321
+ }
2322
+ node = walker.nextNode();
2323
+ }
2324
+ var container = document.createElement('div');
2325
+ container.className = 'qde-svg-container';
2326
+ container.innerHTML = new XMLSerializer().serializeToString(svg);
2327
+ pre.replaceWith(container);
2328
+ }
2329
+ } catch (_e) {/* leave as code block */}
2330
+ });
2331
+
2332
+ // --- HTML (inline, sanitized with DOMPurify) ---
2333
+ htmlBlocks = el.querySelectorAll('pre.quikdown-pre code.language-html');
2334
+ _iterator = _createForOfIteratorHelper(htmlBlocks);
2335
+ _context.p = 7;
2336
+ _iterator.s();
2337
+ case 8:
2338
+ if ((_step = _iterator.n()).done) {
2339
+ _context.n = 16;
2340
+ break;
2341
+ }
2342
+ _block2 = _step.value;
2343
+ _pre2 = _block2.closest('pre');
2344
+ if (_pre2) {
2345
+ _context.n = 9;
2346
+ break;
2347
+ }
2348
+ return _context.a(3, 15);
2349
+ case 9:
2350
+ // Only render if the code is likely meant as rendered HTML (short snippets)
2351
+ // Skip if it looks like documentation (contains doctype, html, head tags)
2352
+ src = _block2.textContent;
2353
+ if (!src.match(/<(!DOCTYPE|html|head|body)/i)) {
2354
+ _context.n = 10;
2355
+ break;
2356
+ }
2357
+ return _context.a(3, 15);
2358
+ case 10:
2359
+ if (window.DOMPurify) {
2360
+ _context.n = 14;
2361
+ break;
2362
+ }
2363
+ _context.p = 11;
2364
+ _context.n = 12;
2365
+ return loadScript(CDN.dompurify);
2366
+ case 12:
2367
+ _context.n = 14;
2368
+ break;
2369
+ case 13:
2370
+ _context.p = 13;
2371
+ _context.v;
2372
+ return _context.a(3, 15);
2373
+ case 14:
2374
+ if (window.DOMPurify) {
2375
+ _container2 = document.createElement('div');
2376
+ _container2.className = 'qde-html-container';
2377
+ _container2.innerHTML = window.DOMPurify.sanitize(src);
2378
+ _pre2.replaceWith(_container2);
2379
+ }
2380
+ case 15:
2381
+ _context.n = 8;
2382
+ break;
2383
+ case 16:
2384
+ _context.n = 18;
2385
+ break;
2386
+ case 17:
2387
+ _context.p = 17;
2388
+ _t3 = _context.v;
2389
+ _iterator.e(_t3);
2390
+ case 18:
2391
+ _context.p = 18;
2392
+ _iterator.f();
2393
+ return _context.f(18);
2394
+ case 19:
2395
+ // --- Math (MathJax) ---
2396
+ // Look for math fences and inline math ($...$, $$...$$)
2397
+ mathBlocks = el.querySelectorAll('pre.quikdown-pre code.language-math, pre.quikdown-pre code.language-tex, pre.quikdown-pre code.language-latex, pre.quikdown-pre code.language-katex');
2398
+ hasInlineMath = el.innerHTML.match(/\$\$[\s\S]+?\$\$|\$[^$\n]+?\$/);
2399
+ if (!(mathBlocks.length > 0 || hasInlineMath)) {
2400
+ _context.n = 28;
2401
+ break;
2402
+ }
2403
+ if (!(!window.MathJax || !window.MathJax.typesetPromise)) {
2404
+ _context.n = 24;
2405
+ break;
2406
+ }
2407
+ if (window.mathJaxLoading) {
2408
+ _context.n = 24;
2409
+ break;
2410
+ }
2411
+ window.mathJaxLoading = true;
2412
+ window.MathJax = {
2413
+ loader: {
2414
+ load: ['input/tex', 'output/svg']
2415
+ },
2416
+ tex: {
2417
+ inlineMath: [['$', '$'], ['\\(', '\\)']],
2418
+ displayMath: [['$$', '$$'], ['\\[', '\\]']],
2419
+ processEscapes: true,
2420
+ processEnvironments: true
2421
+ },
2422
+ options: {
2423
+ renderActions: {
2424
+ addMenu: []
2425
+ }
2426
+ },
2427
+ svg: {
2428
+ fontCache: 'none'
2429
+ },
2430
+ startup: {
2431
+ typeset: false
2432
+ }
2433
+ };
2434
+ _context.p = 20;
2435
+ _context.n = 21;
2436
+ return loadScript(CDN.mathjax);
2437
+ case 21:
2438
+ _context.n = 23;
2439
+ break;
2440
+ case 22:
2441
+ _context.p = 22;
2442
+ _context.v;
2443
+ case 23:
2444
+ window.mathJaxLoading = false;
2445
+ case 24:
2446
+ // Convert math fence blocks to divs MathJax can process
2447
+ mathBlocks.forEach(function (block) {
2448
+ var pre = block.closest('pre');
2449
+ if (!pre) return;
2450
+ var mathDiv = document.createElement('div');
2451
+ mathDiv.className = 'math-display';
2452
+ mathDiv.textContent = '$$' + block.textContent + '$$';
2453
+ pre.replaceWith(mathDiv);
2454
+ });
2455
+ if (!(window.MathJax && window.MathJax.typesetPromise)) {
2456
+ _context.n = 28;
2457
+ break;
2458
+ }
2459
+ _context.p = 25;
2460
+ _context.n = 26;
2461
+ return window.MathJax.typesetPromise([el]);
2462
+ case 26:
2463
+ _context.n = 28;
2464
+ break;
2465
+ case 27:
2466
+ _context.p = 27;
2467
+ _context.v;
2468
+ case 28:
2469
+ // --- Mermaid diagrams ---
2470
+ mermaidBlocks = el.querySelectorAll('pre.quikdown-pre code.language-mermaid');
2471
+ if (!(mermaidBlocks.length > 0)) {
2472
+ _context.n = 43;
2473
+ break;
2474
+ }
2475
+ if (window.mermaid) {
2476
+ _context.n = 32;
2477
+ break;
2478
+ }
2479
+ _context.p = 29;
2480
+ _context.n = 30;
2481
+ return loadScript(CDN.mermaid);
2482
+ case 30:
2483
+ if (window.mermaid) {
2484
+ window.mermaid.initialize({
2485
+ startOnLoad: false,
2486
+ theme: 'default'
2487
+ });
2488
+ }
2489
+ _context.n = 32;
2490
+ break;
2491
+ case 31:
2492
+ _context.p = 31;
2493
+ _context.v;
2494
+ case 32:
2495
+ if (!window.mermaid) {
2496
+ _context.n = 43;
2497
+ break;
2498
+ }
2499
+ _iterator2 = _createForOfIteratorHelper(mermaidBlocks);
2500
+ _context.p = 33;
2501
+ _iterator2.s();
2502
+ case 34:
2503
+ if ((_step2 = _iterator2.n()).done) {
2504
+ _context.n = 40;
2505
+ break;
2506
+ }
2507
+ block = _step2.value;
2508
+ pre = block.closest('pre');
2509
+ if (pre) {
2510
+ _context.n = 35;
2511
+ break;
2512
+ }
2513
+ return _context.a(3, 39);
2514
+ case 35:
2515
+ container = document.createElement('div');
2516
+ container.className = 'qde-mermaid-container';
2517
+ mermaidId = 'mermaid-' + Math.random().toString(36).substring(2, 9);
2518
+ _context.p = 36;
2519
+ _context.n = 37;
2520
+ return window.mermaid.render(mermaidId, block.textContent);
2521
+ case 37:
2522
+ _yield$window$mermaid = _context.v;
2523
+ svg = _yield$window$mermaid.svg;
2524
+ container.innerHTML = svg;
2525
+ pre.replaceWith(container);
2526
+ _context.n = 39;
2527
+ break;
2528
+ case 38:
2529
+ _context.p = 38;
2530
+ _context.v;
2531
+ case 39:
2532
+ _context.n = 34;
2533
+ break;
2534
+ case 40:
2535
+ _context.n = 42;
2536
+ break;
2537
+ case 41:
2538
+ _context.p = 41;
2539
+ _t8 = _context.v;
2540
+ _iterator2.e(_t8);
2541
+ case 42:
2542
+ _context.p = 42;
2543
+ _iterator2.f();
2544
+ return _context.f(42);
2545
+ case 43:
2546
+ // --- GeoJSON / Leaflet maps ---
2547
+ geoBlocks = el.querySelectorAll('pre.quikdown-pre code.language-geojson');
2548
+ if (!(geoBlocks.length > 0)) {
2549
+ _context.n = 55;
2550
+ break;
2551
+ }
2552
+ if (window.L) {
2553
+ _context.n = 47;
2554
+ break;
2555
+ }
2556
+ _context.p = 44;
2557
+ _context.n = 45;
2558
+ return Promise.all([loadScript(CDN.leaflet), loadCSS(CDN.leafletCSS)]);
2559
+ case 45:
2560
+ _context.n = 47;
2561
+ break;
2562
+ case 46:
2563
+ _context.p = 46;
2564
+ _context.v;
2565
+ case 47:
2566
+ if (!window.L) {
2567
+ _context.n = 55;
2568
+ break;
2569
+ }
2570
+ _iterator3 = _createForOfIteratorHelper(geoBlocks);
2571
+ _context.p = 48;
2572
+ _iterator3.s();
2573
+ case 49:
2574
+ if ((_step3 = _iterator3.n()).done) {
2575
+ _context.n = 52;
2576
+ break;
2577
+ }
2578
+ _block = _step3.value;
2579
+ _pre = _block.closest('pre');
2580
+ if (_pre) {
2581
+ _context.n = 50;
2582
+ break;
2583
+ }
2584
+ return _context.a(3, 51);
2585
+ case 50:
2586
+ try {
2587
+ geojson = JSON.parse(_block.textContent);
2588
+ _container = document.createElement('div');
2589
+ _container.className = 'qde-geojson-container';
2590
+ _container.style.cssText = 'height: 300px; width: 100%; border-radius: 4px;';
2591
+ _pre.replaceWith(_container);
2592
+ map = window.L.map(_container);
2593
+ window.L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
2594
+ attribution: '&copy; OpenStreetMap'
2595
+ }).addTo(map);
2596
+ layer = window.L.geoJSON(geojson).addTo(map);
2597
+ map.fitBounds(layer.getBounds());
2598
+ } catch (_e) {/* leave as code block */}
2599
+ case 51:
2600
+ _context.n = 49;
2601
+ break;
2602
+ case 52:
2603
+ _context.n = 54;
2604
+ break;
2605
+ case 53:
2606
+ _context.p = 53;
2607
+ _t0 = _context.v;
2608
+ _iterator3.e(_t0);
2609
+ case 54:
2610
+ _context.p = 54;
2611
+ _iterator3.f();
2612
+ return _context.f(54);
2613
+ case 55:
2614
+ // --- CSV / TSV / PSV tables ---
2615
+ tableBlocks = el.querySelectorAll('pre.quikdown-pre code.language-csv, pre.quikdown-pre code.language-tsv, pre.quikdown-pre code.language-psv');
2616
+ tableBlocks.forEach(function (block) {
2617
+ var pre = block.closest('pre');
2618
+ if (!pre) return;
2619
+ var lang = block.className.match(/language-(csv|tsv|psv)/);
2620
+ if (!lang) return;
2621
+ var delim = {
2622
+ csv: ',',
2623
+ tsv: '\t',
2624
+ psv: '|'
2625
+ }[lang[1]];
2626
+ var lines = block.textContent.trim().split('\n');
2627
+ if (lines.length < 2) return;
2628
+ try {
2629
+ var table = document.createElement('table');
2630
+ table.className = 'quikdown-table';
2631
+ lines.forEach(function (line, i) {
2632
+ var row = document.createElement('tr');
2633
+ var cells = line.split(delim).map(function (c) {
2634
+ return c.trim();
2635
+ });
2636
+ cells.forEach(function (cell) {
2637
+ var td = document.createElement(i === 0 ? 'th' : 'td');
2638
+ td.className = i === 0 ? 'quikdown-th' : 'quikdown-td';
2639
+ td.textContent = cell;
2640
+ row.appendChild(td);
2641
+ });
2642
+ table.appendChild(row);
2643
+ });
2644
+ pre.replaceWith(table);
2645
+ } catch (_e) {/* leave as code block */}
2646
+ });
2647
+
2648
+ // --- JSON pretty-print ---
2649
+ jsonBlocks = el.querySelectorAll('pre.quikdown-pre code.language-json, pre.quikdown-pre code.language-json5');
2650
+ jsonBlocks.forEach(function (block) {
2651
+ try {
2652
+ var obj = JSON.parse(block.textContent);
2653
+ block.textContent = JSON.stringify(obj, null, 2);
2654
+ // If hljs is loaded, re-highlight
2655
+ if (window.hljs && window.hljs.getLanguage('json')) {
2656
+ window.hljs.highlightElement(block);
2657
+ }
2658
+ } catch (_e) {/* not valid JSON, leave as is */}
2659
+ });
2660
+ case 56:
2661
+ return _context.a(2);
2662
+ }
2663
+ }, _callee, null, [[48, 53, 54, 55], [44, 46], [36, 38], [33, 41, 42, 43], [29, 31], [25, 27], [20, 22], [11, 13], [7, 17, 18, 19], [2, 4]]);
2664
+ }));
2665
+ return _postProcessMessage.apply(this, arguments);
2666
+ }
2667
+ var quikchatMDFull = /*#__PURE__*/function (_quikchat) {
2668
+ function quikchatMDFull(parentElement, onSend) {
2669
+ var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
2670
+ _classCallCheck(this, quikchatMDFull);
2671
+ if (!options.messageFormatter) {
2672
+ options.messageFormatter = function (content) {
2673
+ return quikdown_bd(content);
2674
+ };
2675
+ }
2676
+ return _callSuper(this, quikchatMDFull, [parentElement, onSend, options]);
2677
+ }
2678
+
2679
+ // Override message methods to add post-processing
2680
+ _inherits(quikchatMDFull, _quikchat);
2681
+ return _createClass(quikchatMDFull, [{
2682
+ key: "messageAddNew",
2683
+ value: function messageAddNew() {
2684
+ var content = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : "";
2685
+ var userString = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : "user";
2686
+ var align = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : "right";
2687
+ var role = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : "user";
2688
+ var id = _superPropGet(quikchatMDFull, "messageAddNew", this, 3)([content, userString, align, role]);
2689
+ var el = this.messageGetDOMObject(id);
2690
+ if (el) {
2691
+ postProcessMessage(el.querySelector('.quikchat-message-content'));
2692
+ }
2693
+ return id;
2694
+ }
2695
+ }, {
2696
+ key: "messageAddFull",
2697
+ value: function messageAddFull(input) {
2698
+ var id = _superPropGet(quikchatMDFull, "messageAddFull", this, 3)([input]);
2699
+ var el = this.messageGetDOMObject(id);
2700
+ if (el) {
2701
+ postProcessMessage(el.querySelector('.quikchat-message-content'));
2702
+ }
2703
+ return id;
2704
+ }
2705
+ }, {
2706
+ key: "messageAppendContent",
2707
+ value: function messageAppendContent(n, content) {
2708
+ var result = _superPropGet(quikchatMDFull, "messageAppendContent", this, 3)([n, content]);
2709
+ if (result) {
2710
+ var el = this.messageGetDOMObject(n);
2711
+ if (el) {
2712
+ postProcessMessage(el.querySelector('.quikchat-message-content'));
2713
+ }
2714
+ }
2715
+ return result;
2716
+ }
2717
+ }, {
2718
+ key: "messageReplaceContent",
2719
+ value: function messageReplaceContent(n, content) {
2720
+ var result = _superPropGet(quikchatMDFull, "messageReplaceContent", this, 3)([n, content]);
2721
+ if (result) {
2722
+ var el = this.messageGetDOMObject(n);
2723
+ if (el) {
2724
+ postProcessMessage(el.querySelector('.quikchat-message-content'));
2725
+ }
2726
+ }
2727
+ return result;
2728
+ }
2729
+ }, {
2730
+ key: "destroy",
2731
+ value: function destroy() {
2732
+ // No hidden container to clean up in this approach
2733
+ }
2734
+ }]);
2735
+ }(quikchat); // Expose quikdown bd and post-processor for direct access
2736
+ quikchatMDFull.quikdown = quikdown_bd;
2737
+ quikchatMDFull.postProcessMessage = postProcessMessage;
2738
+
2739
+ export { quikchatMDFull as default };
2740
+ //# sourceMappingURL=quikchat-md-full.esm.js.map