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,1914 @@
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 _assertThisInitialized(e) {
7
+ if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
8
+ return e;
9
+ }
10
+ function _callSuper(t, o, e) {
11
+ return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e));
12
+ }
13
+ function _classCallCheck(a, n) {
14
+ if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function");
15
+ }
16
+ function _defineProperties(e, r) {
17
+ for (var t = 0; t < r.length; t++) {
18
+ var o = r[t];
19
+ o.enumerable = o.enumerable || false, o.configurable = true, "value" in o && (o.writable = true), Object.defineProperty(e, _toPropertyKey(o.key), o);
20
+ }
21
+ }
22
+ function _createClass(e, r, t) {
23
+ return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", {
24
+ writable: false
25
+ }), e;
26
+ }
27
+ function _createForOfIteratorHelper(r, e) {
28
+ var t = "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"];
29
+ if (!t) {
30
+ if (Array.isArray(r) || (t = _unsupportedIterableToArray(r)) || e) {
31
+ t && (r = t);
32
+ var n = 0,
33
+ F = function () {};
34
+ return {
35
+ s: F,
36
+ n: function () {
37
+ return n >= r.length ? {
38
+ done: true
39
+ } : {
40
+ done: false,
41
+ value: r[n++]
42
+ };
43
+ },
44
+ e: function (r) {
45
+ throw r;
46
+ },
47
+ f: F
48
+ };
49
+ }
50
+ throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
51
+ }
52
+ var o,
53
+ a = true,
54
+ u = false;
55
+ return {
56
+ s: function () {
57
+ t = t.call(r);
58
+ },
59
+ n: function () {
60
+ var r = t.next();
61
+ return a = r.done, r;
62
+ },
63
+ e: function (r) {
64
+ u = true, o = r;
65
+ },
66
+ f: function () {
67
+ try {
68
+ a || null == t.return || t.return();
69
+ } finally {
70
+ if (u) throw o;
71
+ }
72
+ }
73
+ };
74
+ }
75
+ function _defineProperty(e, r, t) {
76
+ return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, {
77
+ value: t,
78
+ enumerable: true,
79
+ configurable: true,
80
+ writable: true
81
+ }) : e[r] = t, e;
82
+ }
83
+ function _getPrototypeOf(t) {
84
+ return _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) {
85
+ return t.__proto__ || Object.getPrototypeOf(t);
86
+ }, _getPrototypeOf(t);
87
+ }
88
+ function _inherits(t, e) {
89
+ if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function");
90
+ t.prototype = Object.create(e && e.prototype, {
91
+ constructor: {
92
+ value: t,
93
+ writable: true,
94
+ configurable: true
95
+ }
96
+ }), Object.defineProperty(t, "prototype", {
97
+ writable: false
98
+ }), e && _setPrototypeOf(t, e);
99
+ }
100
+ function _isNativeReflectConstruct() {
101
+ try {
102
+ var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {}));
103
+ } catch (t) {}
104
+ return (_isNativeReflectConstruct = function () {
105
+ return !!t;
106
+ })();
107
+ }
108
+ function ownKeys(e, r) {
109
+ var t = Object.keys(e);
110
+ if (Object.getOwnPropertySymbols) {
111
+ var o = Object.getOwnPropertySymbols(e);
112
+ r && (o = o.filter(function (r) {
113
+ return Object.getOwnPropertyDescriptor(e, r).enumerable;
114
+ })), t.push.apply(t, o);
115
+ }
116
+ return t;
117
+ }
118
+ function _objectSpread2(e) {
119
+ for (var r = 1; r < arguments.length; r++) {
120
+ var t = null != arguments[r] ? arguments[r] : {};
121
+ r % 2 ? ownKeys(Object(t), true).forEach(function (r) {
122
+ _defineProperty(e, r, t[r]);
123
+ }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) {
124
+ Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r));
125
+ });
126
+ }
127
+ return e;
128
+ }
129
+ function _possibleConstructorReturn(t, e) {
130
+ if (e && ("object" == typeof e || "function" == typeof e)) return e;
131
+ if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined");
132
+ return _assertThisInitialized(t);
133
+ }
134
+ function _setPrototypeOf(t, e) {
135
+ return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) {
136
+ return t.__proto__ = e, t;
137
+ }, _setPrototypeOf(t, e);
138
+ }
139
+ function _toPrimitive(t, r) {
140
+ if ("object" != typeof t || !t) return t;
141
+ var e = t[Symbol.toPrimitive];
142
+ if (void 0 !== e) {
143
+ var i = e.call(t, r);
144
+ if ("object" != typeof i) return i;
145
+ throw new TypeError("@@toPrimitive must return a primitive value.");
146
+ }
147
+ return ("string" === r ? String : Number)(t);
148
+ }
149
+ function _toPropertyKey(t) {
150
+ var i = _toPrimitive(t, "string");
151
+ return "symbol" == typeof i ? i : i + "";
152
+ }
153
+ function _unsupportedIterableToArray(r, a) {
154
+ if (r) {
155
+ if ("string" == typeof r) return _arrayLikeToArray(r, a);
156
+ var t = {}.toString.call(r).slice(8, -1);
157
+ 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;
158
+ }
159
+ }
160
+
161
+ var quikchat = /*#__PURE__*/function () {
162
+ /**
163
+ *
164
+ * @param string or DOM element parentElement
165
+ * @param {*} meta
166
+ */
167
+ function quikchat(parentElement) {
168
+ var onSend = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : function () {};
169
+ var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
170
+ _classCallCheck(this, quikchat);
171
+ var defaultOpts = {
172
+ theme: 'quikchat-theme-light',
173
+ trackHistory: true,
174
+ showTimestamps: false,
175
+ titleArea: {
176
+ title: "Chat",
177
+ show: false,
178
+ align: "center"
179
+ },
180
+ messagesArea: {
181
+ alternating: true
182
+ }
183
+ };
184
+ var meta = _objectSpread2(_objectSpread2({}, defaultOpts), options); // merge options with defaults
185
+
186
+ if (typeof parentElement === 'string') {
187
+ parentElement = document.querySelector(parentElement);
188
+ }
189
+ this._parentElement = parentElement;
190
+ this._theme = meta.theme;
191
+ this._onSend = onSend ? onSend : function () {}; // call back function for onSend
192
+ this._messageFormatter = meta.messageFormatter || null;
193
+ this._sanitize = meta.sanitize || false;
194
+ this._createWidget();
195
+ // title area
196
+ if (meta.titleArea) {
197
+ this.titleAreaSetContents(meta.titleArea.title, meta.titleArea.align);
198
+ if (meta.titleArea.show === true) {
199
+ this.titleAreaShow();
200
+ } else {
201
+ this.titleAreaHide();
202
+ }
203
+ }
204
+ // messages area
205
+ if (meta.messagesArea) {
206
+ this.messagesAreaAlternateColors(meta.messagesArea.alternating);
207
+ }
208
+ // timestamps
209
+ if (meta.showTimestamps) {
210
+ this.messagesAreaShowTimestamps(true);
211
+ }
212
+ // direction (ltr/rtl)
213
+ if (meta.direction) {
214
+ this.setDirection(meta.direction);
215
+ }
216
+ // plumbing
217
+ this._attachEventListeners();
218
+ this.trackHistory = meta.trackHistory !== false;
219
+ this._historyLimit = 10000000;
220
+ this._history = [];
221
+ }
222
+ return _createClass(quikchat, [{
223
+ key: "_createWidget",
224
+ value: function _createWidget() {
225
+ 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 ");
226
+ this._parentElement.innerHTML = widgetHTML;
227
+ this._chatWidget = this._parentElement.querySelector('.quikchat-base');
228
+ this._titleArea = this._chatWidget.querySelector('.quikchat-title-area');
229
+ this._messagesWrapper = this._chatWidget.querySelector('.quikchat-messages-wrapper');
230
+ this._messagesArea = this._chatWidget.querySelector('.quikchat-messages-area');
231
+ this._scrollBottomBtn = this._messagesWrapper.querySelector('.quikchat-scroll-bottom');
232
+ this._inputArea = this._chatWidget.querySelector('.quikchat-input-area');
233
+ this._textEntry = this._inputArea.querySelector('.quikchat-input-textbox');
234
+ this._sendButton = this._inputArea.querySelector('.quikchat-input-send-btn');
235
+ this.msgid = 0;
236
+ }
237
+
238
+ /**
239
+ * Attach event listeners to the widget
240
+ */
241
+ }, {
242
+ key: "_attachEventListeners",
243
+ value: function _attachEventListeners() {
244
+ var _this = this;
245
+ this._sendButton.addEventListener('click', function () {
246
+ var text = _this._textEntry.value.trim();
247
+ if (text === '') return;
248
+ _this._onSend(_this, text);
249
+ });
250
+ this._textEntry.addEventListener('keydown', function (event) {
251
+ // Check if Shift + Enter is pressed
252
+ if (event.shiftKey && event.keyCode === 13) {
253
+ event.preventDefault();
254
+ var text = _this._textEntry.value.trim();
255
+ if (text === '') return;
256
+ _this._onSend(_this, text);
257
+ }
258
+ });
259
+
260
+ // Auto-grow textarea
261
+ this._textEntry.addEventListener('input', function () {
262
+ return _this._autoGrowTextarea();
263
+ });
264
+ this._messagesArea.addEventListener('scroll', function () {
265
+ var _this$_messagesArea = _this._messagesArea,
266
+ scrollTop = _this$_messagesArea.scrollTop,
267
+ scrollHeight = _this$_messagesArea.scrollHeight,
268
+ clientHeight = _this$_messagesArea.clientHeight;
269
+ _this.userScrolledUp = scrollTop + clientHeight < scrollHeight - 1;
270
+ _this._updateScrollBottomBtn();
271
+ });
272
+
273
+ // Scroll-to-bottom button
274
+ this._scrollBottomBtn.addEventListener('click', function () {
275
+ return _this.scrollToBottom();
276
+ });
277
+
278
+ // Ctrl+End to scroll to bottom
279
+ this._chatWidget.addEventListener('keydown', function (event) {
280
+ if (event.ctrlKey && event.key === 'End') {
281
+ event.preventDefault();
282
+ _this.scrollToBottom();
283
+ }
284
+ });
285
+
286
+ // Use ResizeObserver to detect parent container resize
287
+ if (typeof ResizeObserver !== 'undefined') {
288
+ this._resizeObserver = new ResizeObserver(function () {
289
+ return _this._handleContainerResize();
290
+ });
291
+ this._resizeObserver.observe(this._parentElement);
292
+ }
293
+ }
294
+
295
+ // set the onSend function callback.
296
+ }, {
297
+ key: "setCallbackOnSend",
298
+ value: function setCallbackOnSend(callback) {
299
+ this._onSend = callback;
300
+ }
301
+ // set a callback for everytime a message is added (listener)
302
+ }, {
303
+ key: "setCallbackonMessageAdded",
304
+ value: function setCallbackonMessageAdded(callback) {
305
+ this._onMessageAdded = callback;
306
+ }
307
+ }, {
308
+ key: "setCallbackonMessageAppend",
309
+ value: function setCallbackonMessageAppend(callback) {
310
+ this._onMessageAppend = callback;
311
+ }
312
+ }, {
313
+ key: "setCallbackonMessageReplace",
314
+ value: function setCallbackonMessageReplace(callback) {
315
+ this._onMessageReplace = callback;
316
+ }
317
+ }, {
318
+ key: "setCallbackonMessageDelete",
319
+ value: function setCallbackonMessageDelete(callback) {
320
+ this._onMessageDelete = callback;
321
+ }
322
+
323
+ // Public methods
324
+ }, {
325
+ key: "titleAreaToggle",
326
+ value: function titleAreaToggle() {
327
+ if (this._titleArea.style.display === 'none') {
328
+ this.titleAreaShow();
329
+ } else {
330
+ this.titleAreaHide();
331
+ }
332
+ }
333
+ }, {
334
+ key: "titleAreaShow",
335
+ value: function titleAreaShow() {
336
+ this._titleArea.style.display = '';
337
+ }
338
+ }, {
339
+ key: "titleAreaHide",
340
+ value: function titleAreaHide() {
341
+ this._titleArea.style.display = 'none';
342
+ }
343
+ }, {
344
+ key: "titleAreaSetContents",
345
+ value: function titleAreaSetContents(title) {
346
+ var align = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'center';
347
+ this._titleArea.innerHTML = title;
348
+ this._titleArea.style.textAlign = align;
349
+ }
350
+ }, {
351
+ key: "titleAreaGetContents",
352
+ value: function titleAreaGetContents() {
353
+ return this._titleArea.innerHTML;
354
+ }
355
+ }, {
356
+ key: "inputAreaToggle",
357
+ value: function inputAreaToggle() {
358
+ if (this._inputArea.style.display === 'none') {
359
+ this.inputAreaShow();
360
+ } else {
361
+ this.inputAreaHide();
362
+ }
363
+ }
364
+ }, {
365
+ key: "inputAreaShow",
366
+ value: function inputAreaShow() {
367
+ this._inputArea.style.display = '';
368
+ }
369
+ }, {
370
+ key: "inputAreaHide",
371
+ value: function inputAreaHide() {
372
+ this._inputArea.style.display = 'none';
373
+ }
374
+ }, {
375
+ key: "inputAreaSetEnabled",
376
+ value: function inputAreaSetEnabled(enabled) {
377
+ this._textEntry.disabled = !enabled;
378
+ this._sendButton.disabled = !enabled;
379
+ }
380
+ }, {
381
+ key: "inputAreaSetButtonText",
382
+ value: function inputAreaSetButtonText(text) {
383
+ this._sendButton.textContent = text;
384
+ }
385
+ }, {
386
+ key: "inputAreaGetButtonText",
387
+ value: function inputAreaGetButtonText() {
388
+ return this._sendButton.textContent;
389
+ }
390
+ }, {
391
+ key: "setDirection",
392
+ value: function setDirection(dir) {
393
+ var d = dir === 'rtl' ? 'rtl' : 'ltr';
394
+ this._chatWidget.setAttribute('dir', d);
395
+ if (d === 'rtl') {
396
+ this._chatWidget.classList.add('quikchat-rtl');
397
+ } else {
398
+ this._chatWidget.classList.remove('quikchat-rtl');
399
+ }
400
+ }
401
+ }, {
402
+ key: "getDirection",
403
+ value: function getDirection() {
404
+ return this._chatWidget.getAttribute('dir') || 'ltr';
405
+ }
406
+ }, {
407
+ key: "_handleContainerResize",
408
+ value: function _handleContainerResize() {
409
+ // Layout is handled by CSS flexbox — no JS height calculation needed.
410
+ // This hook exists for future use or custom resize callbacks.
411
+ }
412
+ }, {
413
+ key: "scrollToBottom",
414
+ value: function scrollToBottom() {
415
+ this._messagesArea.scrollTop = this._messagesArea.scrollHeight;
416
+ this.userScrolledUp = false;
417
+ this._updateScrollBottomBtn();
418
+ }
419
+ }, {
420
+ key: "_updateScrollBottomBtn",
421
+ value: function _updateScrollBottomBtn() {
422
+ if (this.userScrolledUp) {
423
+ this._scrollBottomBtn.classList.add('quikchat-scroll-bottom-visible');
424
+ } else {
425
+ this._scrollBottomBtn.classList.remove('quikchat-scroll-bottom-visible');
426
+ }
427
+ }
428
+ }, {
429
+ key: "_autoGrowTextarea",
430
+ value: function _autoGrowTextarea() {
431
+ var el = this._textEntry;
432
+ el.style.height = 'auto';
433
+ var maxHeight = 120;
434
+ el.style.height = Math.min(el.scrollHeight, maxHeight) + 'px';
435
+ el.style.overflowY = el.scrollHeight > maxHeight ? 'auto' : 'hidden';
436
+ }
437
+ }, {
438
+ key: "_formatTimestamp",
439
+ value: function _formatTimestamp(isoString) {
440
+ var d = new Date(isoString);
441
+ var h = d.getHours();
442
+ var m = String(d.getMinutes()).padStart(2, '0');
443
+ var ampm = h >= 12 ? 'PM' : 'AM';
444
+ var h12 = h % 12 || 12;
445
+ return h12 + ':' + m + ' ' + ampm;
446
+ }
447
+ }, {
448
+ key: "messagesAreaShowTimestamps",
449
+ value: function messagesAreaShowTimestamps(show) {
450
+ if (show) {
451
+ this._messagesArea.classList.add('quikchat-show-timestamps');
452
+ } else {
453
+ this._messagesArea.classList.remove('quikchat-show-timestamps');
454
+ }
455
+ }
456
+ }, {
457
+ key: "messagesAreaShowTimestampsGet",
458
+ value: function messagesAreaShowTimestampsGet() {
459
+ return this._messagesArea.classList.contains('quikchat-show-timestamps');
460
+ }
461
+ }, {
462
+ key: "messagesAreaShowTimestampsToggle",
463
+ value: function messagesAreaShowTimestampsToggle() {
464
+ this._messagesArea.classList.toggle('quikchat-show-timestamps');
465
+ }
466
+ }, {
467
+ key: "_escapeHTML",
468
+ value: function _escapeHTML(str) {
469
+ var div = document.createElement('div');
470
+ div.textContent = str;
471
+ return div.innerHTML;
472
+ }
473
+ }, {
474
+ key: "_processContent",
475
+ value: function _processContent(content) {
476
+ if (this._sanitize === true) {
477
+ content = this._escapeHTML(content);
478
+ } else if (typeof this._sanitize === 'function') {
479
+ content = this._sanitize(content);
480
+ }
481
+ if (this._messageFormatter) {
482
+ content = this._messageFormatter(content);
483
+ }
484
+ return content;
485
+ }
486
+
487
+ //messagesArea functions
488
+ }, {
489
+ key: "messagesAreaAlternateColors",
490
+ value: function messagesAreaAlternateColors() {
491
+ var alt = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : true;
492
+ if (alt) {
493
+ this._messagesArea.classList.add('quikchat-messages-area-alt');
494
+ } else {
495
+ this._messagesArea.classList.remove('quikchat-messages-area-alt');
496
+ }
497
+ return alt === true;
498
+ }
499
+ }, {
500
+ key: "messagesAreaAlternateColorsToggle",
501
+ value: function messagesAreaAlternateColorsToggle() {
502
+ this._messagesArea.classList.toggle('quikchat-messages-area-alt');
503
+ }
504
+ }, {
505
+ key: "messagesAreaAlternateColorsGet",
506
+ value: function messagesAreaAlternateColorsGet() {
507
+ return this._messagesArea.classList.contains('quikchat-messages-area-alt');
508
+ }
509
+ // message functions
510
+ }, {
511
+ key: "messageAddFull",
512
+ value: function messageAddFull() {
513
+ var input = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {
514
+ content: "",
515
+ userString: "user",
516
+ align: "right",
517
+ role: "user",
518
+ userID: -1
519
+ };
520
+ var msgid = this.msgid;
521
+ var messageDiv = document.createElement('div');
522
+ var msgidClass = 'quikchat-msgid-' + String(msgid).padStart(10, '0');
523
+ messageDiv.classList.add('quikchat-message', msgidClass);
524
+ messageDiv.classList.add('quikchat-role-' + (input.role || 'user'));
525
+ messageDiv.classList.add('quikchat-align-' + (input.align || 'right'));
526
+ this.msgid++;
527
+ messageDiv.classList.add(this._messagesArea.children.length % 2 === 1 ? 'quikchat-message-1' : 'quikchat-message-2');
528
+
529
+ // Visibility: default true, hidden messages get display:none
530
+ var visible = input.visible !== false;
531
+ if (!visible) {
532
+ messageDiv.style.display = 'none';
533
+ }
534
+
535
+ // Tags: array of strings for group-based visibility control
536
+ var tags = Array.isArray(input.tags) ? input.tags.slice() : [];
537
+ var userDiv = document.createElement('div');
538
+ userDiv.classList.add('quikchat-user-label');
539
+ userDiv.style.textAlign = input.align;
540
+ userDiv.innerHTML = input.userString;
541
+ var contentDiv = document.createElement('div');
542
+ contentDiv.classList.add('quikchat-message-content');
543
+ contentDiv.style.textAlign = input.align;
544
+ contentDiv.innerHTML = this._processContent(input.content);
545
+ var timestamp = new Date().toISOString();
546
+ var timestampSpan = document.createElement('span');
547
+ timestampSpan.classList.add('quikchat-timestamp');
548
+ timestampSpan.textContent = this._formatTimestamp(timestamp);
549
+ messageDiv.appendChild(userDiv);
550
+ messageDiv.appendChild(contentDiv);
551
+ messageDiv.appendChild(timestampSpan);
552
+ this._messagesArea.appendChild(messageDiv);
553
+
554
+ // Scroll to the last message only if the user is not actively scrolling up
555
+ if (!this.userScrolledUp) {
556
+ this._messagesArea.scrollTop = this._messagesArea.scrollHeight;
557
+ }
558
+ this._textEntry.value = '';
559
+ this._autoGrowTextarea();
560
+ var updatedtime = timestamp;
561
+ if (this.trackHistory) {
562
+ this._history.push(_objectSpread2(_objectSpread2({
563
+ msgid: msgid
564
+ }, input), {}, {
565
+ visible: visible,
566
+ tags: tags,
567
+ timestamp: timestamp,
568
+ updatedtime: updatedtime,
569
+ messageDiv: messageDiv
570
+ }));
571
+ if (this._history.length > this._historyLimit) {
572
+ this._history.shift();
573
+ }
574
+ }
575
+ if (this._onMessageAdded) {
576
+ this._onMessageAdded(this, msgid);
577
+ }
578
+ return msgid;
579
+ }
580
+ }, {
581
+ key: "messageAddNew",
582
+ value: function messageAddNew() {
583
+ var content = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : "";
584
+ var userString = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : "user";
585
+ var align = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : "right";
586
+ var role = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : "user";
587
+ return this.messageAddFull({
588
+ content: content,
589
+ userString: userString,
590
+ align: align,
591
+ role: role
592
+ });
593
+ }
594
+ }, {
595
+ key: "messageRemove",
596
+ value: function messageRemove(n) {
597
+ var success = false;
598
+ try {
599
+ this._messagesArea.removeChild(this._messagesArea.querySelector(".quikchat-msgid-".concat(String(n).padStart(10, '0'))));
600
+ success = true;
601
+ } catch (_error) {
602
+ // Message ID not found
603
+ }
604
+ if (success) {
605
+ this._history.splice(this._history.findIndex(function (item) {
606
+ return item.msgid === n;
607
+ }), 1);
608
+ if (this._onMessageDelete) {
609
+ this._onMessageDelete(this, n);
610
+ }
611
+ }
612
+ return success;
613
+ }
614
+ /* returns the message html object from the DOM
615
+ */
616
+ }, {
617
+ key: "messageGetDOMObject",
618
+ value: function messageGetDOMObject(n) {
619
+ var msg = null;
620
+ try {
621
+ msg = this._messagesArea.querySelector(".quikchat-msgid-".concat(String(n).padStart(10, '0')));
622
+ } catch (_error) {
623
+ // Message ID not found
624
+ }
625
+ return msg;
626
+ }
627
+ /* returns the message content only
628
+ */
629
+ }, {
630
+ key: "messageGetContent",
631
+ value: function messageGetContent(n) {
632
+ var content = "";
633
+ try {
634
+ content = this._history.filter(function (item) {
635
+ return item.msgid === n;
636
+ })[0].content;
637
+ } catch (_error) {
638
+ // Message ID not found
639
+ }
640
+ return content;
641
+ }
642
+ }, {
643
+ key: "messageSetVisible",
644
+ value: function messageSetVisible(n, visible) {
645
+ var msgEl = this.messageGetDOMObject(n);
646
+ if (!msgEl) return false;
647
+ msgEl.style.display = visible ? '' : 'none';
648
+ var item = this._history.find(function (entry) {
649
+ return entry.msgid === n;
650
+ });
651
+ if (item) item.visible = visible;
652
+ return true;
653
+ }
654
+ }, {
655
+ key: "messageGetVisible",
656
+ value: function messageGetVisible(n) {
657
+ var item = this._history.find(function (entry) {
658
+ return entry.msgid === n;
659
+ });
660
+ return item ? item.visible !== false : false;
661
+ }
662
+ }, {
663
+ key: "messageToggleVisible",
664
+ value: function messageToggleVisible(n) {
665
+ var current = this.messageGetVisible(n);
666
+ return this.messageSetVisible(n, !current);
667
+ }
668
+ }, {
669
+ key: "messageSetVisibleByTag",
670
+ value: function messageSetVisibleByTag(tag, visible) {
671
+ var count = 0;
672
+ var _iterator = _createForOfIteratorHelper(this._history),
673
+ _step;
674
+ try {
675
+ for (_iterator.s(); !(_step = _iterator.n()).done;) {
676
+ var item = _step.value;
677
+ if (item.tags && item.tags.includes(tag)) {
678
+ this.messageSetVisible(item.msgid, visible);
679
+ count++;
680
+ }
681
+ }
682
+ } catch (err) {
683
+ _iterator.e(err);
684
+ } finally {
685
+ _iterator.f();
686
+ }
687
+ return count;
688
+ }
689
+ }, {
690
+ key: "messageGetTags",
691
+ value: function messageGetTags(n) {
692
+ var item = this._history.find(function (entry) {
693
+ return entry.msgid === n;
694
+ });
695
+ return item && item.tags ? item.tags.slice() : [];
696
+ }
697
+ }, {
698
+ key: "messageSetTags",
699
+ value: function messageSetTags(n, tags) {
700
+ var item = this._history.find(function (entry) {
701
+ return entry.msgid === n;
702
+ });
703
+ if (!item) return false;
704
+ item.tags = Array.isArray(tags) ? tags.slice() : [];
705
+ return true;
706
+ }
707
+
708
+ /* append message to the message content
709
+ */
710
+ }, {
711
+ key: "messageAppendContent",
712
+ value: function messageAppendContent(n, content) {
713
+ var success = false;
714
+ try {
715
+ var msgEl = this._messagesArea.querySelector(".quikchat-msgid-".concat(String(n).padStart(10, '0')));
716
+ var item = this._history.filter(function (entry) {
717
+ return entry.msgid === n;
718
+ })[0];
719
+ item.content += content;
720
+ item.updatedtime = new Date().toISOString();
721
+ msgEl.querySelector('.quikchat-message-content').innerHTML = this._processContent(item.content);
722
+ msgEl.classList.remove('quikchat-typing');
723
+ success = true;
724
+ if (!this.userScrolledUp) {
725
+ this._messagesArea.scrollTop = this._messagesArea.scrollHeight;
726
+ }
727
+ if (this._onMessageAppend) {
728
+ this._onMessageAppend(this, n, content);
729
+ }
730
+ } catch (_error) {
731
+ // Message ID not found
732
+ }
733
+ return success;
734
+ }
735
+
736
+ /* replace message content
737
+ */
738
+ }, {
739
+ key: "messageReplaceContent",
740
+ value: function messageReplaceContent(n, content) {
741
+ var success = false;
742
+ try {
743
+ var msgEl = this._messagesArea.querySelector(".quikchat-msgid-".concat(String(n).padStart(10, '0')));
744
+ var item = this._history.filter(function (entry) {
745
+ return entry.msgid === n;
746
+ })[0];
747
+ item.content = content;
748
+ item.updatedtime = new Date().toISOString();
749
+ msgEl.querySelector('.quikchat-message-content').innerHTML = this._processContent(content);
750
+ msgEl.classList.remove('quikchat-typing');
751
+ success = true;
752
+ if (!this.userScrolledUp) {
753
+ this._messagesArea.scrollTop = this._messagesArea.scrollHeight;
754
+ }
755
+ if (this._onMessageReplace) {
756
+ this._onMessageReplace(this, n, content);
757
+ }
758
+ } catch (_error) {
759
+ // Message ID not found
760
+ }
761
+ return success;
762
+ }
763
+ }, {
764
+ key: "messageAddTypingIndicator",
765
+ value: function messageAddTypingIndicator() {
766
+ var userString = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : '';
767
+ var align = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'left';
768
+ var msgid = this.messageAddFull({
769
+ content: '',
770
+ userString: userString,
771
+ align: align,
772
+ role: 'assistant'
773
+ });
774
+ var msgEl = this.messageGetDOMObject(msgid);
775
+ msgEl.classList.add('quikchat-typing');
776
+ var contentDiv = msgEl.querySelector('.quikchat-message-content');
777
+ contentDiv.innerHTML = '<span class="quikchat-typing-dots"><span>.</span><span>.</span><span>.</span></span>';
778
+ return msgid;
779
+ }
780
+ }, {
781
+ key: "setMessageFormatter",
782
+ value: function setMessageFormatter(formatter) {
783
+ this._messageFormatter = formatter;
784
+ }
785
+ }, {
786
+ key: "setSanitize",
787
+ value: function setSanitize(sanitize) {
788
+ this._sanitize = sanitize;
789
+ }
790
+
791
+ // history functions
792
+ /**
793
+ *
794
+ * @param {*} n
795
+ * @param {*} m
796
+ * @returns array of history messages
797
+ */
798
+ }, {
799
+ key: "historyGet",
800
+ value: function historyGet(n, m) {
801
+ if (n === undefined) {
802
+ return this._history.slice();
803
+ }
804
+ if (m === undefined) {
805
+ if (n < 0) {
806
+ return this._history.slice(n);
807
+ }
808
+ return this._history.slice(n, n + 1);
809
+ }
810
+ return this._history.slice(n, m);
811
+ }
812
+ }, {
813
+ key: "historyClear",
814
+ value: function historyClear() {
815
+ this.msgid = 0;
816
+ this._history = [];
817
+ }
818
+ }, {
819
+ key: "historyGetLength",
820
+ value: function historyGetLength() {
821
+ return this._history.length;
822
+ }
823
+ }, {
824
+ key: "historyGetMessage",
825
+ value: function historyGetMessage(n) {
826
+ if (n >= 0 && n < this._history.length) {
827
+ return this._history[n];
828
+ }
829
+ return {};
830
+ }
831
+ }, {
832
+ key: "historyGetMessageContent",
833
+ value: function historyGetMessageContent(n) {
834
+ if (n >= 0 && n < this._history.length) {
835
+ return this._history[n].content;
836
+ }
837
+ return "";
838
+ }
839
+ }, {
840
+ key: "historyExport",
841
+ value: function historyExport() {
842
+ return this._history.map(function (item) {
843
+ return {
844
+ msgid: item.msgid,
845
+ content: item.content,
846
+ userString: item.userString,
847
+ align: item.align,
848
+ role: item.role,
849
+ userID: item.userID,
850
+ visible: item.visible,
851
+ tags: item.tags ? item.tags.slice() : [],
852
+ timestamp: item.timestamp,
853
+ updatedtime: item.updatedtime
854
+ };
855
+ });
856
+ }
857
+ }, {
858
+ key: "historyImport",
859
+ value: function historyImport(data) {
860
+ // Clear existing messages from DOM and history
861
+ this._messagesArea.innerHTML = '';
862
+ this._history = [];
863
+ this.msgid = 0;
864
+ var _iterator2 = _createForOfIteratorHelper(data),
865
+ _step2;
866
+ try {
867
+ for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {
868
+ var entry = _step2.value;
869
+ this.messageAddFull({
870
+ content: entry.content || '',
871
+ userString: entry.userString || 'user',
872
+ align: entry.align || 'right',
873
+ role: entry.role || 'user',
874
+ userID: entry.userID,
875
+ visible: entry.visible,
876
+ tags: entry.tags
877
+ });
878
+ }
879
+ } catch (err) {
880
+ _iterator2.e(err);
881
+ } finally {
882
+ _iterator2.f();
883
+ }
884
+ }
885
+ }, {
886
+ key: "changeTheme",
887
+ value: function changeTheme(newTheme) {
888
+ this._chatWidget.classList.remove(this._theme);
889
+ this._chatWidget.classList.add(newTheme);
890
+ this._theme = newTheme;
891
+ }
892
+ }, {
893
+ key: "theme",
894
+ get: function get() {
895
+ return this._theme;
896
+ }
897
+ }], [{
898
+ key: "version",
899
+ value: function version() {
900
+ return {
901
+ "version": "1.2.6",
902
+ "license": "BSD-2",
903
+ "url": "https://github/deftio/quikchat"
904
+ };
905
+ }
906
+
907
+ /**
908
+ * quikchat.loremIpsum() - Generate a simple string of Lorem Ipsum text (sample typographer's text) of numChars in length.
909
+ * borrowed from github.com/deftio/bitwrench.js
910
+ * @param {number} numChars - The number of characters to generate (random btw 25 and 150 if undefined).
911
+ * @param {number} [startSpot=0] - The starting index in the Lorem Ipsum text. If undefined, a random startSpot will be generated.
912
+ * @param {boolean} [startWithCapitalLetter=true] - If true, capitalize the first character or inject a capital letter if the first character isn't a capital letter.
913
+ *
914
+ * @returns {string} A string of Lorem Ipsum text.
915
+ *
916
+ * @example
917
+ * // Returns 200 characters of Lorem Ipsum starting from index 50
918
+ * loremIpsum(200, 50);
919
+ *
920
+ * @example
921
+ * //Returns a 200 Lorem Ipsum characters starting from a random index
922
+ * loremIpsum(200);
923
+ */
924
+ }, {
925
+ key: "loremIpsum",
926
+ value: function loremIpsum(numChars) {
927
+ var startSpot = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : undefined;
928
+ var startWithCapitalLetter = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : true;
929
+ 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. ";
930
+ if (typeof numChars !== "number") {
931
+ numChars = Math.floor(Math.random() * 126) + 25;
932
+ }
933
+ if (startSpot === undefined) {
934
+ startSpot = Math.floor(Math.random() * loremText.length);
935
+ }
936
+ startSpot = startSpot % loremText.length;
937
+
938
+ // Move startSpot to the next non-whitespace and non-punctuation character
939
+ while (loremText[startSpot] === ' ' || /[.,:;!?]/.test(loremText[startSpot])) {
940
+ startSpot = (startSpot + 1) % loremText.length;
941
+ }
942
+ var l = loremText.substring(startSpot) + loremText.substring(0, startSpot);
943
+ var s = "";
944
+ while (numChars > 0) {
945
+ s += numChars < l.length ? l.substring(0, numChars) : l;
946
+ numChars -= l.length;
947
+ }
948
+ if (s[s.length - 1] === " ") {
949
+ s = s.substring(0, s.length - 1) + "."; // always end on non-whitespace. "." was chosen arbitrarily.
950
+ }
951
+ if (startWithCapitalLetter) {
952
+ s = s[0].toUpperCase() + s.substring(1);
953
+ }
954
+ return s;
955
+ }
956
+ }]);
957
+ }();
958
+
959
+ /**
960
+ * quikdown - Lightweight Markdown Parser
961
+ * @version 1.2.10
962
+ * @license BSD-2-Clause
963
+ * @copyright DeftIO 2025
964
+ */
965
+ /**
966
+ * quikdown_classify — Shared line-classification utilities
967
+ * ═════════════════════════════════════════════════════════
968
+ *
969
+ * Pure functions for classifying markdown lines. Used by both the main
970
+ * parser (quikdown.js) and the editor (quikdown_edit.js) so the logic
971
+ * lives in one place.
972
+ *
973
+ * All functions operate on a **trimmed** line (caller must trim).
974
+ * None use regexes with nested quantifiers — every check is either a
975
+ * simple regex or a linear scan, so there is zero ReDoS risk.
976
+ */
977
+
978
+
979
+ /**
980
+ * Dash-only HR check — exact parity with the main parser's original
981
+ * regex `/^---+\s*$/`. Only matches lines of three or more dashes
982
+ * with optional trailing whitespace (no interspersed spaces).
983
+ *
984
+ * @param {string} trimmed The line, already trimmed
985
+ * @returns {boolean}
986
+ */
987
+ function isDashHRLine(trimmed) {
988
+ if (trimmed.length < 3) return false;
989
+ for (let i = 0; i < trimmed.length; i++) {
990
+ const ch = trimmed[i];
991
+ if (ch === '-') continue;
992
+ // Allow trailing whitespace only
993
+ if (ch === ' ' || ch === '\t') {
994
+ for (let j = i + 1; j < trimmed.length; j++) {
995
+ if (trimmed[j] !== ' ' && trimmed[j] !== '\t') return false;
996
+ }
997
+ return i >= 3; // at least 3 dashes before whitespace
998
+ }
999
+ return false;
1000
+ }
1001
+ return true; // all dashes
1002
+ }
1003
+
1004
+ /**
1005
+ * quikdown — A compact, scanner-based markdown parser
1006
+ * ════════════════════════════════════════════════════
1007
+ *
1008
+ * Architecture overview (v1.2.8 — lexer rewrite)
1009
+ * ───────────────────────────────────────────────
1010
+ * Prior to v1.2.8, quikdown used a multi-pass regex pipeline: each block
1011
+ * type (headings, blockquotes, HR, lists, tables) and each inline format
1012
+ * (bold, italic, links, …) was handled by its own global regex applied
1013
+ * sequentially to the full document string. That worked but made the code
1014
+ * hard to extend and debug — a new construct meant adding another regex
1015
+ * pass, and ordering bugs between passes were subtle.
1016
+ *
1017
+ * Starting in v1.2.8 the parser uses a **line-scanning** approach for
1018
+ * block detection and a **per-block inline pass** for formatting:
1019
+ *
1020
+ * ┌─────────────────────────────────────────────────────────┐
1021
+ * │ Phase 1 — Code Extraction │
1022
+ * │ Scan for fenced code blocks (``` / ~~~) and inline │
1023
+ * │ code spans (`…`). Replace with §CB§ / §IC§ place- │
1024
+ * │ holders so code content is never touched by later │
1025
+ * │ phases. │
1026
+ * ├─────────────────────────────────────────────────────────┤
1027
+ * │ Phase 2 — HTML Escaping │
1028
+ * │ Escape &, <, >, ", ' in the remaining text to prevent │
1029
+ * │ XSS. (Skipped when allow_unsafe_html is true.) │
1030
+ * ├─────────────────────────────────────────────────────────┤
1031
+ * │ Phase 3 — Block Scanning │
1032
+ * │ Walk the text **line by line**. At each line, the │
1033
+ * │ scanner checks (in order): │
1034
+ * │ • table rows (|) │
1035
+ * │ • headings (#) │
1036
+ * │ • HR (---) │
1037
+ * │ • blockquotes (&gt;) │
1038
+ * │ • list items (-, *, +, 1.) │
1039
+ * │ • code-block placeholder (§CB…§) │
1040
+ * │ • paragraph text (everything else) │
1041
+ * │ │
1042
+ * │ Block text is run through the **inline formatter** │
1043
+ * │ which handles bold, italic, strikethrough, links, │
1044
+ * │ images, and autolinks. │
1045
+ * │ │
1046
+ * │ Paragraphs are wrapped in <p> tags. Lazy linefeeds │
1047
+ * │ (single \n → <br>) are handled here too. │
1048
+ * ├─────────────────────────────────────────────────────────┤
1049
+ * │ Phase 4 — Code Restoration │
1050
+ * │ Replace §CB§ / §IC§ placeholders with rendered <pre> │
1051
+ * │ / <code> HTML, applying the fence_plugin if present. │
1052
+ * └─────────────────────────────────────────────────────────┘
1053
+ *
1054
+ * Why this design?
1055
+ * • Single pass over lines for block identification — no re-scanning.
1056
+ * • Each block type is a clearly separated branch, easy to add new ones.
1057
+ * • Inline formatting is confined to block text — can't accidentally
1058
+ * match across block boundaries or inside HTML tags.
1059
+ * • Code extraction still uses a simple regex (it's one pattern, not a
1060
+ * chain) because the §-placeholder approach is proven and simple.
1061
+ *
1062
+ * @param {string} markdown The markdown source text
1063
+ * @param {Object} options Configuration (see below)
1064
+ * @returns {string} Rendered HTML
1065
+ */
1066
+
1067
+
1068
+ // ────────────────────────────────────────────────────────────────────
1069
+ // Constants
1070
+ // ────────────────────────────────────────────────────────────────────
1071
+
1072
+ /** Build-time version stamp (injected by tools/updateVersion) */
1073
+ const quikdownVersion = '1.2.10';
1074
+
1075
+ /** CSS class prefix used for all generated elements */
1076
+ const CLASS_PREFIX = 'quikdown-';
1077
+
1078
+ /** Placeholder sigils — chosen to be extremely unlikely in real text */
1079
+ const PLACEHOLDER_CB = '§CB'; // fenced code blocks
1080
+ const PLACEHOLDER_IC = '§IC'; // inline code spans
1081
+
1082
+ /** HTML entity escape map */
1083
+ const ESC_MAP = {'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'};
1084
+
1085
+ // ────────────────────────────────────────────────────────────────────
1086
+ // Style definitions
1087
+ // ────────────────────────────────────────────────────────────────────
1088
+
1089
+ /**
1090
+ * Inline styles for every element quikdown can emit.
1091
+ * When `inline_styles: true` these are injected as style="…" attributes.
1092
+ * When `inline_styles: false` (default) we use class="quikdown-<tag>"
1093
+ * and these same values are emitted by `quikdown.emitStyles()`.
1094
+ */
1095
+ const QUIKDOWN_STYLES = {
1096
+ h1: 'font-size:2em;font-weight:600;margin:.67em 0;text-align:left',
1097
+ h2: 'font-size:1.5em;font-weight:600;margin:.83em 0',
1098
+ h3: 'font-size:1.25em;font-weight:600;margin:1em 0',
1099
+ h4: 'font-size:1em;font-weight:600;margin:1.33em 0',
1100
+ h5: 'font-size:.875em;font-weight:600;margin:1.67em 0',
1101
+ h6: 'font-size:.85em;font-weight:600;margin:2em 0',
1102
+ pre: 'background:#f4f4f4;padding:10px;border-radius:4px;overflow-x:auto;margin:1em 0',
1103
+ code: 'background:#f0f0f0;padding:2px 4px;border-radius:3px;font-family:monospace',
1104
+ blockquote: 'border-left:4px solid #ddd;margin-left:0;padding-left:1em',
1105
+ table: 'border-collapse:collapse;width:100%;margin:1em 0',
1106
+ th: 'border:1px solid #ddd;padding:8px;background-color:#f2f2f2;font-weight:bold;text-align:left',
1107
+ td: 'border:1px solid #ddd;padding:8px;text-align:left',
1108
+ hr: 'border:none;border-top:1px solid #ddd;margin:1em 0',
1109
+ img: 'max-width:100%;height:auto',
1110
+ a: 'color:#06c;text-decoration:underline',
1111
+ strong: 'font-weight:bold',
1112
+ em: 'font-style:italic',
1113
+ del: 'text-decoration:line-through',
1114
+ ul: 'margin:.5em 0;padding-left:2em',
1115
+ ol: 'margin:.5em 0;padding-left:2em',
1116
+ li: 'margin:.25em 0',
1117
+ 'task-item': 'list-style:none',
1118
+ 'task-checkbox': 'margin-right:.5em'
1119
+ };
1120
+
1121
+ // ────────────────────────────────────────────────────────────────────
1122
+ // Attribute factory
1123
+ // ────────────────────────────────────────────────────────────────────
1124
+
1125
+ /**
1126
+ * Creates a `getAttr(tag, additionalStyle?)` helper that returns
1127
+ * either a class="…" or style="…" attribute string depending on mode.
1128
+ *
1129
+ * @param {boolean} inline_styles True → emit style="…"; false → class="…"
1130
+ * @param {Object} styles The QUIKDOWN_STYLES map
1131
+ * @returns {Function}
1132
+ */
1133
+ function createGetAttr(inline_styles, styles) {
1134
+ return function(tag, additionalStyle = '') {
1135
+ if (inline_styles) {
1136
+ let style = styles[tag];
1137
+ if (!style && !additionalStyle) return '';
1138
+
1139
+ // When adding alignment that conflicts with the tag's default,
1140
+ // strip the default text-align first.
1141
+ if (additionalStyle && additionalStyle.includes('text-align') && style && style.includes('text-align')) {
1142
+ style = style.replace(/text-align:[^;]+;?/, '').trim();
1143
+ /* istanbul ignore next */
1144
+ if (style && !style.endsWith(';')) style += ';';
1145
+ }
1146
+
1147
+ /* istanbul ignore next - defensive: additionalStyle without style doesn't occur with current tags */
1148
+ const fullStyle = additionalStyle ? (style ? `${style}${additionalStyle}` : additionalStyle) : style;
1149
+ return ` style="${fullStyle}"`;
1150
+ } else {
1151
+ const classAttr = ` class="${CLASS_PREFIX}${tag}"`;
1152
+ if (additionalStyle) {
1153
+ return `${classAttr} style="${additionalStyle}"`;
1154
+ }
1155
+ return classAttr;
1156
+ }
1157
+ };
1158
+ }
1159
+
1160
+ // ════════════════════════════════════════════════════════════════════
1161
+ // Main parser function
1162
+ // ════════════════════════════════════════════════════════════════════
1163
+
1164
+ function quikdown(markdown, options = {}) {
1165
+ // ── Guard: only process non-empty strings ──
1166
+ if (!markdown || typeof markdown !== 'string') {
1167
+ return '';
1168
+ }
1169
+
1170
+ // ── Unpack options ──
1171
+ const { fence_plugin, inline_styles = false, bidirectional = false, lazy_linefeeds = false, allow_unsafe_html = false } = options;
1172
+ const styles = QUIKDOWN_STYLES;
1173
+ const getAttr = createGetAttr(inline_styles, styles);
1174
+
1175
+ // ── Helpers (closed over options) ──
1176
+
1177
+ /** Escape the five HTML-special characters. */
1178
+ function escapeHtml(text) {
1179
+ return text.replace(/[&<>"']/g, m => ESC_MAP[m]);
1180
+ }
1181
+
1182
+ /**
1183
+ * Bidirectional marker helper.
1184
+ * When bidirectional mode is on, returns ` data-qd="…"`.
1185
+ * The non-bidirectional branch is a trivial no-op arrow; it is
1186
+ * exercised in the core bundle but never in quikdown_bd.
1187
+ */
1188
+ /* istanbul ignore next - trivial no-op fallback */
1189
+ const dataQd = bidirectional ? (marker) => ` data-qd="${escapeHtml(marker)}"` : () => '';
1190
+
1191
+ /**
1192
+ * Sanitize a URL to block javascript:, vbscript:, and non-image data: URIs.
1193
+ * Returns '#' for blocked URLs.
1194
+ */
1195
+ function sanitizeUrl(url, allowUnsafe = false) {
1196
+ /* istanbul ignore next - defensive programming, regex ensures url is never empty */
1197
+ if (!url) return '';
1198
+ if (allowUnsafe) return url;
1199
+
1200
+ const trimmedUrl = url.trim();
1201
+ const lowerUrl = trimmedUrl.toLowerCase();
1202
+ const dangerousProtocols = ['javascript:', 'vbscript:', 'data:'];
1203
+
1204
+ for (const protocol of dangerousProtocols) {
1205
+ if (lowerUrl.startsWith(protocol)) {
1206
+ if (protocol === 'data:' && lowerUrl.startsWith('data:image/')) {
1207
+ return trimmedUrl;
1208
+ }
1209
+ return '#';
1210
+ }
1211
+ }
1212
+ return trimmedUrl;
1213
+ }
1214
+
1215
+ // ────────────────────────────────────────────────────────────────
1216
+ // Phase 1 — Code Extraction
1217
+ // ────────────────────────────────────────────────────────────────
1218
+ // Why extract code first? Fenced blocks and inline code spans can
1219
+ // contain markdown-like characters (*, _, #, |, etc.) that must NOT
1220
+ // be interpreted as formatting. By pulling them out and replacing
1221
+ // with unique placeholders, the rest of the pipeline never sees them.
1222
+
1223
+ let html = markdown;
1224
+ const codeBlocks = []; // Array of {lang, code, custom, fence, hasReverse}
1225
+ const inlineCodes = []; // Array of escaped-HTML strings
1226
+
1227
+ // ── Fenced code blocks ──
1228
+ // Matches paired fences: ``` with ``` and ~~~ with ~~~.
1229
+ // The fence must start at column 0 of a line (^ with /m flag).
1230
+ // Group 1 = fence marker, Group 2 = language hint, Group 3 = code body.
1231
+ html = html.replace(/^(```|~~~)([^\n]*)\n([\s\S]*?)^\1$/gm, (match, fence, lang, code) => {
1232
+ const placeholder = `${PLACEHOLDER_CB}${codeBlocks.length}§`;
1233
+ const langTrimmed = lang ? lang.trim() : '';
1234
+
1235
+ if (fence_plugin && fence_plugin.render && typeof fence_plugin.render === 'function') {
1236
+ // Custom plugin — store raw code (un-escaped) so the plugin
1237
+ // receives the original source.
1238
+ codeBlocks.push({
1239
+ lang: langTrimmed,
1240
+ code: code.trimEnd(),
1241
+ custom: true,
1242
+ fence: fence,
1243
+ hasReverse: !!fence_plugin.reverse
1244
+ });
1245
+ } else {
1246
+ // Default — pre-escape the code for safe HTML output.
1247
+ codeBlocks.push({
1248
+ lang: langTrimmed,
1249
+ code: escapeHtml(code.trimEnd()),
1250
+ custom: false,
1251
+ fence: fence
1252
+ });
1253
+ }
1254
+ return placeholder;
1255
+ });
1256
+
1257
+ // ── Inline code spans ──
1258
+ // Matches a single backtick pair: `content`.
1259
+ // Content is captured and HTML-escaped immediately.
1260
+ html = html.replace(/`([^`]+)`/g, (match, code) => {
1261
+ const placeholder = `${PLACEHOLDER_IC}${inlineCodes.length}§`;
1262
+ inlineCodes.push(escapeHtml(code));
1263
+ return placeholder;
1264
+ });
1265
+
1266
+ // ────────────────────────────────────────────────────────────────
1267
+ // Phase 2 — HTML Escaping
1268
+ // ────────────────────────────────────────────────────────────────
1269
+ // All remaining text (everything except code placeholders) is escaped
1270
+ // to prevent XSS. The `allow_unsafe_html` option skips this for
1271
+ // trusted pipelines that intentionally embed raw HTML.
1272
+
1273
+ if (!allow_unsafe_html) {
1274
+ html = escapeHtml(html);
1275
+ }
1276
+
1277
+ // ────────────────────────────────────────────────────────────────
1278
+ // Phase 3 — Block Scanning + Inline Formatting + Paragraphs
1279
+ // ────────────────────────────────────────────────────────────────
1280
+ // This is the heart of the lexer rewrite. Instead of applying
1281
+ // 10+ global regex passes, we:
1282
+ // 1. Process tables (line walker — tables need multi-line lookahead)
1283
+ // 2. Scan remaining lines for headings, HR, blockquotes
1284
+ // 3. Process lists (line walker — lists need indent tracking)
1285
+ // 4. Apply inline formatting to all text content
1286
+ // 5. Wrap remaining text in <p> tags
1287
+ //
1288
+ // Steps 1 and 3 are line-walkers that process the full text in a
1289
+ // single pass each. Step 2 replaces global regex with a per-line
1290
+ // scanner. Steps 4-5 are applied to the result.
1291
+ //
1292
+ // Total: 3 structured passes instead of 10+ regex passes.
1293
+
1294
+ // ── Step 1: Tables ──
1295
+ // Tables need multi-line lookahead (header → separator → body rows)
1296
+ // so they're handled by a dedicated line-walker first.
1297
+ html = processTable(html, getAttr);
1298
+
1299
+ // ── Step 2: Headings, HR, Blockquotes ──
1300
+ // These are simple line-level constructs. We scan each line once
1301
+ // and replace matching lines with their HTML representation.
1302
+ html = scanLineBlocks(html, getAttr, dataQd);
1303
+
1304
+ // ── Step 3: Lists ──
1305
+ // Lists need indent-level tracking across lines, so they get their
1306
+ // own line-walker.
1307
+ html = processLists(html, getAttr, inline_styles, bidirectional);
1308
+
1309
+ // ── Step 4: Inline formatting ──
1310
+ // Apply bold, italic, strikethrough, images, links, and autolinks
1311
+ // to all text content. This runs on the output of steps 1-3, so
1312
+ // it sees text inside headings, blockquotes, table cells, list
1313
+ // items, and paragraph text.
1314
+
1315
+ // Images (must come before links — ![alt](src) vs [text](url))
1316
+ html = html.replace(/!\[([^\]]*)\]\(([^)]+)\)/g, (match, alt, src) => {
1317
+ const sanitizedSrc = sanitizeUrl(src, options.allow_unsafe_urls);
1318
+ /* istanbul ignore next - bd-only branch */
1319
+ const altAttr = bidirectional && alt ? ` data-qd-alt="${escapeHtml(alt)}"` : '';
1320
+ /* istanbul ignore next - bd-only branch */
1321
+ const srcAttr = bidirectional ? ` data-qd-src="${escapeHtml(src)}"` : '';
1322
+ return `<img${getAttr('img')} src="${sanitizedSrc}" alt="${alt}"${altAttr}${srcAttr}${dataQd('!')}>`;
1323
+ });
1324
+
1325
+ // Links
1326
+ html = html.replace(/\[([^\]]+)\]\(([^)]+)\)/g, (match, text, href) => {
1327
+ const sanitizedHref = sanitizeUrl(href, options.allow_unsafe_urls);
1328
+ const isExternal = /^https?:\/\//i.test(sanitizedHref);
1329
+ const rel = isExternal ? ' rel="noopener noreferrer"' : '';
1330
+ /* istanbul ignore next - bd-only branch */
1331
+ const textAttr = bidirectional ? ` data-qd-text="${escapeHtml(text)}"` : '';
1332
+ return `<a${getAttr('a')} href="${sanitizedHref}"${rel}${textAttr}${dataQd('[')}>${text}</a>`;
1333
+ });
1334
+
1335
+ // Autolinks — bare https?:// URLs become clickable <a> tags
1336
+ html = html.replace(/(^|\s)(https?:\/\/[^\s<]+)/g, (match, prefix, url) => {
1337
+ const sanitizedUrl = sanitizeUrl(url, options.allow_unsafe_urls);
1338
+ return `${prefix}<a${getAttr('a')} href="${sanitizedUrl}" rel="noopener noreferrer">${url}</a>`;
1339
+ });
1340
+
1341
+ // Protect rendered tags so emphasis regexes don't see attribute
1342
+ // values — fixes #3 (underscores in URLs interpreted as emphasis).
1343
+ const savedTags = [];
1344
+ html = html.replace(/<[^>]+>/g, m => { savedTags.push(m); return `%%T${savedTags.length - 1}%%`; });
1345
+
1346
+ // Bold, italic, strikethrough
1347
+ const inlinePatterns = [
1348
+ [/\*\*(.+?)\*\*/g, 'strong', '**'],
1349
+ [/__(.+?)__/g, 'strong', '__'],
1350
+ [/(?<!\*)\*(?!\*)(.+?)(?<!\*)\*(?!\*)/g, 'em', '*'],
1351
+ [/(?<!_)_(?!_)(.+?)(?<!_)_(?!_)/g, 'em', '_'],
1352
+ [/~~(.+?)~~/g, 'del', '~~']
1353
+ ];
1354
+ inlinePatterns.forEach(([pattern, tag, marker]) => {
1355
+ html = html.replace(pattern, `<${tag}${getAttr(tag)}${dataQd(marker)}>$1</${tag}>`);
1356
+ });
1357
+
1358
+ // Restore protected tags
1359
+ html = html.replace(/%%T(\d+)%%/g, (_, i) => savedTags[i]);
1360
+
1361
+ // ── Step 5: Line breaks + paragraph wrapping ──
1362
+ if (lazy_linefeeds) {
1363
+ // Lazy linefeeds mode: every single \n becomes <br> EXCEPT:
1364
+ // • Double newlines → paragraph break
1365
+ // • Newlines adjacent to block elements (h, blockquote, pre, hr, table, list)
1366
+ //
1367
+ // Strategy: protect block-adjacent newlines with §N§, convert
1368
+ // the rest, then restore.
1369
+
1370
+ const blocks = [];
1371
+ let bi = 0;
1372
+
1373
+ // Protect tables and lists from <br> injection
1374
+ html = html.replace(/<(table|[uo]l)[^>]*>[\s\S]*?<\/\1>/g, m => {
1375
+ blocks[bi] = m;
1376
+ return `§B${bi++}§`;
1377
+ });
1378
+
1379
+ html = html.replace(/\n\n+/g, '§P§')
1380
+ // After block-level closing tags
1381
+ .replace(/(<\/(?:h[1-6]|blockquote|pre)>)\n/g, '$1§N§')
1382
+ .replace(/(<(?:h[1-6]|blockquote|pre|hr)[^>]*>)\n/g, '$1§N§')
1383
+ // Before block-level opening tags
1384
+ .replace(/\n(<(?:h[1-6]|blockquote|pre|hr)[^>]*>)/g, '§N§$1')
1385
+ .replace(/\n(§B\d+§)/g, '§N§$1')
1386
+ .replace(/(§B\d+§)\n/g, '$1§N§')
1387
+ // Convert surviving newlines to <br>
1388
+ .replace(/\n/g, `<br${getAttr('br')}>`)
1389
+ // Restore
1390
+ .replace(/§N§/g, '\n')
1391
+ .replace(/§P§/g, '</p><p>');
1392
+
1393
+ // Restore protected blocks
1394
+ blocks.forEach((b, i) => html = html.replace(`§B${i}§`, b));
1395
+
1396
+ html = '<p>' + html + '</p>';
1397
+ } else {
1398
+ // Standard mode: two trailing spaces → <br>, double newline → new paragraph
1399
+ html = html.replace(/ {2}$/gm, `<br${getAttr('br')}>`);
1400
+
1401
+ html = html.replace(/\n\n+/g, (match, offset) => {
1402
+ const before = html.substring(0, offset);
1403
+ if (before.match(/<\/(h[1-6]|blockquote|ul|ol|table|pre|hr)>$/)) {
1404
+ return '<p>';
1405
+ }
1406
+ return '</p><p>';
1407
+ });
1408
+ html = '<p>' + html + '</p>';
1409
+ }
1410
+
1411
+ // ── Step 6: Cleanup ──
1412
+ // Remove <p> wrappers that accidentally enclose block elements.
1413
+ // This is simpler than trying to prevent them during wrapping.
1414
+ const cleanupPatterns = [
1415
+ [/<p><\/p>/g, ''],
1416
+ [/<p>(<h[1-6][^>]*>)/g, '$1'],
1417
+ [/(<\/h[1-6]>)<\/p>/g, '$1'],
1418
+ [/<p>(<blockquote[^>]*>)/g, '$1'],
1419
+ [/(<\/blockquote>)<\/p>/g, '$1'],
1420
+ [/<p>(<ul[^>]*>|<ol[^>]*>)/g, '$1'],
1421
+ [/(<\/ul>|<\/ol>)<\/p>/g, '$1'],
1422
+ [/<p>(<hr[^>]*>)<\/p>/g, '$1'],
1423
+ [/<p>(<table[^>]*>)/g, '$1'],
1424
+ [/(<\/table>)<\/p>/g, '$1'],
1425
+ [/<p>(<pre[^>]*>)/g, '$1'],
1426
+ [/(<\/pre>)<\/p>/g, '$1'],
1427
+ [new RegExp(`<p>(${PLACEHOLDER_CB}\\d+§)</p>`, 'g'), '$1']
1428
+ ];
1429
+ cleanupPatterns.forEach(([pattern, replacement]) => {
1430
+ html = html.replace(pattern, replacement);
1431
+ });
1432
+
1433
+ // When a block element is followed by a newline and then text, open a <p>.
1434
+ html = html.replace(/(<\/(?:h[1-6]|blockquote|ul|ol|table|pre|hr)>)\n([^<])/g, '$1\n<p>$2');
1435
+
1436
+ // ────────────────────────────────────────────────────────────────
1437
+ // Phase 4 — Code Restoration
1438
+ // ────────────────────────────────────────────────────────────────
1439
+ // Replace placeholders with rendered HTML. For fenced blocks this
1440
+ // means wrapping in <pre><code>…</code></pre> (or calling the
1441
+ // fence_plugin). For inline code it means <code>…</code>.
1442
+
1443
+ codeBlocks.forEach((block, i) => {
1444
+ let replacement;
1445
+
1446
+ if (block.custom && fence_plugin && fence_plugin.render) {
1447
+ // Delegate to the user-provided fence plugin.
1448
+ replacement = fence_plugin.render(block.code, block.lang);
1449
+
1450
+ if (replacement === undefined) {
1451
+ // Plugin declined — fall back to default rendering.
1452
+ const langClass = !inline_styles && block.lang ? ` class="language-${block.lang}"` : '';
1453
+ const codeAttr = inline_styles ? getAttr('code') : langClass;
1454
+ /* istanbul ignore next - bd-only branch */
1455
+ const langAttr = bidirectional && block.lang ? ` data-qd-lang="${escapeHtml(block.lang)}"` : '';
1456
+ /* istanbul ignore next - bd-only branch */
1457
+ const fenceAttr = bidirectional ? ` data-qd-fence="${escapeHtml(block.fence)}"` : '';
1458
+ replacement = `<pre${getAttr('pre')}${fenceAttr}${langAttr}><code${codeAttr}>${escapeHtml(block.code)}</code></pre>`;
1459
+ } else /* istanbul ignore next - bd-only branch */ if (bidirectional) {
1460
+ // Plugin returned HTML — inject data attributes for roundtrip.
1461
+ replacement = replacement.replace(/^<(\w+)/,
1462
+ `<$1 data-qd-fence="${escapeHtml(block.fence)}" data-qd-lang="${escapeHtml(block.lang)}" data-qd-source="${escapeHtml(block.code)}"`);
1463
+ }
1464
+ } else {
1465
+ // Default rendering — wrap in <pre><code>.
1466
+ const langClass = !inline_styles && block.lang ? ` class="language-${block.lang}"` : '';
1467
+ const codeAttr = inline_styles ? getAttr('code') : langClass;
1468
+ /* istanbul ignore next - bd-only branch */
1469
+ const langAttr = bidirectional && block.lang ? ` data-qd-lang="${escapeHtml(block.lang)}"` : '';
1470
+ /* istanbul ignore next - bd-only branch */
1471
+ const fenceAttr = bidirectional ? ` data-qd-fence="${escapeHtml(block.fence)}"` : '';
1472
+ replacement = `<pre${getAttr('pre')}${fenceAttr}${langAttr}><code${codeAttr}>${block.code}</code></pre>`;
1473
+ }
1474
+
1475
+ const placeholder = `${PLACEHOLDER_CB}${i}§`;
1476
+ html = html.replace(placeholder, replacement);
1477
+ });
1478
+
1479
+ // Restore inline code spans
1480
+ inlineCodes.forEach((code, i) => {
1481
+ const placeholder = `${PLACEHOLDER_IC}${i}§`;
1482
+ html = html.replace(placeholder, `<code${getAttr('code')}${dataQd('`')}>${code}</code>`);
1483
+ });
1484
+
1485
+ return html.trim();
1486
+ }
1487
+
1488
+ // ════════════════════════════════════════════════════════════════════
1489
+ // Block-level line scanner
1490
+ // ════════════════════════════════════════════════════════════════════
1491
+
1492
+ /**
1493
+ * scanLineBlocks — single-pass line scanner for headings, HR, blockquotes
1494
+ *
1495
+ * Walks the text line by line. For each line it checks (in order):
1496
+ * 1. Heading — starts with 1-6 '#' followed by a space
1497
+ * 2. HR — line is entirely '---…' (3+ dashes, optional trailing space)
1498
+ * 3. Blockquote — starts with '&gt; ' (the > was already HTML-escaped)
1499
+ *
1500
+ * Lines that don't match any block pattern are passed through unchanged.
1501
+ *
1502
+ * This replaces three separate global regex passes from the pre-1.2.8
1503
+ * architecture with one structured scan.
1504
+ *
1505
+ * @param {string} text The document text (HTML-escaped, code extracted)
1506
+ * @param {Function} getAttr Attribute factory (class or style)
1507
+ * @param {Function} dataQd Bidirectional marker factory
1508
+ * @returns {string} Text with block-level elements rendered
1509
+ */
1510
+ function scanLineBlocks(text, getAttr, dataQd) {
1511
+ const lines = text.split('\n');
1512
+ const result = [];
1513
+ let i = 0;
1514
+
1515
+ while (i < lines.length) {
1516
+ const line = lines[i];
1517
+
1518
+ // ── Heading ──
1519
+ // Count leading '#' characters. Valid heading: 1-6 hashes then a space.
1520
+ // Example: "## Hello World ##" → <h2>Hello World</h2>
1521
+ let hashCount = 0;
1522
+ while (hashCount < line.length && hashCount < 7 && line[hashCount] === '#') {
1523
+ hashCount++;
1524
+ }
1525
+ if (hashCount >= 1 && hashCount <= 6 && line[hashCount] === ' ') {
1526
+ // Extract content after "# " and strip trailing hashes
1527
+ const content = line.slice(hashCount + 1).replace(/\s*#+\s*$/, '');
1528
+ const tag = 'h' + hashCount;
1529
+ result.push(`<${tag}${getAttr(tag)}${dataQd('#'.repeat(hashCount))}>${content}</${tag}>`);
1530
+ i++;
1531
+ continue;
1532
+ }
1533
+
1534
+ // ── Horizontal Rule ──
1535
+ // Three or more dashes, optional trailing whitespace, nothing else.
1536
+ if (isDashHRLine(line)) {
1537
+ result.push(`<hr${getAttr('hr')}>`);
1538
+ i++;
1539
+ continue;
1540
+ }
1541
+
1542
+ // ── Blockquote ──
1543
+ // After Phase 2, the '>' character has been escaped to '&gt;'.
1544
+ // Pattern: "&gt; content" or merged consecutive blockquotes.
1545
+ if (/^&gt;\s+/.test(line)) {
1546
+ result.push(`<blockquote${getAttr('blockquote')}>${line.replace(/^&gt;\s+/, '')}</blockquote>`);
1547
+ i++;
1548
+ continue;
1549
+ }
1550
+
1551
+ // ── Pass-through ──
1552
+ result.push(line);
1553
+ i++;
1554
+ }
1555
+
1556
+ // Merge consecutive blockquotes into a single element.
1557
+ // <blockquote>A</blockquote>\n<blockquote>B</blockquote>
1558
+ // → <blockquote>A\nB</blockquote>
1559
+ let joined = result.join('\n');
1560
+ joined = joined.replace(/<\/blockquote>\n<blockquote>/g, '\n');
1561
+ return joined;
1562
+ }
1563
+
1564
+ // ════════════════════════════════════════════════════════════════════
1565
+ // Table processing (line walker)
1566
+ // ════════════════════════════════════════════════════════════════════
1567
+
1568
+ /**
1569
+ * Inline markdown formatter for table cells.
1570
+ * Handles bold, italic, strikethrough, and code within cell text.
1571
+ * Links / images / autolinks are handled by the global inline pass
1572
+ * (Phase 3 Step 4) which runs after table processing.
1573
+ */
1574
+ function processInlineMarkdown(text, getAttr) {
1575
+ const patterns = [
1576
+ [/\*\*(.+?)\*\*/g, 'strong'],
1577
+ [/__(.+?)__/g, 'strong'],
1578
+ [/(?<!\*)\*(?!\*)(.+?)(?<!\*)\*(?!\*)/g, 'em'],
1579
+ [/(?<!_)_(?!_)(.+?)(?<!_)_(?!_)/g, 'em'],
1580
+ [/~~(.+?)~~/g, 'del'],
1581
+ [/`([^`]+)`/g, 'code']
1582
+ ];
1583
+ patterns.forEach(([pattern, tag]) => {
1584
+ text = text.replace(pattern, `<${tag}${getAttr(tag)}>$1</${tag}>`);
1585
+ });
1586
+ return text;
1587
+ }
1588
+
1589
+ /**
1590
+ * processTable — line walker for markdown tables
1591
+ *
1592
+ * Walks through lines looking for runs of pipe-containing lines.
1593
+ * Each run is validated (must contain a separator row: |---|---|)
1594
+ * and rendered as an HTML <table>. Invalid runs are restored as-is.
1595
+ *
1596
+ * @param {string} text Full document text
1597
+ * @param {Function} getAttr Attribute factory
1598
+ * @returns {string} Text with tables rendered
1599
+ */
1600
+ function processTable(text, getAttr) {
1601
+ const lines = text.split('\n');
1602
+ const result = [];
1603
+ let inTable = false;
1604
+ let tableLines = [];
1605
+
1606
+ for (let i = 0; i < lines.length; i++) {
1607
+ const line = lines[i].trim();
1608
+
1609
+ if (line.includes('|') && (line.startsWith('|') || /[^\\|]/.test(line))) {
1610
+ if (!inTable) {
1611
+ inTable = true;
1612
+ tableLines = [];
1613
+ }
1614
+ tableLines.push(line);
1615
+ } else {
1616
+ if (inTable) {
1617
+ const tableHtml = buildTable(tableLines, getAttr);
1618
+ if (tableHtml) {
1619
+ result.push(tableHtml);
1620
+ } else {
1621
+ result.push(...tableLines);
1622
+ }
1623
+ inTable = false;
1624
+ tableLines = [];
1625
+ }
1626
+ result.push(lines[i]);
1627
+ }
1628
+ }
1629
+
1630
+ // Handle table at end of document
1631
+ if (inTable && tableLines.length > 0) {
1632
+ const tableHtml = buildTable(tableLines, getAttr);
1633
+ if (tableHtml) {
1634
+ result.push(tableHtml);
1635
+ } else {
1636
+ result.push(...tableLines);
1637
+ }
1638
+ }
1639
+
1640
+ return result.join('\n');
1641
+ }
1642
+
1643
+ /**
1644
+ * buildTable — validate and render a table from accumulated lines
1645
+ *
1646
+ * @param {string[]} lines Array of pipe-containing lines
1647
+ * @param {Function} getAttr Attribute factory
1648
+ * @returns {string|null} HTML table string, or null if invalid
1649
+ */
1650
+ function buildTable(lines, getAttr) {
1651
+ if (lines.length < 2) return null;
1652
+
1653
+ // Find the separator row (---|---|)
1654
+ let separatorIndex = -1;
1655
+ for (let i = 1; i < lines.length; i++) {
1656
+ if (/^\|?[\s\-:|]+\|?$/.test(lines[i]) && lines[i].includes('-')) {
1657
+ separatorIndex = i;
1658
+ break;
1659
+ }
1660
+ }
1661
+ if (separatorIndex === -1) return null;
1662
+
1663
+ const headerLines = lines.slice(0, separatorIndex);
1664
+ const bodyLines = lines.slice(separatorIndex + 1);
1665
+
1666
+ // Parse alignment from separator cells (:--- = left, :---: = center, ---: = right)
1667
+ const separator = lines[separatorIndex];
1668
+ const separatorCells = separator.trim().replace(/^\|/, '').replace(/\|$/, '').split('|');
1669
+ const alignments = separatorCells.map(cell => {
1670
+ const trimmed = cell.trim();
1671
+ if (trimmed.startsWith(':') && trimmed.endsWith(':')) return 'center';
1672
+ if (trimmed.endsWith(':')) return 'right';
1673
+ return 'left';
1674
+ });
1675
+
1676
+ let html = `<table${getAttr('table')}>\n`;
1677
+
1678
+ // Header
1679
+ html += `<thead${getAttr('thead')}>\n`;
1680
+ headerLines.forEach(line => {
1681
+ html += `<tr${getAttr('tr')}>\n`;
1682
+ const cells = line.trim().replace(/^\|/, '').replace(/\|$/, '').split('|');
1683
+ cells.forEach((cell, i) => {
1684
+ const alignStyle = alignments[i] && alignments[i] !== 'left' ? `text-align:${alignments[i]}` : '';
1685
+ const processedCell = processInlineMarkdown(cell.trim(), getAttr);
1686
+ html += `<th${getAttr('th', alignStyle)}>${processedCell}</th>\n`;
1687
+ });
1688
+ html += '</tr>\n';
1689
+ });
1690
+ html += '</thead>\n';
1691
+
1692
+ // Body
1693
+ if (bodyLines.length > 0) {
1694
+ html += `<tbody${getAttr('tbody')}>\n`;
1695
+ bodyLines.forEach(line => {
1696
+ html += `<tr${getAttr('tr')}>\n`;
1697
+ const cells = line.trim().replace(/^\|/, '').replace(/\|$/, '').split('|');
1698
+ cells.forEach((cell, i) => {
1699
+ const alignStyle = alignments[i] && alignments[i] !== 'left' ? `text-align:${alignments[i]}` : '';
1700
+ const processedCell = processInlineMarkdown(cell.trim(), getAttr);
1701
+ html += `<td${getAttr('td', alignStyle)}>${processedCell}</td>\n`;
1702
+ });
1703
+ html += '</tr>\n';
1704
+ });
1705
+ html += '</tbody>\n';
1706
+ }
1707
+
1708
+ html += '</table>';
1709
+ return html;
1710
+ }
1711
+
1712
+ // ════════════════════════════════════════════════════════════════════
1713
+ // List processing (line walker)
1714
+ // ════════════════════════════════════════════════════════════════════
1715
+
1716
+ /**
1717
+ * processLists — line walker for ordered, unordered, and task lists
1718
+ *
1719
+ * Scans each line for list markers (-, *, +, 1., 2., etc.) with
1720
+ * optional leading indentation for nesting. Non-list lines close
1721
+ * any open lists and pass through unchanged.
1722
+ *
1723
+ * Task lists (- [ ] / - [x]) are detected and rendered with
1724
+ * checkbox inputs.
1725
+ *
1726
+ * @param {string} text Full document text
1727
+ * @param {Function} getAttr Attribute factory
1728
+ * @param {boolean} inline_styles Whether to use inline styles
1729
+ * @param {boolean} bidirectional Whether to add data-qd markers
1730
+ * @returns {string} Text with lists rendered
1731
+ */
1732
+ function processLists(text, getAttr, inline_styles, bidirectional) {
1733
+ const lines = text.split('\n');
1734
+ const result = [];
1735
+ const listStack = []; // tracks nesting: [{type:'ul', level:0}, …]
1736
+
1737
+ // Helper to escape HTML for data-qd attributes. List markers (`-`, `*`,
1738
+ // `+`, `1.`, etc.) never contain HTML-special chars, so the replace
1739
+ // callback is defensive-only and never actually fires in practice.
1740
+ /* istanbul ignore next - defensive: list markers never trigger escaping */
1741
+ const escapeHtml = (text) => text.replace(/[&<>"']/g,
1742
+ /* istanbul ignore next - defensive: list markers never contain HTML specials */
1743
+ m => ({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'})[m]);
1744
+ /* istanbul ignore next - trivial no-op fallback; not exercised via bd bundle */
1745
+ const dataQd = bidirectional ? (marker) => ` data-qd="${escapeHtml(marker)}"` : () => '';
1746
+
1747
+ for (let i = 0; i < lines.length; i++) {
1748
+ const line = lines[i];
1749
+ const match = line.match(/^(\s*)([*\-+]|\d+\.)\s+(.+)$/);
1750
+
1751
+ if (match) {
1752
+ const [, indent, marker, content] = match;
1753
+ const level = Math.floor(indent.length / 2);
1754
+ const isOrdered = /^\d+\./.test(marker);
1755
+ const listType = isOrdered ? 'ol' : 'ul';
1756
+
1757
+ // Task list detection (only in unordered lists)
1758
+ let listItemContent = content;
1759
+ let taskListClass = '';
1760
+ const taskMatch = content.match(/^\[([x ])\]\s+(.*)$/i);
1761
+ if (taskMatch && !isOrdered) {
1762
+ const [, checked, taskContent] = taskMatch;
1763
+ const isChecked = checked.toLowerCase() === 'x';
1764
+ const checkboxAttr = inline_styles
1765
+ ? ' style="margin-right:.5em"'
1766
+ : ` class="${CLASS_PREFIX}task-checkbox"`;
1767
+ listItemContent = `<input type="checkbox"${checkboxAttr}${isChecked ? ' checked' : ''} disabled> ${taskContent}`;
1768
+ taskListClass = inline_styles ? ' style="list-style:none"' : ` class="${CLASS_PREFIX}task-item"`;
1769
+ }
1770
+
1771
+ // Close deeper nesting levels
1772
+ while (listStack.length > level + 1) {
1773
+ const list = listStack.pop();
1774
+ result.push(`</${list.type}>`);
1775
+ }
1776
+
1777
+ // Open new list or switch type at current level
1778
+ if (listStack.length === level) {
1779
+ listStack.push({ type: listType, level });
1780
+ result.push(`<${listType}${getAttr(listType)}>`);
1781
+ } else if (listStack.length === level + 1) {
1782
+ const currentList = listStack[listStack.length - 1];
1783
+ if (currentList.type !== listType) {
1784
+ result.push(`</${currentList.type}>`);
1785
+ listStack.pop();
1786
+ listStack.push({ type: listType, level });
1787
+ result.push(`<${listType}${getAttr(listType)}>`);
1788
+ }
1789
+ }
1790
+
1791
+ const liAttr = taskListClass || getAttr('li');
1792
+ result.push(`<li${liAttr}${dataQd(marker)}>${listItemContent}</li>`);
1793
+ } else {
1794
+ // Not a list item — close all open lists
1795
+ while (listStack.length > 0) {
1796
+ const list = listStack.pop();
1797
+ result.push(`</${list.type}>`);
1798
+ }
1799
+ result.push(line);
1800
+ }
1801
+ }
1802
+
1803
+ // Close any remaining open lists
1804
+ while (listStack.length > 0) {
1805
+ const list = listStack.pop();
1806
+ result.push(`</${list.type}>`);
1807
+ }
1808
+
1809
+ return result.join('\n');
1810
+ }
1811
+
1812
+ // ════════════════════════════════════════════════════════════════════
1813
+ // Static API
1814
+ // ════════════════════════════════════════════════════════════════════
1815
+
1816
+ /**
1817
+ * Emit CSS rules for all quikdown elements.
1818
+ *
1819
+ * @param {string} prefix Class prefix (default: 'quikdown-')
1820
+ * @param {string} theme 'light' (default) or 'dark'
1821
+ * @returns {string} CSS text
1822
+ */
1823
+ quikdown.emitStyles = function(prefix = 'quikdown-', theme = 'light') {
1824
+ const styles = QUIKDOWN_STYLES;
1825
+
1826
+ const themeOverrides = {
1827
+ dark: {
1828
+ '#f4f4f4': '#2a2a2a', // pre background
1829
+ '#f0f0f0': '#2a2a2a', // code background
1830
+ '#f2f2f2': '#2a2a2a', // th background
1831
+ '#ddd': '#3a3a3a', // borders
1832
+ '#06c': '#6db3f2', // links
1833
+ _textColor: '#e0e0e0'
1834
+ },
1835
+ light: {
1836
+ _textColor: '#333'
1837
+ }
1838
+ };
1839
+
1840
+ let css = '';
1841
+ for (const [tag, style] of Object.entries(styles)) {
1842
+ let themedStyle = style;
1843
+
1844
+ if (theme === 'dark' && themeOverrides.dark) {
1845
+ for (const [oldColor, newColor] of Object.entries(themeOverrides.dark)) {
1846
+ if (!oldColor.startsWith('_')) {
1847
+ themedStyle = themedStyle.replaceAll(oldColor, newColor);
1848
+ }
1849
+ }
1850
+ const needsTextColor = ['h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'td', 'li', 'blockquote'];
1851
+ if (needsTextColor.includes(tag)) {
1852
+ themedStyle += `;color:${themeOverrides.dark._textColor}`;
1853
+ }
1854
+ } else if (theme === 'light' && themeOverrides.light) {
1855
+ const needsTextColor = ['h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'td', 'li', 'blockquote'];
1856
+ if (needsTextColor.includes(tag)) {
1857
+ themedStyle += `;color:${themeOverrides.light._textColor}`;
1858
+ }
1859
+ }
1860
+
1861
+ css += `.${prefix}${tag} { ${themedStyle} }\n`;
1862
+ }
1863
+
1864
+ return css;
1865
+ };
1866
+
1867
+ /**
1868
+ * Create a pre-configured parser with baked-in options.
1869
+ *
1870
+ * @param {Object} options Options to bake in
1871
+ * @returns {Function} Configured quikdown(markdown) function
1872
+ */
1873
+ quikdown.configure = function(options) {
1874
+ return function(markdown) {
1875
+ return quikdown(markdown, options);
1876
+ };
1877
+ };
1878
+
1879
+ /** Semantic version (injected at build time) */
1880
+ quikdown.version = quikdownVersion;
1881
+
1882
+ // ════════════════════════════════════════════════════════════════════
1883
+ // Exports
1884
+ // ════════════════════════════════════════════════════════════════════
1885
+
1886
+ /* istanbul ignore next */
1887
+ if (typeof module !== 'undefined' && module.exports) {
1888
+ module.exports = quikdown;
1889
+ }
1890
+
1891
+ /* istanbul ignore next */
1892
+ if (typeof window !== 'undefined') {
1893
+ window.quikdown = quikdown;
1894
+ }
1895
+
1896
+ // Subclass that pre-wires quikdown as the message formatter
1897
+ var quikchatMD = /*#__PURE__*/function (_quikchat) {
1898
+ function quikchatMD(parentElement, onSend) {
1899
+ var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
1900
+ _classCallCheck(this, quikchatMD);
1901
+ if (!options.messageFormatter) {
1902
+ options.messageFormatter = function (content) {
1903
+ return quikdown(content);
1904
+ };
1905
+ }
1906
+ return _callSuper(this, quikchatMD, [parentElement, onSend, options]);
1907
+ }
1908
+ _inherits(quikchatMD, _quikchat);
1909
+ return _createClass(quikchatMD);
1910
+ }(quikchat); // Expose quikdown on the class for direct access
1911
+ quikchatMD.quikdown = quikdown;
1912
+
1913
+ export { quikchatMD as default };
1914
+ //# sourceMappingURL=quikchat-md.esm.js.map