quikchat 1.1.17 → 1.2.6

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