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