@redvars/peacock 3.8.5 → 3.9.0

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 (56) hide show
  1. package/dist/button.js +4 -0
  2. package/dist/button.js.map +1 -1
  3. package/dist/custom-elements-jsdocs.json +249 -15
  4. package/dist/custom-elements.json +1029 -167
  5. package/dist/floating-controller-CZYwnRVu.js +185 -0
  6. package/dist/floating-controller-CZYwnRVu.js.map +1 -0
  7. package/dist/{floating-controller-CnUZnOhK.js → floating-ui.dom-oQieRCpS.js} +2 -183
  8. package/dist/floating-ui.dom-oQieRCpS.js.map +1 -0
  9. package/dist/html-editor.js +3 -21091
  10. package/dist/html-editor.js.map +1 -1
  11. package/dist/index-DcbiqHpf.js +21091 -0
  12. package/dist/index-DcbiqHpf.js.map +1 -0
  13. package/dist/index.js +7 -2
  14. package/dist/index.js.map +1 -1
  15. package/dist/loader.js +15 -2
  16. package/dist/loader.js.map +1 -1
  17. package/dist/markdown-editor.js +4439 -0
  18. package/dist/markdown-editor.js.map +1 -0
  19. package/dist/menu.js +2 -1
  20. package/dist/menu.js.map +1 -1
  21. package/dist/popover.js +2 -1
  22. package/dist/popover.js.map +1 -1
  23. package/dist/{select-D85kpjUt.js → select-CnnPbvpQ.js} +68 -71
  24. package/dist/select-CnnPbvpQ.js.map +1 -0
  25. package/dist/src/index.d.ts +2 -0
  26. package/dist/src/input/input.d.ts +5 -5
  27. package/dist/src/markdown-editor/index.d.ts +2 -0
  28. package/dist/src/markdown-editor/markdown-editor.d.ts +116 -0
  29. package/dist/src/timeline/index.d.ts +2 -0
  30. package/dist/src/timeline/timeline-item.d.ts +23 -0
  31. package/dist/src/timeline/timeline.d.ts +27 -0
  32. package/dist/sub-menu.js +2 -1
  33. package/dist/sub-menu.js.map +1 -1
  34. package/dist/timeline-item.js +175 -0
  35. package/dist/timeline-item.js.map +1 -0
  36. package/dist/timeline.js +69 -0
  37. package/dist/timeline.js.map +1 -0
  38. package/dist/tooltip.js +2 -1
  39. package/dist/tooltip.js.map +1 -1
  40. package/dist/tsconfig.tsbuildinfo +1 -1
  41. package/package.json +5 -1
  42. package/readme.md +2 -2
  43. package/src/button/button/button-sizes.scss +4 -0
  44. package/src/index.ts +2 -0
  45. package/src/input/input.ts +85 -82
  46. package/src/loader.ts +12 -0
  47. package/src/markdown-editor/index.ts +3 -0
  48. package/src/markdown-editor/markdown-editor.scss +378 -0
  49. package/src/markdown-editor/markdown-editor.ts +994 -0
  50. package/src/timeline/index.ts +2 -0
  51. package/src/timeline/timeline-item.scss +108 -0
  52. package/src/timeline/timeline-item.ts +62 -0
  53. package/src/timeline/timeline.scss +21 -0
  54. package/src/timeline/timeline.ts +43 -0
  55. package/dist/floating-controller-CnUZnOhK.js.map +0 -1
  56. package/dist/select-D85kpjUt.js.map +0 -1
@@ -0,0 +1,4439 @@
1
+ import { i, _ as __decorate, I as IndividualComponent, b, A } from './IndividualComponent-Bdwyrvd6.js';
2
+ import { n } from './property-B49QQ8pS.js';
3
+ import { r } from './state-DkTK9EGF.js';
4
+ import { e } from './query-CHb9Ft_d.js';
5
+ import { e as e$1 } from './class-map-DG7CA1et.js';
6
+ import { N as NodeSelection, S as Slice, F as Fragment, D as DOMSerializer, E as Editor, a as StarterKit, U as Underline, P as Placeholder, b as Extension, c as Suggestion, d as Plugin } from './index-DcbiqHpf.js';
7
+ import { c as computePosition, o as offset, f as flip, s as shift } from './floating-ui.dom-oQieRCpS.js';
8
+ import { B as BaseInput } from './BaseInput-CU1zZYKc.js';
9
+ import { r as redispatchEvent } from './dispatch-event-utils-CuEqjlPT.js';
10
+ import './base-Cl6v8-BZ.js';
11
+ import './directive-ZPhl09Yt.js';
12
+
13
+ /**
14
+ * marked v14.1.4 - a markdown parser
15
+ * Copyright (c) 2011-2024, Christopher Jeffrey. (MIT Licensed)
16
+ * https://github.com/markedjs/marked
17
+ */
18
+
19
+ /**
20
+ * DO NOT EDIT THIS FILE
21
+ * The code in this file is generated from files in ./src/
22
+ */
23
+
24
+ /**
25
+ * Gets the original marked default options.
26
+ */
27
+ function _getDefaults() {
28
+ return {
29
+ async: false,
30
+ breaks: false,
31
+ extensions: null,
32
+ gfm: true,
33
+ hooks: null,
34
+ pedantic: false,
35
+ renderer: null,
36
+ silent: false,
37
+ tokenizer: null,
38
+ walkTokens: null,
39
+ };
40
+ }
41
+ let _defaults = _getDefaults();
42
+ function changeDefaults(newDefaults) {
43
+ _defaults = newDefaults;
44
+ }
45
+
46
+ /**
47
+ * Helpers
48
+ */
49
+ const escapeTest = /[&<>"']/;
50
+ const escapeReplace = new RegExp(escapeTest.source, 'g');
51
+ const escapeTestNoEncode = /[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/;
52
+ const escapeReplaceNoEncode = new RegExp(escapeTestNoEncode.source, 'g');
53
+ const escapeReplacements = {
54
+ '&': '&amp;',
55
+ '<': '&lt;',
56
+ '>': '&gt;',
57
+ '"': '&quot;',
58
+ "'": '&#39;',
59
+ };
60
+ const getEscapeReplacement = (ch) => escapeReplacements[ch];
61
+ function escape$1(html, encode) {
62
+ if (encode) {
63
+ if (escapeTest.test(html)) {
64
+ return html.replace(escapeReplace, getEscapeReplacement);
65
+ }
66
+ }
67
+ else {
68
+ if (escapeTestNoEncode.test(html)) {
69
+ return html.replace(escapeReplaceNoEncode, getEscapeReplacement);
70
+ }
71
+ }
72
+ return html;
73
+ }
74
+ const caret = /(^|[^\[])\^/g;
75
+ function edit(regex, opt) {
76
+ let source = typeof regex === 'string' ? regex : regex.source;
77
+ opt = opt || '';
78
+ const obj = {
79
+ replace: (name, val) => {
80
+ let valSource = typeof val === 'string' ? val : val.source;
81
+ valSource = valSource.replace(caret, '$1');
82
+ source = source.replace(name, valSource);
83
+ return obj;
84
+ },
85
+ getRegex: () => {
86
+ return new RegExp(source, opt);
87
+ },
88
+ };
89
+ return obj;
90
+ }
91
+ function cleanUrl(href) {
92
+ try {
93
+ href = encodeURI(href).replace(/%25/g, '%');
94
+ }
95
+ catch {
96
+ return null;
97
+ }
98
+ return href;
99
+ }
100
+ const noopTest = { exec: () => null };
101
+ function splitCells(tableRow, count) {
102
+ // ensure that every cell-delimiting pipe has a space
103
+ // before it to distinguish it from an escaped pipe
104
+ const row = tableRow.replace(/\|/g, (match, offset, str) => {
105
+ let escaped = false;
106
+ let curr = offset;
107
+ while (--curr >= 0 && str[curr] === '\\')
108
+ escaped = !escaped;
109
+ if (escaped) {
110
+ // odd number of slashes means | is escaped
111
+ // so we leave it alone
112
+ return '|';
113
+ }
114
+ else {
115
+ // add space before unescaped |
116
+ return ' |';
117
+ }
118
+ }), cells = row.split(/ \|/);
119
+ let i = 0;
120
+ // First/last cell in a row cannot be empty if it has no leading/trailing pipe
121
+ if (!cells[0].trim()) {
122
+ cells.shift();
123
+ }
124
+ if (cells.length > 0 && !cells[cells.length - 1].trim()) {
125
+ cells.pop();
126
+ }
127
+ if (count) {
128
+ if (cells.length > count) {
129
+ cells.splice(count);
130
+ }
131
+ else {
132
+ while (cells.length < count)
133
+ cells.push('');
134
+ }
135
+ }
136
+ for (; i < cells.length; i++) {
137
+ // leading or trailing whitespace is ignored per the gfm spec
138
+ cells[i] = cells[i].trim().replace(/\\\|/g, '|');
139
+ }
140
+ return cells;
141
+ }
142
+ /**
143
+ * Remove trailing 'c's. Equivalent to str.replace(/c*$/, '').
144
+ * /c*$/ is vulnerable to REDOS.
145
+ *
146
+ * @param str
147
+ * @param c
148
+ * @param invert Remove suffix of non-c chars instead. Default falsey.
149
+ */
150
+ function rtrim(str, c, invert) {
151
+ const l = str.length;
152
+ if (l === 0) {
153
+ return '';
154
+ }
155
+ // Length of suffix matching the invert condition.
156
+ let suffLen = 0;
157
+ // Step left until we fail to match the invert condition.
158
+ while (suffLen < l) {
159
+ const currChar = str.charAt(l - suffLen - 1);
160
+ if (currChar === c && true) {
161
+ suffLen++;
162
+ }
163
+ else {
164
+ break;
165
+ }
166
+ }
167
+ return str.slice(0, l - suffLen);
168
+ }
169
+ function findClosingBracket(str, b) {
170
+ if (str.indexOf(b[1]) === -1) {
171
+ return -1;
172
+ }
173
+ let level = 0;
174
+ for (let i = 0; i < str.length; i++) {
175
+ if (str[i] === '\\') {
176
+ i++;
177
+ }
178
+ else if (str[i] === b[0]) {
179
+ level++;
180
+ }
181
+ else if (str[i] === b[1]) {
182
+ level--;
183
+ if (level < 0) {
184
+ return i;
185
+ }
186
+ }
187
+ }
188
+ return -1;
189
+ }
190
+
191
+ function outputLink(cap, link, raw, lexer) {
192
+ const href = link.href;
193
+ const title = link.title ? escape$1(link.title) : null;
194
+ const text = cap[1].replace(/\\([\[\]])/g, '$1');
195
+ if (cap[0].charAt(0) !== '!') {
196
+ lexer.state.inLink = true;
197
+ const token = {
198
+ type: 'link',
199
+ raw,
200
+ href,
201
+ title,
202
+ text,
203
+ tokens: lexer.inlineTokens(text),
204
+ };
205
+ lexer.state.inLink = false;
206
+ return token;
207
+ }
208
+ return {
209
+ type: 'image',
210
+ raw,
211
+ href,
212
+ title,
213
+ text: escape$1(text),
214
+ };
215
+ }
216
+ function indentCodeCompensation(raw, text) {
217
+ const matchIndentToCode = raw.match(/^(\s+)(?:```)/);
218
+ if (matchIndentToCode === null) {
219
+ return text;
220
+ }
221
+ const indentToCode = matchIndentToCode[1];
222
+ return text
223
+ .split('\n')
224
+ .map(node => {
225
+ const matchIndentInNode = node.match(/^\s+/);
226
+ if (matchIndentInNode === null) {
227
+ return node;
228
+ }
229
+ const [indentInNode] = matchIndentInNode;
230
+ if (indentInNode.length >= indentToCode.length) {
231
+ return node.slice(indentToCode.length);
232
+ }
233
+ return node;
234
+ })
235
+ .join('\n');
236
+ }
237
+ /**
238
+ * Tokenizer
239
+ */
240
+ class _Tokenizer {
241
+ options;
242
+ rules; // set by the lexer
243
+ lexer; // set by the lexer
244
+ constructor(options) {
245
+ this.options = options || _defaults;
246
+ }
247
+ space(src) {
248
+ const cap = this.rules.block.newline.exec(src);
249
+ if (cap && cap[0].length > 0) {
250
+ return {
251
+ type: 'space',
252
+ raw: cap[0],
253
+ };
254
+ }
255
+ }
256
+ code(src) {
257
+ const cap = this.rules.block.code.exec(src);
258
+ if (cap) {
259
+ const text = cap[0].replace(/^(?: {1,4}| {0,3}\t)/gm, '');
260
+ return {
261
+ type: 'code',
262
+ raw: cap[0],
263
+ codeBlockStyle: 'indented',
264
+ text: !this.options.pedantic
265
+ ? rtrim(text, '\n')
266
+ : text,
267
+ };
268
+ }
269
+ }
270
+ fences(src) {
271
+ const cap = this.rules.block.fences.exec(src);
272
+ if (cap) {
273
+ const raw = cap[0];
274
+ const text = indentCodeCompensation(raw, cap[3] || '');
275
+ return {
276
+ type: 'code',
277
+ raw,
278
+ lang: cap[2] ? cap[2].trim().replace(this.rules.inline.anyPunctuation, '$1') : cap[2],
279
+ text,
280
+ };
281
+ }
282
+ }
283
+ heading(src) {
284
+ const cap = this.rules.block.heading.exec(src);
285
+ if (cap) {
286
+ let text = cap[2].trim();
287
+ // remove trailing #s
288
+ if (/#$/.test(text)) {
289
+ const trimmed = rtrim(text, '#');
290
+ if (this.options.pedantic) {
291
+ text = trimmed.trim();
292
+ }
293
+ else if (!trimmed || / $/.test(trimmed)) {
294
+ // CommonMark requires space before trailing #s
295
+ text = trimmed.trim();
296
+ }
297
+ }
298
+ return {
299
+ type: 'heading',
300
+ raw: cap[0],
301
+ depth: cap[1].length,
302
+ text,
303
+ tokens: this.lexer.inline(text),
304
+ };
305
+ }
306
+ }
307
+ hr(src) {
308
+ const cap = this.rules.block.hr.exec(src);
309
+ if (cap) {
310
+ return {
311
+ type: 'hr',
312
+ raw: rtrim(cap[0], '\n'),
313
+ };
314
+ }
315
+ }
316
+ blockquote(src) {
317
+ const cap = this.rules.block.blockquote.exec(src);
318
+ if (cap) {
319
+ let lines = rtrim(cap[0], '\n').split('\n');
320
+ let raw = '';
321
+ let text = '';
322
+ const tokens = [];
323
+ while (lines.length > 0) {
324
+ let inBlockquote = false;
325
+ const currentLines = [];
326
+ let i;
327
+ for (i = 0; i < lines.length; i++) {
328
+ // get lines up to a continuation
329
+ if (/^ {0,3}>/.test(lines[i])) {
330
+ currentLines.push(lines[i]);
331
+ inBlockquote = true;
332
+ }
333
+ else if (!inBlockquote) {
334
+ currentLines.push(lines[i]);
335
+ }
336
+ else {
337
+ break;
338
+ }
339
+ }
340
+ lines = lines.slice(i);
341
+ const currentRaw = currentLines.join('\n');
342
+ const currentText = currentRaw
343
+ // precede setext continuation with 4 spaces so it isn't a setext
344
+ .replace(/\n {0,3}((?:=+|-+) *)(?=\n|$)/g, '\n $1')
345
+ .replace(/^ {0,3}>[ \t]?/gm, '');
346
+ raw = raw ? `${raw}\n${currentRaw}` : currentRaw;
347
+ text = text ? `${text}\n${currentText}` : currentText;
348
+ // parse blockquote lines as top level tokens
349
+ // merge paragraphs if this is a continuation
350
+ const top = this.lexer.state.top;
351
+ this.lexer.state.top = true;
352
+ this.lexer.blockTokens(currentText, tokens, true);
353
+ this.lexer.state.top = top;
354
+ // if there is no continuation then we are done
355
+ if (lines.length === 0) {
356
+ break;
357
+ }
358
+ const lastToken = tokens[tokens.length - 1];
359
+ if (lastToken?.type === 'code') {
360
+ // blockquote continuation cannot be preceded by a code block
361
+ break;
362
+ }
363
+ else if (lastToken?.type === 'blockquote') {
364
+ // include continuation in nested blockquote
365
+ const oldToken = lastToken;
366
+ const newText = oldToken.raw + '\n' + lines.join('\n');
367
+ const newToken = this.blockquote(newText);
368
+ tokens[tokens.length - 1] = newToken;
369
+ raw = raw.substring(0, raw.length - oldToken.raw.length) + newToken.raw;
370
+ text = text.substring(0, text.length - oldToken.text.length) + newToken.text;
371
+ break;
372
+ }
373
+ else if (lastToken?.type === 'list') {
374
+ // include continuation in nested list
375
+ const oldToken = lastToken;
376
+ const newText = oldToken.raw + '\n' + lines.join('\n');
377
+ const newToken = this.list(newText);
378
+ tokens[tokens.length - 1] = newToken;
379
+ raw = raw.substring(0, raw.length - lastToken.raw.length) + newToken.raw;
380
+ text = text.substring(0, text.length - oldToken.raw.length) + newToken.raw;
381
+ lines = newText.substring(tokens[tokens.length - 1].raw.length).split('\n');
382
+ continue;
383
+ }
384
+ }
385
+ return {
386
+ type: 'blockquote',
387
+ raw,
388
+ tokens,
389
+ text,
390
+ };
391
+ }
392
+ }
393
+ list(src) {
394
+ let cap = this.rules.block.list.exec(src);
395
+ if (cap) {
396
+ let bull = cap[1].trim();
397
+ const isordered = bull.length > 1;
398
+ const list = {
399
+ type: 'list',
400
+ raw: '',
401
+ ordered: isordered,
402
+ start: isordered ? +bull.slice(0, -1) : '',
403
+ loose: false,
404
+ items: [],
405
+ };
406
+ bull = isordered ? `\\d{1,9}\\${bull.slice(-1)}` : `\\${bull}`;
407
+ if (this.options.pedantic) {
408
+ bull = isordered ? bull : '[*+-]';
409
+ }
410
+ // Get next list item
411
+ const itemRegex = new RegExp(`^( {0,3}${bull})((?:[\t ][^\\n]*)?(?:\\n|$))`);
412
+ let endsWithBlankLine = false;
413
+ // Check if current bullet point can start a new List Item
414
+ while (src) {
415
+ let endEarly = false;
416
+ let raw = '';
417
+ let itemContents = '';
418
+ if (!(cap = itemRegex.exec(src))) {
419
+ break;
420
+ }
421
+ if (this.rules.block.hr.test(src)) { // End list if bullet was actually HR (possibly move into itemRegex?)
422
+ break;
423
+ }
424
+ raw = cap[0];
425
+ src = src.substring(raw.length);
426
+ let line = cap[2].split('\n', 1)[0].replace(/^\t+/, (t) => ' '.repeat(3 * t.length));
427
+ let nextLine = src.split('\n', 1)[0];
428
+ let blankLine = !line.trim();
429
+ let indent = 0;
430
+ if (this.options.pedantic) {
431
+ indent = 2;
432
+ itemContents = line.trimStart();
433
+ }
434
+ else if (blankLine) {
435
+ indent = cap[1].length + 1;
436
+ }
437
+ else {
438
+ indent = cap[2].search(/[^ ]/); // Find first non-space char
439
+ indent = indent > 4 ? 1 : indent; // Treat indented code blocks (> 4 spaces) as having only 1 indent
440
+ itemContents = line.slice(indent);
441
+ indent += cap[1].length;
442
+ }
443
+ if (blankLine && /^[ \t]*$/.test(nextLine)) { // Items begin with at most one blank line
444
+ raw += nextLine + '\n';
445
+ src = src.substring(nextLine.length + 1);
446
+ endEarly = true;
447
+ }
448
+ if (!endEarly) {
449
+ const nextBulletRegex = new RegExp(`^ {0,${Math.min(3, indent - 1)}}(?:[*+-]|\\d{1,9}[.)])((?:[ \t][^\\n]*)?(?:\\n|$))`);
450
+ const hrRegex = new RegExp(`^ {0,${Math.min(3, indent - 1)}}((?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})(?:\\n+|$)`);
451
+ const fencesBeginRegex = new RegExp(`^ {0,${Math.min(3, indent - 1)}}(?:\`\`\`|~~~)`);
452
+ const headingBeginRegex = new RegExp(`^ {0,${Math.min(3, indent - 1)}}#`);
453
+ const htmlBeginRegex = new RegExp(`^ {0,${Math.min(3, indent - 1)}}<(?:[a-z].*>|!--)`, 'i');
454
+ // Check if following lines should be included in List Item
455
+ while (src) {
456
+ const rawLine = src.split('\n', 1)[0];
457
+ let nextLineWithoutTabs;
458
+ nextLine = rawLine;
459
+ // Re-align to follow commonmark nesting rules
460
+ if (this.options.pedantic) {
461
+ nextLine = nextLine.replace(/^ {1,4}(?=( {4})*[^ ])/g, ' ');
462
+ nextLineWithoutTabs = nextLine;
463
+ }
464
+ else {
465
+ nextLineWithoutTabs = nextLine.replace(/\t/g, ' ');
466
+ }
467
+ // End list item if found code fences
468
+ if (fencesBeginRegex.test(nextLine)) {
469
+ break;
470
+ }
471
+ // End list item if found start of new heading
472
+ if (headingBeginRegex.test(nextLine)) {
473
+ break;
474
+ }
475
+ // End list item if found start of html block
476
+ if (htmlBeginRegex.test(nextLine)) {
477
+ break;
478
+ }
479
+ // End list item if found start of new bullet
480
+ if (nextBulletRegex.test(nextLine)) {
481
+ break;
482
+ }
483
+ // Horizontal rule found
484
+ if (hrRegex.test(nextLine)) {
485
+ break;
486
+ }
487
+ if (nextLineWithoutTabs.search(/[^ ]/) >= indent || !nextLine.trim()) { // Dedent if possible
488
+ itemContents += '\n' + nextLineWithoutTabs.slice(indent);
489
+ }
490
+ else {
491
+ // not enough indentation
492
+ if (blankLine) {
493
+ break;
494
+ }
495
+ // paragraph continuation unless last line was a different block level element
496
+ if (line.replace(/\t/g, ' ').search(/[^ ]/) >= 4) { // indented code block
497
+ break;
498
+ }
499
+ if (fencesBeginRegex.test(line)) {
500
+ break;
501
+ }
502
+ if (headingBeginRegex.test(line)) {
503
+ break;
504
+ }
505
+ if (hrRegex.test(line)) {
506
+ break;
507
+ }
508
+ itemContents += '\n' + nextLine;
509
+ }
510
+ if (!blankLine && !nextLine.trim()) { // Check if current line is blank
511
+ blankLine = true;
512
+ }
513
+ raw += rawLine + '\n';
514
+ src = src.substring(rawLine.length + 1);
515
+ line = nextLineWithoutTabs.slice(indent);
516
+ }
517
+ }
518
+ if (!list.loose) {
519
+ // If the previous item ended with a blank line, the list is loose
520
+ if (endsWithBlankLine) {
521
+ list.loose = true;
522
+ }
523
+ else if (/\n[ \t]*\n[ \t]*$/.test(raw)) {
524
+ endsWithBlankLine = true;
525
+ }
526
+ }
527
+ let istask = null;
528
+ let ischecked;
529
+ // Check for task list items
530
+ if (this.options.gfm) {
531
+ istask = /^\[[ xX]\] /.exec(itemContents);
532
+ if (istask) {
533
+ ischecked = istask[0] !== '[ ] ';
534
+ itemContents = itemContents.replace(/^\[[ xX]\] +/, '');
535
+ }
536
+ }
537
+ list.items.push({
538
+ type: 'list_item',
539
+ raw,
540
+ task: !!istask,
541
+ checked: ischecked,
542
+ loose: false,
543
+ text: itemContents,
544
+ tokens: [],
545
+ });
546
+ list.raw += raw;
547
+ }
548
+ // Do not consume newlines at end of final item. Alternatively, make itemRegex *start* with any newlines to simplify/speed up endsWithBlankLine logic
549
+ list.items[list.items.length - 1].raw = list.items[list.items.length - 1].raw.trimEnd();
550
+ list.items[list.items.length - 1].text = list.items[list.items.length - 1].text.trimEnd();
551
+ list.raw = list.raw.trimEnd();
552
+ // Item child tokens handled here at end because we needed to have the final item to trim it first
553
+ for (let i = 0; i < list.items.length; i++) {
554
+ this.lexer.state.top = false;
555
+ list.items[i].tokens = this.lexer.blockTokens(list.items[i].text, []);
556
+ if (!list.loose) {
557
+ // Check if list should be loose
558
+ const spacers = list.items[i].tokens.filter(t => t.type === 'space');
559
+ const hasMultipleLineBreaks = spacers.length > 0 && spacers.some(t => /\n.*\n/.test(t.raw));
560
+ list.loose = hasMultipleLineBreaks;
561
+ }
562
+ }
563
+ // Set all items to loose if list is loose
564
+ if (list.loose) {
565
+ for (let i = 0; i < list.items.length; i++) {
566
+ list.items[i].loose = true;
567
+ }
568
+ }
569
+ return list;
570
+ }
571
+ }
572
+ html(src) {
573
+ const cap = this.rules.block.html.exec(src);
574
+ if (cap) {
575
+ const token = {
576
+ type: 'html',
577
+ block: true,
578
+ raw: cap[0],
579
+ pre: cap[1] === 'pre' || cap[1] === 'script' || cap[1] === 'style',
580
+ text: cap[0],
581
+ };
582
+ return token;
583
+ }
584
+ }
585
+ def(src) {
586
+ const cap = this.rules.block.def.exec(src);
587
+ if (cap) {
588
+ const tag = cap[1].toLowerCase().replace(/\s+/g, ' ');
589
+ const href = cap[2] ? cap[2].replace(/^<(.*)>$/, '$1').replace(this.rules.inline.anyPunctuation, '$1') : '';
590
+ const title = cap[3] ? cap[3].substring(1, cap[3].length - 1).replace(this.rules.inline.anyPunctuation, '$1') : cap[3];
591
+ return {
592
+ type: 'def',
593
+ tag,
594
+ raw: cap[0],
595
+ href,
596
+ title,
597
+ };
598
+ }
599
+ }
600
+ table(src) {
601
+ const cap = this.rules.block.table.exec(src);
602
+ if (!cap) {
603
+ return;
604
+ }
605
+ if (!/[:|]/.test(cap[2])) {
606
+ // delimiter row must have a pipe (|) or colon (:) otherwise it is a setext heading
607
+ return;
608
+ }
609
+ const headers = splitCells(cap[1]);
610
+ const aligns = cap[2].replace(/^\||\| *$/g, '').split('|');
611
+ const rows = cap[3] && cap[3].trim() ? cap[3].replace(/\n[ \t]*$/, '').split('\n') : [];
612
+ const item = {
613
+ type: 'table',
614
+ raw: cap[0],
615
+ header: [],
616
+ align: [],
617
+ rows: [],
618
+ };
619
+ if (headers.length !== aligns.length) {
620
+ // header and align columns must be equal, rows can be different.
621
+ return;
622
+ }
623
+ for (const align of aligns) {
624
+ if (/^ *-+: *$/.test(align)) {
625
+ item.align.push('right');
626
+ }
627
+ else if (/^ *:-+: *$/.test(align)) {
628
+ item.align.push('center');
629
+ }
630
+ else if (/^ *:-+ *$/.test(align)) {
631
+ item.align.push('left');
632
+ }
633
+ else {
634
+ item.align.push(null);
635
+ }
636
+ }
637
+ for (let i = 0; i < headers.length; i++) {
638
+ item.header.push({
639
+ text: headers[i],
640
+ tokens: this.lexer.inline(headers[i]),
641
+ header: true,
642
+ align: item.align[i],
643
+ });
644
+ }
645
+ for (const row of rows) {
646
+ item.rows.push(splitCells(row, item.header.length).map((cell, i) => {
647
+ return {
648
+ text: cell,
649
+ tokens: this.lexer.inline(cell),
650
+ header: false,
651
+ align: item.align[i],
652
+ };
653
+ }));
654
+ }
655
+ return item;
656
+ }
657
+ lheading(src) {
658
+ const cap = this.rules.block.lheading.exec(src);
659
+ if (cap) {
660
+ return {
661
+ type: 'heading',
662
+ raw: cap[0],
663
+ depth: cap[2].charAt(0) === '=' ? 1 : 2,
664
+ text: cap[1],
665
+ tokens: this.lexer.inline(cap[1]),
666
+ };
667
+ }
668
+ }
669
+ paragraph(src) {
670
+ const cap = this.rules.block.paragraph.exec(src);
671
+ if (cap) {
672
+ const text = cap[1].charAt(cap[1].length - 1) === '\n'
673
+ ? cap[1].slice(0, -1)
674
+ : cap[1];
675
+ return {
676
+ type: 'paragraph',
677
+ raw: cap[0],
678
+ text,
679
+ tokens: this.lexer.inline(text),
680
+ };
681
+ }
682
+ }
683
+ text(src) {
684
+ const cap = this.rules.block.text.exec(src);
685
+ if (cap) {
686
+ return {
687
+ type: 'text',
688
+ raw: cap[0],
689
+ text: cap[0],
690
+ tokens: this.lexer.inline(cap[0]),
691
+ };
692
+ }
693
+ }
694
+ escape(src) {
695
+ const cap = this.rules.inline.escape.exec(src);
696
+ if (cap) {
697
+ return {
698
+ type: 'escape',
699
+ raw: cap[0],
700
+ text: escape$1(cap[1]),
701
+ };
702
+ }
703
+ }
704
+ tag(src) {
705
+ const cap = this.rules.inline.tag.exec(src);
706
+ if (cap) {
707
+ if (!this.lexer.state.inLink && /^<a /i.test(cap[0])) {
708
+ this.lexer.state.inLink = true;
709
+ }
710
+ else if (this.lexer.state.inLink && /^<\/a>/i.test(cap[0])) {
711
+ this.lexer.state.inLink = false;
712
+ }
713
+ if (!this.lexer.state.inRawBlock && /^<(pre|code|kbd|script)(\s|>)/i.test(cap[0])) {
714
+ this.lexer.state.inRawBlock = true;
715
+ }
716
+ else if (this.lexer.state.inRawBlock && /^<\/(pre|code|kbd|script)(\s|>)/i.test(cap[0])) {
717
+ this.lexer.state.inRawBlock = false;
718
+ }
719
+ return {
720
+ type: 'html',
721
+ raw: cap[0],
722
+ inLink: this.lexer.state.inLink,
723
+ inRawBlock: this.lexer.state.inRawBlock,
724
+ block: false,
725
+ text: cap[0],
726
+ };
727
+ }
728
+ }
729
+ link(src) {
730
+ const cap = this.rules.inline.link.exec(src);
731
+ if (cap) {
732
+ const trimmedUrl = cap[2].trim();
733
+ if (!this.options.pedantic && /^</.test(trimmedUrl)) {
734
+ // commonmark requires matching angle brackets
735
+ if (!(/>$/.test(trimmedUrl))) {
736
+ return;
737
+ }
738
+ // ending angle bracket cannot be escaped
739
+ const rtrimSlash = rtrim(trimmedUrl.slice(0, -1), '\\');
740
+ if ((trimmedUrl.length - rtrimSlash.length) % 2 === 0) {
741
+ return;
742
+ }
743
+ }
744
+ else {
745
+ // find closing parenthesis
746
+ const lastParenIndex = findClosingBracket(cap[2], '()');
747
+ if (lastParenIndex > -1) {
748
+ const start = cap[0].indexOf('!') === 0 ? 5 : 4;
749
+ const linkLen = start + cap[1].length + lastParenIndex;
750
+ cap[2] = cap[2].substring(0, lastParenIndex);
751
+ cap[0] = cap[0].substring(0, linkLen).trim();
752
+ cap[3] = '';
753
+ }
754
+ }
755
+ let href = cap[2];
756
+ let title = '';
757
+ if (this.options.pedantic) {
758
+ // split pedantic href and title
759
+ const link = /^([^'"]*[^\s])\s+(['"])(.*)\2/.exec(href);
760
+ if (link) {
761
+ href = link[1];
762
+ title = link[3];
763
+ }
764
+ }
765
+ else {
766
+ title = cap[3] ? cap[3].slice(1, -1) : '';
767
+ }
768
+ href = href.trim();
769
+ if (/^</.test(href)) {
770
+ if (this.options.pedantic && !(/>$/.test(trimmedUrl))) {
771
+ // pedantic allows starting angle bracket without ending angle bracket
772
+ href = href.slice(1);
773
+ }
774
+ else {
775
+ href = href.slice(1, -1);
776
+ }
777
+ }
778
+ return outputLink(cap, {
779
+ href: href ? href.replace(this.rules.inline.anyPunctuation, '$1') : href,
780
+ title: title ? title.replace(this.rules.inline.anyPunctuation, '$1') : title,
781
+ }, cap[0], this.lexer);
782
+ }
783
+ }
784
+ reflink(src, links) {
785
+ let cap;
786
+ if ((cap = this.rules.inline.reflink.exec(src))
787
+ || (cap = this.rules.inline.nolink.exec(src))) {
788
+ const linkString = (cap[2] || cap[1]).replace(/\s+/g, ' ');
789
+ const link = links[linkString.toLowerCase()];
790
+ if (!link) {
791
+ const text = cap[0].charAt(0);
792
+ return {
793
+ type: 'text',
794
+ raw: text,
795
+ text,
796
+ };
797
+ }
798
+ return outputLink(cap, link, cap[0], this.lexer);
799
+ }
800
+ }
801
+ emStrong(src, maskedSrc, prevChar = '') {
802
+ let match = this.rules.inline.emStrongLDelim.exec(src);
803
+ if (!match)
804
+ return;
805
+ // _ can't be between two alphanumerics. \p{L}\p{N} includes non-english alphabet/numbers as well
806
+ if (match[3] && prevChar.match(/[\p{L}\p{N}]/u))
807
+ return;
808
+ const nextChar = match[1] || match[2] || '';
809
+ if (!nextChar || !prevChar || this.rules.inline.punctuation.exec(prevChar)) {
810
+ // unicode Regex counts emoji as 1 char; spread into array for proper count (used multiple times below)
811
+ const lLength = [...match[0]].length - 1;
812
+ let rDelim, rLength, delimTotal = lLength, midDelimTotal = 0;
813
+ const endReg = match[0][0] === '*' ? this.rules.inline.emStrongRDelimAst : this.rules.inline.emStrongRDelimUnd;
814
+ endReg.lastIndex = 0;
815
+ // Clip maskedSrc to same section of string as src (move to lexer?)
816
+ maskedSrc = maskedSrc.slice(-1 * src.length + lLength);
817
+ while ((match = endReg.exec(maskedSrc)) != null) {
818
+ rDelim = match[1] || match[2] || match[3] || match[4] || match[5] || match[6];
819
+ if (!rDelim)
820
+ continue; // skip single * in __abc*abc__
821
+ rLength = [...rDelim].length;
822
+ if (match[3] || match[4]) { // found another Left Delim
823
+ delimTotal += rLength;
824
+ continue;
825
+ }
826
+ else if (match[5] || match[6]) { // either Left or Right Delim
827
+ if (lLength % 3 && !((lLength + rLength) % 3)) {
828
+ midDelimTotal += rLength;
829
+ continue; // CommonMark Emphasis Rules 9-10
830
+ }
831
+ }
832
+ delimTotal -= rLength;
833
+ if (delimTotal > 0)
834
+ continue; // Haven't found enough closing delimiters
835
+ // Remove extra characters. *a*** -> *a*
836
+ rLength = Math.min(rLength, rLength + delimTotal + midDelimTotal);
837
+ // char length can be >1 for unicode characters;
838
+ const lastCharLength = [...match[0]][0].length;
839
+ const raw = src.slice(0, lLength + match.index + lastCharLength + rLength);
840
+ // Create `em` if smallest delimiter has odd char count. *a***
841
+ if (Math.min(lLength, rLength) % 2) {
842
+ const text = raw.slice(1, -1);
843
+ return {
844
+ type: 'em',
845
+ raw,
846
+ text,
847
+ tokens: this.lexer.inlineTokens(text),
848
+ };
849
+ }
850
+ // Create 'strong' if smallest delimiter has even char count. **a***
851
+ const text = raw.slice(2, -2);
852
+ return {
853
+ type: 'strong',
854
+ raw,
855
+ text,
856
+ tokens: this.lexer.inlineTokens(text),
857
+ };
858
+ }
859
+ }
860
+ }
861
+ codespan(src) {
862
+ const cap = this.rules.inline.code.exec(src);
863
+ if (cap) {
864
+ let text = cap[2].replace(/\n/g, ' ');
865
+ const hasNonSpaceChars = /[^ ]/.test(text);
866
+ const hasSpaceCharsOnBothEnds = /^ /.test(text) && / $/.test(text);
867
+ if (hasNonSpaceChars && hasSpaceCharsOnBothEnds) {
868
+ text = text.substring(1, text.length - 1);
869
+ }
870
+ text = escape$1(text, true);
871
+ return {
872
+ type: 'codespan',
873
+ raw: cap[0],
874
+ text,
875
+ };
876
+ }
877
+ }
878
+ br(src) {
879
+ const cap = this.rules.inline.br.exec(src);
880
+ if (cap) {
881
+ return {
882
+ type: 'br',
883
+ raw: cap[0],
884
+ };
885
+ }
886
+ }
887
+ del(src) {
888
+ const cap = this.rules.inline.del.exec(src);
889
+ if (cap) {
890
+ return {
891
+ type: 'del',
892
+ raw: cap[0],
893
+ text: cap[2],
894
+ tokens: this.lexer.inlineTokens(cap[2]),
895
+ };
896
+ }
897
+ }
898
+ autolink(src) {
899
+ const cap = this.rules.inline.autolink.exec(src);
900
+ if (cap) {
901
+ let text, href;
902
+ if (cap[2] === '@') {
903
+ text = escape$1(cap[1]);
904
+ href = 'mailto:' + text;
905
+ }
906
+ else {
907
+ text = escape$1(cap[1]);
908
+ href = text;
909
+ }
910
+ return {
911
+ type: 'link',
912
+ raw: cap[0],
913
+ text,
914
+ href,
915
+ tokens: [
916
+ {
917
+ type: 'text',
918
+ raw: text,
919
+ text,
920
+ },
921
+ ],
922
+ };
923
+ }
924
+ }
925
+ url(src) {
926
+ let cap;
927
+ if (cap = this.rules.inline.url.exec(src)) {
928
+ let text, href;
929
+ if (cap[2] === '@') {
930
+ text = escape$1(cap[0]);
931
+ href = 'mailto:' + text;
932
+ }
933
+ else {
934
+ // do extended autolink path validation
935
+ let prevCapZero;
936
+ do {
937
+ prevCapZero = cap[0];
938
+ cap[0] = this.rules.inline._backpedal.exec(cap[0])?.[0] ?? '';
939
+ } while (prevCapZero !== cap[0]);
940
+ text = escape$1(cap[0]);
941
+ if (cap[1] === 'www.') {
942
+ href = 'http://' + cap[0];
943
+ }
944
+ else {
945
+ href = cap[0];
946
+ }
947
+ }
948
+ return {
949
+ type: 'link',
950
+ raw: cap[0],
951
+ text,
952
+ href,
953
+ tokens: [
954
+ {
955
+ type: 'text',
956
+ raw: text,
957
+ text,
958
+ },
959
+ ],
960
+ };
961
+ }
962
+ }
963
+ inlineText(src) {
964
+ const cap = this.rules.inline.text.exec(src);
965
+ if (cap) {
966
+ let text;
967
+ if (this.lexer.state.inRawBlock) {
968
+ text = cap[0];
969
+ }
970
+ else {
971
+ text = escape$1(cap[0]);
972
+ }
973
+ return {
974
+ type: 'text',
975
+ raw: cap[0],
976
+ text,
977
+ };
978
+ }
979
+ }
980
+ }
981
+
982
+ /**
983
+ * Block-Level Grammar
984
+ */
985
+ const newline = /^(?:[ \t]*(?:\n|$))+/;
986
+ const blockCode = /^((?: {4}| {0,3}\t)[^\n]+(?:\n(?:[ \t]*(?:\n|$))*)?)+/;
987
+ const fences = /^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/;
988
+ const hr = /^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/;
989
+ const heading = /^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/;
990
+ const bullet = /(?:[*+-]|\d{1,9}[.)])/;
991
+ const lheading = edit(/^(?!bull |blockCode|fences|blockquote|heading|html)((?:.|\n(?!\s*?\n|bull |blockCode|fences|blockquote|heading|html))+?)\n {0,3}(=+|-+) *(?:\n+|$)/)
992
+ .replace(/bull/g, bullet) // lists can interrupt
993
+ .replace(/blockCode/g, /(?: {4}| {0,3}\t)/) // indented code blocks can interrupt
994
+ .replace(/fences/g, / {0,3}(?:`{3,}|~{3,})/) // fenced code blocks can interrupt
995
+ .replace(/blockquote/g, / {0,3}>/) // blockquote can interrupt
996
+ .replace(/heading/g, / {0,3}#{1,6}/) // ATX heading can interrupt
997
+ .replace(/html/g, / {0,3}<[^\n>]+>\n/) // block html can interrupt
998
+ .getRegex();
999
+ const _paragraph = /^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table| +\n)[^\n]+)*)/;
1000
+ const blockText = /^[^\n]+/;
1001
+ const _blockLabel = /(?!\s*\])(?:\\.|[^\[\]\\])+/;
1002
+ const def = edit(/^ {0,3}\[(label)\]: *(?:\n[ \t]*)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n[ \t]*)?| *\n[ \t]*)(title))? *(?:\n+|$)/)
1003
+ .replace('label', _blockLabel)
1004
+ .replace('title', /(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/)
1005
+ .getRegex();
1006
+ const list = edit(/^( {0,3}bull)([ \t][^\n]+?)?(?:\n|$)/)
1007
+ .replace(/bull/g, bullet)
1008
+ .getRegex();
1009
+ const _tag = 'address|article|aside|base|basefont|blockquote|body|caption'
1010
+ + '|center|col|colgroup|dd|details|dialog|dir|div|dl|dt|fieldset|figcaption'
1011
+ + '|figure|footer|form|frame|frameset|h[1-6]|head|header|hr|html|iframe'
1012
+ + '|legend|li|link|main|menu|menuitem|meta|nav|noframes|ol|optgroup|option'
1013
+ + '|p|param|search|section|summary|table|tbody|td|tfoot|th|thead|title'
1014
+ + '|tr|track|ul';
1015
+ const _comment = /<!--(?:-?>|[\s\S]*?(?:-->|$))/;
1016
+ const html = edit('^ {0,3}(?:' // optional indentation
1017
+ + '<(script|pre|style|textarea)[\\s>][\\s\\S]*?(?:</\\1>[^\\n]*\\n+|$)' // (1)
1018
+ + '|comment[^\\n]*(\\n+|$)' // (2)
1019
+ + '|<\\?[\\s\\S]*?(?:\\?>\\n*|$)' // (3)
1020
+ + '|<![A-Z][\\s\\S]*?(?:>\\n*|$)' // (4)
1021
+ + '|<!\\[CDATA\\[[\\s\\S]*?(?:\\]\\]>\\n*|$)' // (5)
1022
+ + '|</?(tag)(?: +|\\n|/?>)[\\s\\S]*?(?:(?:\\n[ \t]*)+\\n|$)' // (6)
1023
+ + '|<(?!script|pre|style|textarea)([a-z][\\w-]*)(?:attribute)*? */?>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ \t]*)+\\n|$)' // (7) open tag
1024
+ + '|</(?!script|pre|style|textarea)[a-z][\\w-]*\\s*>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ \t]*)+\\n|$)' // (7) closing tag
1025
+ + ')', 'i')
1026
+ .replace('comment', _comment)
1027
+ .replace('tag', _tag)
1028
+ .replace('attribute', / +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/)
1029
+ .getRegex();
1030
+ const paragraph = edit(_paragraph)
1031
+ .replace('hr', hr)
1032
+ .replace('heading', ' {0,3}#{1,6}(?:\\s|$)')
1033
+ .replace('|lheading', '') // setext headings don't interrupt commonmark paragraphs
1034
+ .replace('|table', '')
1035
+ .replace('blockquote', ' {0,3}>')
1036
+ .replace('fences', ' {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n')
1037
+ .replace('list', ' {0,3}(?:[*+-]|1[.)]) ') // only lists starting from 1 can interrupt
1038
+ .replace('html', '</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)')
1039
+ .replace('tag', _tag) // pars can be interrupted by type (6) html blocks
1040
+ .getRegex();
1041
+ const blockquote = edit(/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/)
1042
+ .replace('paragraph', paragraph)
1043
+ .getRegex();
1044
+ /**
1045
+ * Normal Block Grammar
1046
+ */
1047
+ const blockNormal = {
1048
+ blockquote,
1049
+ code: blockCode,
1050
+ def,
1051
+ fences,
1052
+ heading,
1053
+ hr,
1054
+ html,
1055
+ lheading,
1056
+ list,
1057
+ newline,
1058
+ paragraph,
1059
+ table: noopTest,
1060
+ text: blockText,
1061
+ };
1062
+ /**
1063
+ * GFM Block Grammar
1064
+ */
1065
+ const gfmTable = edit('^ *([^\\n ].*)\\n' // Header
1066
+ + ' {0,3}((?:\\| *)?:?-+:? *(?:\\| *:?-+:? *)*(?:\\| *)?)' // Align
1067
+ + '(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)') // Cells
1068
+ .replace('hr', hr)
1069
+ .replace('heading', ' {0,3}#{1,6}(?:\\s|$)')
1070
+ .replace('blockquote', ' {0,3}>')
1071
+ .replace('code', '(?: {4}| {0,3}\t)[^\\n]')
1072
+ .replace('fences', ' {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n')
1073
+ .replace('list', ' {0,3}(?:[*+-]|1[.)]) ') // only lists starting from 1 can interrupt
1074
+ .replace('html', '</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)')
1075
+ .replace('tag', _tag) // tables can be interrupted by type (6) html blocks
1076
+ .getRegex();
1077
+ const blockGfm = {
1078
+ ...blockNormal,
1079
+ table: gfmTable,
1080
+ paragraph: edit(_paragraph)
1081
+ .replace('hr', hr)
1082
+ .replace('heading', ' {0,3}#{1,6}(?:\\s|$)')
1083
+ .replace('|lheading', '') // setext headings don't interrupt commonmark paragraphs
1084
+ .replace('table', gfmTable) // interrupt paragraphs with table
1085
+ .replace('blockquote', ' {0,3}>')
1086
+ .replace('fences', ' {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n')
1087
+ .replace('list', ' {0,3}(?:[*+-]|1[.)]) ') // only lists starting from 1 can interrupt
1088
+ .replace('html', '</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)')
1089
+ .replace('tag', _tag) // pars can be interrupted by type (6) html blocks
1090
+ .getRegex(),
1091
+ };
1092
+ /**
1093
+ * Pedantic grammar (original John Gruber's loose markdown specification)
1094
+ */
1095
+ const blockPedantic = {
1096
+ ...blockNormal,
1097
+ html: edit('^ *(?:comment *(?:\\n|\\s*$)'
1098
+ + '|<(tag)[\\s\\S]+?</\\1> *(?:\\n{2,}|\\s*$)' // closed tag
1099
+ + '|<tag(?:"[^"]*"|\'[^\']*\'|\\s[^\'"/>\\s]*)*?/?> *(?:\\n{2,}|\\s*$))')
1100
+ .replace('comment', _comment)
1101
+ .replace(/tag/g, '(?!(?:'
1102
+ + 'a|em|strong|small|s|cite|q|dfn|abbr|data|time|code|var|samp|kbd|sub'
1103
+ + '|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo|span|br|wbr|ins|del|img)'
1104
+ + '\\b)\\w+(?!:|[^\\w\\s@]*@)\\b')
1105
+ .getRegex(),
1106
+ def: /^ *\[([^\]]+)\]: *<?([^\s>]+)>?(?: +(["(][^\n]+[")]))? *(?:\n+|$)/,
1107
+ heading: /^(#{1,6})(.*)(?:\n+|$)/,
1108
+ fences: noopTest, // fences not supported
1109
+ lheading: /^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/,
1110
+ paragraph: edit(_paragraph)
1111
+ .replace('hr', hr)
1112
+ .replace('heading', ' *#{1,6} *[^\n]')
1113
+ .replace('lheading', lheading)
1114
+ .replace('|table', '')
1115
+ .replace('blockquote', ' {0,3}>')
1116
+ .replace('|fences', '')
1117
+ .replace('|list', '')
1118
+ .replace('|html', '')
1119
+ .replace('|tag', '')
1120
+ .getRegex(),
1121
+ };
1122
+ /**
1123
+ * Inline-Level Grammar
1124
+ */
1125
+ const escape = /^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/;
1126
+ const inlineCode = /^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/;
1127
+ const br = /^( {2,}|\\)\n(?!\s*$)/;
1128
+ const inlineText = /^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\<!\[`*_]|\b_|$)|[^ ](?= {2,}\n)))/;
1129
+ // list of unicode punctuation marks, plus any missing characters from CommonMark spec
1130
+ const _punctuation = '\\p{P}\\p{S}';
1131
+ const punctuation = edit(/^((?![*_])[\spunctuation])/, 'u')
1132
+ .replace(/punctuation/g, _punctuation).getRegex();
1133
+ // sequences em should skip over [title](link), `code`, <html>
1134
+ const blockSkip = /\[[^[\]]*?\]\((?:\\.|[^\\\(\)]|\((?:\\.|[^\\\(\)])*\))*\)|`[^`]*?`|<[^<>]*?>/g;
1135
+ const emStrongLDelim = edit(/^(?:\*+(?:((?!\*)[punct])|[^\s*]))|^_+(?:((?!_)[punct])|([^\s_]))/, 'u')
1136
+ .replace(/punct/g, _punctuation)
1137
+ .getRegex();
1138
+ const emStrongRDelimAst = edit('^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)' // Skip orphan inside strong
1139
+ + '|[^*]+(?=[^*])' // Consume to delim
1140
+ + '|(?!\\*)[punct](\\*+)(?=[\\s]|$)' // (1) #*** can only be a Right Delimiter
1141
+ + '|[^punct\\s](\\*+)(?!\\*)(?=[punct\\s]|$)' // (2) a***#, a*** can only be a Right Delimiter
1142
+ + '|(?!\\*)[punct\\s](\\*+)(?=[^punct\\s])' // (3) #***a, ***a can only be Left Delimiter
1143
+ + '|[\\s](\\*+)(?!\\*)(?=[punct])' // (4) ***# can only be Left Delimiter
1144
+ + '|(?!\\*)[punct](\\*+)(?!\\*)(?=[punct])' // (5) #***# can be either Left or Right Delimiter
1145
+ + '|[^punct\\s](\\*+)(?=[^punct\\s])', 'gu') // (6) a***a can be either Left or Right Delimiter
1146
+ .replace(/punct/g, _punctuation)
1147
+ .getRegex();
1148
+ // (6) Not allowed for _
1149
+ const emStrongRDelimUnd = edit('^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)' // Skip orphan inside strong
1150
+ + '|[^_]+(?=[^_])' // Consume to delim
1151
+ + '|(?!_)[punct](_+)(?=[\\s]|$)' // (1) #___ can only be a Right Delimiter
1152
+ + '|[^punct\\s](_+)(?!_)(?=[punct\\s]|$)' // (2) a___#, a___ can only be a Right Delimiter
1153
+ + '|(?!_)[punct\\s](_+)(?=[^punct\\s])' // (3) #___a, ___a can only be Left Delimiter
1154
+ + '|[\\s](_+)(?!_)(?=[punct])' // (4) ___# can only be Left Delimiter
1155
+ + '|(?!_)[punct](_+)(?!_)(?=[punct])', 'gu') // (5) #___# can be either Left or Right Delimiter
1156
+ .replace(/punct/g, _punctuation)
1157
+ .getRegex();
1158
+ const anyPunctuation = edit(/\\([punct])/, 'gu')
1159
+ .replace(/punct/g, _punctuation)
1160
+ .getRegex();
1161
+ const autolink = edit(/^<(scheme:[^\s\x00-\x1f<>]*|email)>/)
1162
+ .replace('scheme', /[a-zA-Z][a-zA-Z0-9+.-]{1,31}/)
1163
+ .replace('email', /[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+(@)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+(?![-_])/)
1164
+ .getRegex();
1165
+ const _inlineComment = edit(_comment).replace('(?:-->|$)', '-->').getRegex();
1166
+ const tag = edit('^comment'
1167
+ + '|^</[a-zA-Z][\\w:-]*\\s*>' // self-closing tag
1168
+ + '|^<[a-zA-Z][\\w-]*(?:attribute)*?\\s*/?>' // open tag
1169
+ + '|^<\\?[\\s\\S]*?\\?>' // processing instruction, e.g. <?php ?>
1170
+ + '|^<![a-zA-Z]+\\s[\\s\\S]*?>' // declaration, e.g. <!DOCTYPE html>
1171
+ + '|^<!\\[CDATA\\[[\\s\\S]*?\\]\\]>') // CDATA section
1172
+ .replace('comment', _inlineComment)
1173
+ .replace('attribute', /\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/)
1174
+ .getRegex();
1175
+ const _inlineLabel = /(?:\[(?:\\.|[^\[\]\\])*\]|\\.|`[^`]*`|[^\[\]\\`])*?/;
1176
+ const link = edit(/^!?\[(label)\]\(\s*(href)(?:\s+(title))?\s*\)/)
1177
+ .replace('label', _inlineLabel)
1178
+ .replace('href', /<(?:\\.|[^\n<>\\])+>|[^\s\x00-\x1f]*/)
1179
+ .replace('title', /"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/)
1180
+ .getRegex();
1181
+ const reflink = edit(/^!?\[(label)\]\[(ref)\]/)
1182
+ .replace('label', _inlineLabel)
1183
+ .replace('ref', _blockLabel)
1184
+ .getRegex();
1185
+ const nolink = edit(/^!?\[(ref)\](?:\[\])?/)
1186
+ .replace('ref', _blockLabel)
1187
+ .getRegex();
1188
+ const reflinkSearch = edit('reflink|nolink(?!\\()', 'g')
1189
+ .replace('reflink', reflink)
1190
+ .replace('nolink', nolink)
1191
+ .getRegex();
1192
+ /**
1193
+ * Normal Inline Grammar
1194
+ */
1195
+ const inlineNormal = {
1196
+ _backpedal: noopTest, // only used for GFM url
1197
+ anyPunctuation,
1198
+ autolink,
1199
+ blockSkip,
1200
+ br,
1201
+ code: inlineCode,
1202
+ del: noopTest,
1203
+ emStrongLDelim,
1204
+ emStrongRDelimAst,
1205
+ emStrongRDelimUnd,
1206
+ escape,
1207
+ link,
1208
+ nolink,
1209
+ punctuation,
1210
+ reflink,
1211
+ reflinkSearch,
1212
+ tag,
1213
+ text: inlineText,
1214
+ url: noopTest,
1215
+ };
1216
+ /**
1217
+ * Pedantic Inline Grammar
1218
+ */
1219
+ const inlinePedantic = {
1220
+ ...inlineNormal,
1221
+ link: edit(/^!?\[(label)\]\((.*?)\)/)
1222
+ .replace('label', _inlineLabel)
1223
+ .getRegex(),
1224
+ reflink: edit(/^!?\[(label)\]\s*\[([^\]]*)\]/)
1225
+ .replace('label', _inlineLabel)
1226
+ .getRegex(),
1227
+ };
1228
+ /**
1229
+ * GFM Inline Grammar
1230
+ */
1231
+ const inlineGfm = {
1232
+ ...inlineNormal,
1233
+ escape: edit(escape).replace('])', '~|])').getRegex(),
1234
+ url: edit(/^((?:ftp|https?):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/, 'i')
1235
+ .replace('email', /[A-Za-z0-9._+-]+(@)[a-zA-Z0-9-_]+(?:\.[a-zA-Z0-9-_]*[a-zA-Z0-9])+(?![-_])/)
1236
+ .getRegex(),
1237
+ _backpedal: /(?:[^?!.,:;*_'"~()&]+|\([^)]*\)|&(?![a-zA-Z0-9]+;$)|[?!.,:;*_'"~)]+(?!$))+/,
1238
+ del: /^(~~?)(?=[^\s~])((?:\\.|[^\\])*?(?:\\.|[^\s~\\]))\1(?=[^~]|$)/,
1239
+ text: /^([`~]+|[^`~])(?:(?= {2,}\n)|(?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)|[\s\S]*?(?:(?=[\\<!\[`*~_]|\b_|https?:\/\/|ftp:\/\/|www\.|$)|[^ ](?= {2,}\n)|[^a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-](?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)))/,
1240
+ };
1241
+ /**
1242
+ * GFM + Line Breaks Inline Grammar
1243
+ */
1244
+ const inlineBreaks = {
1245
+ ...inlineGfm,
1246
+ br: edit(br).replace('{2,}', '*').getRegex(),
1247
+ text: edit(inlineGfm.text)
1248
+ .replace('\\b_', '\\b_| {2,}\\n')
1249
+ .replace(/\{2,\}/g, '*')
1250
+ .getRegex(),
1251
+ };
1252
+ /**
1253
+ * exports
1254
+ */
1255
+ const block = {
1256
+ normal: blockNormal,
1257
+ gfm: blockGfm,
1258
+ pedantic: blockPedantic,
1259
+ };
1260
+ const inline = {
1261
+ normal: inlineNormal,
1262
+ gfm: inlineGfm,
1263
+ breaks: inlineBreaks,
1264
+ pedantic: inlinePedantic,
1265
+ };
1266
+
1267
+ /**
1268
+ * Block Lexer
1269
+ */
1270
+ class _Lexer {
1271
+ tokens;
1272
+ options;
1273
+ state;
1274
+ tokenizer;
1275
+ inlineQueue;
1276
+ constructor(options) {
1277
+ // TokenList cannot be created in one go
1278
+ this.tokens = [];
1279
+ this.tokens.links = Object.create(null);
1280
+ this.options = options || _defaults;
1281
+ this.options.tokenizer = this.options.tokenizer || new _Tokenizer();
1282
+ this.tokenizer = this.options.tokenizer;
1283
+ this.tokenizer.options = this.options;
1284
+ this.tokenizer.lexer = this;
1285
+ this.inlineQueue = [];
1286
+ this.state = {
1287
+ inLink: false,
1288
+ inRawBlock: false,
1289
+ top: true,
1290
+ };
1291
+ const rules = {
1292
+ block: block.normal,
1293
+ inline: inline.normal,
1294
+ };
1295
+ if (this.options.pedantic) {
1296
+ rules.block = block.pedantic;
1297
+ rules.inline = inline.pedantic;
1298
+ }
1299
+ else if (this.options.gfm) {
1300
+ rules.block = block.gfm;
1301
+ if (this.options.breaks) {
1302
+ rules.inline = inline.breaks;
1303
+ }
1304
+ else {
1305
+ rules.inline = inline.gfm;
1306
+ }
1307
+ }
1308
+ this.tokenizer.rules = rules;
1309
+ }
1310
+ /**
1311
+ * Expose Rules
1312
+ */
1313
+ static get rules() {
1314
+ return {
1315
+ block,
1316
+ inline,
1317
+ };
1318
+ }
1319
+ /**
1320
+ * Static Lex Method
1321
+ */
1322
+ static lex(src, options) {
1323
+ const lexer = new _Lexer(options);
1324
+ return lexer.lex(src);
1325
+ }
1326
+ /**
1327
+ * Static Lex Inline Method
1328
+ */
1329
+ static lexInline(src, options) {
1330
+ const lexer = new _Lexer(options);
1331
+ return lexer.inlineTokens(src);
1332
+ }
1333
+ /**
1334
+ * Preprocessing
1335
+ */
1336
+ lex(src) {
1337
+ src = src
1338
+ .replace(/\r\n|\r/g, '\n');
1339
+ this.blockTokens(src, this.tokens);
1340
+ for (let i = 0; i < this.inlineQueue.length; i++) {
1341
+ const next = this.inlineQueue[i];
1342
+ this.inlineTokens(next.src, next.tokens);
1343
+ }
1344
+ this.inlineQueue = [];
1345
+ return this.tokens;
1346
+ }
1347
+ blockTokens(src, tokens = [], lastParagraphClipped = false) {
1348
+ if (this.options.pedantic) {
1349
+ src = src.replace(/\t/g, ' ').replace(/^ +$/gm, '');
1350
+ }
1351
+ let token;
1352
+ let lastToken;
1353
+ let cutSrc;
1354
+ while (src) {
1355
+ if (this.options.extensions
1356
+ && this.options.extensions.block
1357
+ && this.options.extensions.block.some((extTokenizer) => {
1358
+ if (token = extTokenizer.call({ lexer: this }, src, tokens)) {
1359
+ src = src.substring(token.raw.length);
1360
+ tokens.push(token);
1361
+ return true;
1362
+ }
1363
+ return false;
1364
+ })) {
1365
+ continue;
1366
+ }
1367
+ // newline
1368
+ if (token = this.tokenizer.space(src)) {
1369
+ src = src.substring(token.raw.length);
1370
+ if (token.raw.length === 1 && tokens.length > 0) {
1371
+ // if there's a single \n as a spacer, it's terminating the last line,
1372
+ // so move it there so that we don't get unnecessary paragraph tags
1373
+ tokens[tokens.length - 1].raw += '\n';
1374
+ }
1375
+ else {
1376
+ tokens.push(token);
1377
+ }
1378
+ continue;
1379
+ }
1380
+ // code
1381
+ if (token = this.tokenizer.code(src)) {
1382
+ src = src.substring(token.raw.length);
1383
+ lastToken = tokens[tokens.length - 1];
1384
+ // An indented code block cannot interrupt a paragraph.
1385
+ if (lastToken && (lastToken.type === 'paragraph' || lastToken.type === 'text')) {
1386
+ lastToken.raw += '\n' + token.raw;
1387
+ lastToken.text += '\n' + token.text;
1388
+ this.inlineQueue[this.inlineQueue.length - 1].src = lastToken.text;
1389
+ }
1390
+ else {
1391
+ tokens.push(token);
1392
+ }
1393
+ continue;
1394
+ }
1395
+ // fences
1396
+ if (token = this.tokenizer.fences(src)) {
1397
+ src = src.substring(token.raw.length);
1398
+ tokens.push(token);
1399
+ continue;
1400
+ }
1401
+ // heading
1402
+ if (token = this.tokenizer.heading(src)) {
1403
+ src = src.substring(token.raw.length);
1404
+ tokens.push(token);
1405
+ continue;
1406
+ }
1407
+ // hr
1408
+ if (token = this.tokenizer.hr(src)) {
1409
+ src = src.substring(token.raw.length);
1410
+ tokens.push(token);
1411
+ continue;
1412
+ }
1413
+ // blockquote
1414
+ if (token = this.tokenizer.blockquote(src)) {
1415
+ src = src.substring(token.raw.length);
1416
+ tokens.push(token);
1417
+ continue;
1418
+ }
1419
+ // list
1420
+ if (token = this.tokenizer.list(src)) {
1421
+ src = src.substring(token.raw.length);
1422
+ tokens.push(token);
1423
+ continue;
1424
+ }
1425
+ // html
1426
+ if (token = this.tokenizer.html(src)) {
1427
+ src = src.substring(token.raw.length);
1428
+ tokens.push(token);
1429
+ continue;
1430
+ }
1431
+ // def
1432
+ if (token = this.tokenizer.def(src)) {
1433
+ src = src.substring(token.raw.length);
1434
+ lastToken = tokens[tokens.length - 1];
1435
+ if (lastToken && (lastToken.type === 'paragraph' || lastToken.type === 'text')) {
1436
+ lastToken.raw += '\n' + token.raw;
1437
+ lastToken.text += '\n' + token.raw;
1438
+ this.inlineQueue[this.inlineQueue.length - 1].src = lastToken.text;
1439
+ }
1440
+ else if (!this.tokens.links[token.tag]) {
1441
+ this.tokens.links[token.tag] = {
1442
+ href: token.href,
1443
+ title: token.title,
1444
+ };
1445
+ }
1446
+ continue;
1447
+ }
1448
+ // table (gfm)
1449
+ if (token = this.tokenizer.table(src)) {
1450
+ src = src.substring(token.raw.length);
1451
+ tokens.push(token);
1452
+ continue;
1453
+ }
1454
+ // lheading
1455
+ if (token = this.tokenizer.lheading(src)) {
1456
+ src = src.substring(token.raw.length);
1457
+ tokens.push(token);
1458
+ continue;
1459
+ }
1460
+ // top-level paragraph
1461
+ // prevent paragraph consuming extensions by clipping 'src' to extension start
1462
+ cutSrc = src;
1463
+ if (this.options.extensions && this.options.extensions.startBlock) {
1464
+ let startIndex = Infinity;
1465
+ const tempSrc = src.slice(1);
1466
+ let tempStart;
1467
+ this.options.extensions.startBlock.forEach((getStartIndex) => {
1468
+ tempStart = getStartIndex.call({ lexer: this }, tempSrc);
1469
+ if (typeof tempStart === 'number' && tempStart >= 0) {
1470
+ startIndex = Math.min(startIndex, tempStart);
1471
+ }
1472
+ });
1473
+ if (startIndex < Infinity && startIndex >= 0) {
1474
+ cutSrc = src.substring(0, startIndex + 1);
1475
+ }
1476
+ }
1477
+ if (this.state.top && (token = this.tokenizer.paragraph(cutSrc))) {
1478
+ lastToken = tokens[tokens.length - 1];
1479
+ if (lastParagraphClipped && lastToken?.type === 'paragraph') {
1480
+ lastToken.raw += '\n' + token.raw;
1481
+ lastToken.text += '\n' + token.text;
1482
+ this.inlineQueue.pop();
1483
+ this.inlineQueue[this.inlineQueue.length - 1].src = lastToken.text;
1484
+ }
1485
+ else {
1486
+ tokens.push(token);
1487
+ }
1488
+ lastParagraphClipped = (cutSrc.length !== src.length);
1489
+ src = src.substring(token.raw.length);
1490
+ continue;
1491
+ }
1492
+ // text
1493
+ if (token = this.tokenizer.text(src)) {
1494
+ src = src.substring(token.raw.length);
1495
+ lastToken = tokens[tokens.length - 1];
1496
+ if (lastToken && lastToken.type === 'text') {
1497
+ lastToken.raw += '\n' + token.raw;
1498
+ lastToken.text += '\n' + token.text;
1499
+ this.inlineQueue.pop();
1500
+ this.inlineQueue[this.inlineQueue.length - 1].src = lastToken.text;
1501
+ }
1502
+ else {
1503
+ tokens.push(token);
1504
+ }
1505
+ continue;
1506
+ }
1507
+ if (src) {
1508
+ const errMsg = 'Infinite loop on byte: ' + src.charCodeAt(0);
1509
+ if (this.options.silent) {
1510
+ console.error(errMsg);
1511
+ break;
1512
+ }
1513
+ else {
1514
+ throw new Error(errMsg);
1515
+ }
1516
+ }
1517
+ }
1518
+ this.state.top = true;
1519
+ return tokens;
1520
+ }
1521
+ inline(src, tokens = []) {
1522
+ this.inlineQueue.push({ src, tokens });
1523
+ return tokens;
1524
+ }
1525
+ /**
1526
+ * Lexing/Compiling
1527
+ */
1528
+ inlineTokens(src, tokens = []) {
1529
+ let token, lastToken, cutSrc;
1530
+ // String with links masked to avoid interference with em and strong
1531
+ let maskedSrc = src;
1532
+ let match;
1533
+ let keepPrevChar, prevChar;
1534
+ // Mask out reflinks
1535
+ if (this.tokens.links) {
1536
+ const links = Object.keys(this.tokens.links);
1537
+ if (links.length > 0) {
1538
+ while ((match = this.tokenizer.rules.inline.reflinkSearch.exec(maskedSrc)) != null) {
1539
+ if (links.includes(match[0].slice(match[0].lastIndexOf('[') + 1, -1))) {
1540
+ maskedSrc = maskedSrc.slice(0, match.index) + '[' + 'a'.repeat(match[0].length - 2) + ']' + maskedSrc.slice(this.tokenizer.rules.inline.reflinkSearch.lastIndex);
1541
+ }
1542
+ }
1543
+ }
1544
+ }
1545
+ // Mask out other blocks
1546
+ while ((match = this.tokenizer.rules.inline.blockSkip.exec(maskedSrc)) != null) {
1547
+ maskedSrc = maskedSrc.slice(0, match.index) + '[' + 'a'.repeat(match[0].length - 2) + ']' + maskedSrc.slice(this.tokenizer.rules.inline.blockSkip.lastIndex);
1548
+ }
1549
+ // Mask out escaped characters
1550
+ while ((match = this.tokenizer.rules.inline.anyPunctuation.exec(maskedSrc)) != null) {
1551
+ maskedSrc = maskedSrc.slice(0, match.index) + '++' + maskedSrc.slice(this.tokenizer.rules.inline.anyPunctuation.lastIndex);
1552
+ }
1553
+ while (src) {
1554
+ if (!keepPrevChar) {
1555
+ prevChar = '';
1556
+ }
1557
+ keepPrevChar = false;
1558
+ // extensions
1559
+ if (this.options.extensions
1560
+ && this.options.extensions.inline
1561
+ && this.options.extensions.inline.some((extTokenizer) => {
1562
+ if (token = extTokenizer.call({ lexer: this }, src, tokens)) {
1563
+ src = src.substring(token.raw.length);
1564
+ tokens.push(token);
1565
+ return true;
1566
+ }
1567
+ return false;
1568
+ })) {
1569
+ continue;
1570
+ }
1571
+ // escape
1572
+ if (token = this.tokenizer.escape(src)) {
1573
+ src = src.substring(token.raw.length);
1574
+ tokens.push(token);
1575
+ continue;
1576
+ }
1577
+ // tag
1578
+ if (token = this.tokenizer.tag(src)) {
1579
+ src = src.substring(token.raw.length);
1580
+ lastToken = tokens[tokens.length - 1];
1581
+ if (lastToken && token.type === 'text' && lastToken.type === 'text') {
1582
+ lastToken.raw += token.raw;
1583
+ lastToken.text += token.text;
1584
+ }
1585
+ else {
1586
+ tokens.push(token);
1587
+ }
1588
+ continue;
1589
+ }
1590
+ // link
1591
+ if (token = this.tokenizer.link(src)) {
1592
+ src = src.substring(token.raw.length);
1593
+ tokens.push(token);
1594
+ continue;
1595
+ }
1596
+ // reflink, nolink
1597
+ if (token = this.tokenizer.reflink(src, this.tokens.links)) {
1598
+ src = src.substring(token.raw.length);
1599
+ lastToken = tokens[tokens.length - 1];
1600
+ if (lastToken && token.type === 'text' && lastToken.type === 'text') {
1601
+ lastToken.raw += token.raw;
1602
+ lastToken.text += token.text;
1603
+ }
1604
+ else {
1605
+ tokens.push(token);
1606
+ }
1607
+ continue;
1608
+ }
1609
+ // em & strong
1610
+ if (token = this.tokenizer.emStrong(src, maskedSrc, prevChar)) {
1611
+ src = src.substring(token.raw.length);
1612
+ tokens.push(token);
1613
+ continue;
1614
+ }
1615
+ // code
1616
+ if (token = this.tokenizer.codespan(src)) {
1617
+ src = src.substring(token.raw.length);
1618
+ tokens.push(token);
1619
+ continue;
1620
+ }
1621
+ // br
1622
+ if (token = this.tokenizer.br(src)) {
1623
+ src = src.substring(token.raw.length);
1624
+ tokens.push(token);
1625
+ continue;
1626
+ }
1627
+ // del (gfm)
1628
+ if (token = this.tokenizer.del(src)) {
1629
+ src = src.substring(token.raw.length);
1630
+ tokens.push(token);
1631
+ continue;
1632
+ }
1633
+ // autolink
1634
+ if (token = this.tokenizer.autolink(src)) {
1635
+ src = src.substring(token.raw.length);
1636
+ tokens.push(token);
1637
+ continue;
1638
+ }
1639
+ // url (gfm)
1640
+ if (!this.state.inLink && (token = this.tokenizer.url(src))) {
1641
+ src = src.substring(token.raw.length);
1642
+ tokens.push(token);
1643
+ continue;
1644
+ }
1645
+ // text
1646
+ // prevent inlineText consuming extensions by clipping 'src' to extension start
1647
+ cutSrc = src;
1648
+ if (this.options.extensions && this.options.extensions.startInline) {
1649
+ let startIndex = Infinity;
1650
+ const tempSrc = src.slice(1);
1651
+ let tempStart;
1652
+ this.options.extensions.startInline.forEach((getStartIndex) => {
1653
+ tempStart = getStartIndex.call({ lexer: this }, tempSrc);
1654
+ if (typeof tempStart === 'number' && tempStart >= 0) {
1655
+ startIndex = Math.min(startIndex, tempStart);
1656
+ }
1657
+ });
1658
+ if (startIndex < Infinity && startIndex >= 0) {
1659
+ cutSrc = src.substring(0, startIndex + 1);
1660
+ }
1661
+ }
1662
+ if (token = this.tokenizer.inlineText(cutSrc)) {
1663
+ src = src.substring(token.raw.length);
1664
+ if (token.raw.slice(-1) !== '_') { // Track prevChar before string of ____ started
1665
+ prevChar = token.raw.slice(-1);
1666
+ }
1667
+ keepPrevChar = true;
1668
+ lastToken = tokens[tokens.length - 1];
1669
+ if (lastToken && lastToken.type === 'text') {
1670
+ lastToken.raw += token.raw;
1671
+ lastToken.text += token.text;
1672
+ }
1673
+ else {
1674
+ tokens.push(token);
1675
+ }
1676
+ continue;
1677
+ }
1678
+ if (src) {
1679
+ const errMsg = 'Infinite loop on byte: ' + src.charCodeAt(0);
1680
+ if (this.options.silent) {
1681
+ console.error(errMsg);
1682
+ break;
1683
+ }
1684
+ else {
1685
+ throw new Error(errMsg);
1686
+ }
1687
+ }
1688
+ }
1689
+ return tokens;
1690
+ }
1691
+ }
1692
+
1693
+ /**
1694
+ * Renderer
1695
+ */
1696
+ class _Renderer {
1697
+ options;
1698
+ parser; // set by the parser
1699
+ constructor(options) {
1700
+ this.options = options || _defaults;
1701
+ }
1702
+ space(token) {
1703
+ return '';
1704
+ }
1705
+ code({ text, lang, escaped }) {
1706
+ const langString = (lang || '').match(/^\S*/)?.[0];
1707
+ const code = text.replace(/\n$/, '') + '\n';
1708
+ if (!langString) {
1709
+ return '<pre><code>'
1710
+ + (escaped ? code : escape$1(code, true))
1711
+ + '</code></pre>\n';
1712
+ }
1713
+ return '<pre><code class="language-'
1714
+ + escape$1(langString)
1715
+ + '">'
1716
+ + (escaped ? code : escape$1(code, true))
1717
+ + '</code></pre>\n';
1718
+ }
1719
+ blockquote({ tokens }) {
1720
+ const body = this.parser.parse(tokens);
1721
+ return `<blockquote>\n${body}</blockquote>\n`;
1722
+ }
1723
+ html({ text }) {
1724
+ return text;
1725
+ }
1726
+ heading({ tokens, depth }) {
1727
+ return `<h${depth}>${this.parser.parseInline(tokens)}</h${depth}>\n`;
1728
+ }
1729
+ hr(token) {
1730
+ return '<hr>\n';
1731
+ }
1732
+ list(token) {
1733
+ const ordered = token.ordered;
1734
+ const start = token.start;
1735
+ let body = '';
1736
+ for (let j = 0; j < token.items.length; j++) {
1737
+ const item = token.items[j];
1738
+ body += this.listitem(item);
1739
+ }
1740
+ const type = ordered ? 'ol' : 'ul';
1741
+ const startAttr = (ordered && start !== 1) ? (' start="' + start + '"') : '';
1742
+ return '<' + type + startAttr + '>\n' + body + '</' + type + '>\n';
1743
+ }
1744
+ listitem(item) {
1745
+ let itemBody = '';
1746
+ if (item.task) {
1747
+ const checkbox = this.checkbox({ checked: !!item.checked });
1748
+ if (item.loose) {
1749
+ if (item.tokens.length > 0 && item.tokens[0].type === 'paragraph') {
1750
+ item.tokens[0].text = checkbox + ' ' + item.tokens[0].text;
1751
+ if (item.tokens[0].tokens && item.tokens[0].tokens.length > 0 && item.tokens[0].tokens[0].type === 'text') {
1752
+ item.tokens[0].tokens[0].text = checkbox + ' ' + item.tokens[0].tokens[0].text;
1753
+ }
1754
+ }
1755
+ else {
1756
+ item.tokens.unshift({
1757
+ type: 'text',
1758
+ raw: checkbox + ' ',
1759
+ text: checkbox + ' ',
1760
+ });
1761
+ }
1762
+ }
1763
+ else {
1764
+ itemBody += checkbox + ' ';
1765
+ }
1766
+ }
1767
+ itemBody += this.parser.parse(item.tokens, !!item.loose);
1768
+ return `<li>${itemBody}</li>\n`;
1769
+ }
1770
+ checkbox({ checked }) {
1771
+ return '<input '
1772
+ + (checked ? 'checked="" ' : '')
1773
+ + 'disabled="" type="checkbox">';
1774
+ }
1775
+ paragraph({ tokens }) {
1776
+ return `<p>${this.parser.parseInline(tokens)}</p>\n`;
1777
+ }
1778
+ table(token) {
1779
+ let header = '';
1780
+ // header
1781
+ let cell = '';
1782
+ for (let j = 0; j < token.header.length; j++) {
1783
+ cell += this.tablecell(token.header[j]);
1784
+ }
1785
+ header += this.tablerow({ text: cell });
1786
+ let body = '';
1787
+ for (let j = 0; j < token.rows.length; j++) {
1788
+ const row = token.rows[j];
1789
+ cell = '';
1790
+ for (let k = 0; k < row.length; k++) {
1791
+ cell += this.tablecell(row[k]);
1792
+ }
1793
+ body += this.tablerow({ text: cell });
1794
+ }
1795
+ if (body)
1796
+ body = `<tbody>${body}</tbody>`;
1797
+ return '<table>\n'
1798
+ + '<thead>\n'
1799
+ + header
1800
+ + '</thead>\n'
1801
+ + body
1802
+ + '</table>\n';
1803
+ }
1804
+ tablerow({ text }) {
1805
+ return `<tr>\n${text}</tr>\n`;
1806
+ }
1807
+ tablecell(token) {
1808
+ const content = this.parser.parseInline(token.tokens);
1809
+ const type = token.header ? 'th' : 'td';
1810
+ const tag = token.align
1811
+ ? `<${type} align="${token.align}">`
1812
+ : `<${type}>`;
1813
+ return tag + content + `</${type}>\n`;
1814
+ }
1815
+ /**
1816
+ * span level renderer
1817
+ */
1818
+ strong({ tokens }) {
1819
+ return `<strong>${this.parser.parseInline(tokens)}</strong>`;
1820
+ }
1821
+ em({ tokens }) {
1822
+ return `<em>${this.parser.parseInline(tokens)}</em>`;
1823
+ }
1824
+ codespan({ text }) {
1825
+ return `<code>${text}</code>`;
1826
+ }
1827
+ br(token) {
1828
+ return '<br>';
1829
+ }
1830
+ del({ tokens }) {
1831
+ return `<del>${this.parser.parseInline(tokens)}</del>`;
1832
+ }
1833
+ link({ href, title, tokens }) {
1834
+ const text = this.parser.parseInline(tokens);
1835
+ const cleanHref = cleanUrl(href);
1836
+ if (cleanHref === null) {
1837
+ return text;
1838
+ }
1839
+ href = cleanHref;
1840
+ let out = '<a href="' + href + '"';
1841
+ if (title) {
1842
+ out += ' title="' + title + '"';
1843
+ }
1844
+ out += '>' + text + '</a>';
1845
+ return out;
1846
+ }
1847
+ image({ href, title, text }) {
1848
+ const cleanHref = cleanUrl(href);
1849
+ if (cleanHref === null) {
1850
+ return text;
1851
+ }
1852
+ href = cleanHref;
1853
+ let out = `<img src="${href}" alt="${text}"`;
1854
+ if (title) {
1855
+ out += ` title="${title}"`;
1856
+ }
1857
+ out += '>';
1858
+ return out;
1859
+ }
1860
+ text(token) {
1861
+ return 'tokens' in token && token.tokens ? this.parser.parseInline(token.tokens) : token.text;
1862
+ }
1863
+ }
1864
+
1865
+ /**
1866
+ * TextRenderer
1867
+ * returns only the textual part of the token
1868
+ */
1869
+ class _TextRenderer {
1870
+ // no need for block level renderers
1871
+ strong({ text }) {
1872
+ return text;
1873
+ }
1874
+ em({ text }) {
1875
+ return text;
1876
+ }
1877
+ codespan({ text }) {
1878
+ return text;
1879
+ }
1880
+ del({ text }) {
1881
+ return text;
1882
+ }
1883
+ html({ text }) {
1884
+ return text;
1885
+ }
1886
+ text({ text }) {
1887
+ return text;
1888
+ }
1889
+ link({ text }) {
1890
+ return '' + text;
1891
+ }
1892
+ image({ text }) {
1893
+ return '' + text;
1894
+ }
1895
+ br() {
1896
+ return '';
1897
+ }
1898
+ }
1899
+
1900
+ /**
1901
+ * Parsing & Compiling
1902
+ */
1903
+ class _Parser {
1904
+ options;
1905
+ renderer;
1906
+ textRenderer;
1907
+ constructor(options) {
1908
+ this.options = options || _defaults;
1909
+ this.options.renderer = this.options.renderer || new _Renderer();
1910
+ this.renderer = this.options.renderer;
1911
+ this.renderer.options = this.options;
1912
+ this.renderer.parser = this;
1913
+ this.textRenderer = new _TextRenderer();
1914
+ }
1915
+ /**
1916
+ * Static Parse Method
1917
+ */
1918
+ static parse(tokens, options) {
1919
+ const parser = new _Parser(options);
1920
+ return parser.parse(tokens);
1921
+ }
1922
+ /**
1923
+ * Static Parse Inline Method
1924
+ */
1925
+ static parseInline(tokens, options) {
1926
+ const parser = new _Parser(options);
1927
+ return parser.parseInline(tokens);
1928
+ }
1929
+ /**
1930
+ * Parse Loop
1931
+ */
1932
+ parse(tokens, top = true) {
1933
+ let out = '';
1934
+ for (let i = 0; i < tokens.length; i++) {
1935
+ const anyToken = tokens[i];
1936
+ // Run any renderer extensions
1937
+ if (this.options.extensions && this.options.extensions.renderers && this.options.extensions.renderers[anyToken.type]) {
1938
+ const genericToken = anyToken;
1939
+ const ret = this.options.extensions.renderers[genericToken.type].call({ parser: this }, genericToken);
1940
+ if (ret !== false || !['space', 'hr', 'heading', 'code', 'table', 'blockquote', 'list', 'html', 'paragraph', 'text'].includes(genericToken.type)) {
1941
+ out += ret || '';
1942
+ continue;
1943
+ }
1944
+ }
1945
+ const token = anyToken;
1946
+ switch (token.type) {
1947
+ case 'space': {
1948
+ out += this.renderer.space(token);
1949
+ continue;
1950
+ }
1951
+ case 'hr': {
1952
+ out += this.renderer.hr(token);
1953
+ continue;
1954
+ }
1955
+ case 'heading': {
1956
+ out += this.renderer.heading(token);
1957
+ continue;
1958
+ }
1959
+ case 'code': {
1960
+ out += this.renderer.code(token);
1961
+ continue;
1962
+ }
1963
+ case 'table': {
1964
+ out += this.renderer.table(token);
1965
+ continue;
1966
+ }
1967
+ case 'blockquote': {
1968
+ out += this.renderer.blockquote(token);
1969
+ continue;
1970
+ }
1971
+ case 'list': {
1972
+ out += this.renderer.list(token);
1973
+ continue;
1974
+ }
1975
+ case 'html': {
1976
+ out += this.renderer.html(token);
1977
+ continue;
1978
+ }
1979
+ case 'paragraph': {
1980
+ out += this.renderer.paragraph(token);
1981
+ continue;
1982
+ }
1983
+ case 'text': {
1984
+ let textToken = token;
1985
+ let body = this.renderer.text(textToken);
1986
+ while (i + 1 < tokens.length && tokens[i + 1].type === 'text') {
1987
+ textToken = tokens[++i];
1988
+ body += '\n' + this.renderer.text(textToken);
1989
+ }
1990
+ if (top) {
1991
+ out += this.renderer.paragraph({
1992
+ type: 'paragraph',
1993
+ raw: body,
1994
+ text: body,
1995
+ tokens: [{ type: 'text', raw: body, text: body }],
1996
+ });
1997
+ }
1998
+ else {
1999
+ out += body;
2000
+ }
2001
+ continue;
2002
+ }
2003
+ default: {
2004
+ const errMsg = 'Token with "' + token.type + '" type was not found.';
2005
+ if (this.options.silent) {
2006
+ console.error(errMsg);
2007
+ return '';
2008
+ }
2009
+ else {
2010
+ throw new Error(errMsg);
2011
+ }
2012
+ }
2013
+ }
2014
+ }
2015
+ return out;
2016
+ }
2017
+ /**
2018
+ * Parse Inline Tokens
2019
+ */
2020
+ parseInline(tokens, renderer) {
2021
+ renderer = renderer || this.renderer;
2022
+ let out = '';
2023
+ for (let i = 0; i < tokens.length; i++) {
2024
+ const anyToken = tokens[i];
2025
+ // Run any renderer extensions
2026
+ if (this.options.extensions && this.options.extensions.renderers && this.options.extensions.renderers[anyToken.type]) {
2027
+ const ret = this.options.extensions.renderers[anyToken.type].call({ parser: this }, anyToken);
2028
+ if (ret !== false || !['escape', 'html', 'link', 'image', 'strong', 'em', 'codespan', 'br', 'del', 'text'].includes(anyToken.type)) {
2029
+ out += ret || '';
2030
+ continue;
2031
+ }
2032
+ }
2033
+ const token = anyToken;
2034
+ switch (token.type) {
2035
+ case 'escape': {
2036
+ out += renderer.text(token);
2037
+ break;
2038
+ }
2039
+ case 'html': {
2040
+ out += renderer.html(token);
2041
+ break;
2042
+ }
2043
+ case 'link': {
2044
+ out += renderer.link(token);
2045
+ break;
2046
+ }
2047
+ case 'image': {
2048
+ out += renderer.image(token);
2049
+ break;
2050
+ }
2051
+ case 'strong': {
2052
+ out += renderer.strong(token);
2053
+ break;
2054
+ }
2055
+ case 'em': {
2056
+ out += renderer.em(token);
2057
+ break;
2058
+ }
2059
+ case 'codespan': {
2060
+ out += renderer.codespan(token);
2061
+ break;
2062
+ }
2063
+ case 'br': {
2064
+ out += renderer.br(token);
2065
+ break;
2066
+ }
2067
+ case 'del': {
2068
+ out += renderer.del(token);
2069
+ break;
2070
+ }
2071
+ case 'text': {
2072
+ out += renderer.text(token);
2073
+ break;
2074
+ }
2075
+ default: {
2076
+ const errMsg = 'Token with "' + token.type + '" type was not found.';
2077
+ if (this.options.silent) {
2078
+ console.error(errMsg);
2079
+ return '';
2080
+ }
2081
+ else {
2082
+ throw new Error(errMsg);
2083
+ }
2084
+ }
2085
+ }
2086
+ }
2087
+ return out;
2088
+ }
2089
+ }
2090
+
2091
+ class _Hooks {
2092
+ options;
2093
+ block;
2094
+ constructor(options) {
2095
+ this.options = options || _defaults;
2096
+ }
2097
+ static passThroughHooks = new Set([
2098
+ 'preprocess',
2099
+ 'postprocess',
2100
+ 'processAllTokens',
2101
+ ]);
2102
+ /**
2103
+ * Process markdown before marked
2104
+ */
2105
+ preprocess(markdown) {
2106
+ return markdown;
2107
+ }
2108
+ /**
2109
+ * Process HTML after marked is finished
2110
+ */
2111
+ postprocess(html) {
2112
+ return html;
2113
+ }
2114
+ /**
2115
+ * Process all tokens before walk tokens
2116
+ */
2117
+ processAllTokens(tokens) {
2118
+ return tokens;
2119
+ }
2120
+ /**
2121
+ * Provide function to tokenize markdown
2122
+ */
2123
+ provideLexer() {
2124
+ return this.block ? _Lexer.lex : _Lexer.lexInline;
2125
+ }
2126
+ /**
2127
+ * Provide function to parse tokens
2128
+ */
2129
+ provideParser() {
2130
+ return this.block ? _Parser.parse : _Parser.parseInline;
2131
+ }
2132
+ }
2133
+
2134
+ class Marked {
2135
+ defaults = _getDefaults();
2136
+ options = this.setOptions;
2137
+ parse = this.parseMarkdown(true);
2138
+ parseInline = this.parseMarkdown(false);
2139
+ Parser = _Parser;
2140
+ Renderer = _Renderer;
2141
+ TextRenderer = _TextRenderer;
2142
+ Lexer = _Lexer;
2143
+ Tokenizer = _Tokenizer;
2144
+ Hooks = _Hooks;
2145
+ constructor(...args) {
2146
+ this.use(...args);
2147
+ }
2148
+ /**
2149
+ * Run callback for every token
2150
+ */
2151
+ walkTokens(tokens, callback) {
2152
+ let values = [];
2153
+ for (const token of tokens) {
2154
+ values = values.concat(callback.call(this, token));
2155
+ switch (token.type) {
2156
+ case 'table': {
2157
+ const tableToken = token;
2158
+ for (const cell of tableToken.header) {
2159
+ values = values.concat(this.walkTokens(cell.tokens, callback));
2160
+ }
2161
+ for (const row of tableToken.rows) {
2162
+ for (const cell of row) {
2163
+ values = values.concat(this.walkTokens(cell.tokens, callback));
2164
+ }
2165
+ }
2166
+ break;
2167
+ }
2168
+ case 'list': {
2169
+ const listToken = token;
2170
+ values = values.concat(this.walkTokens(listToken.items, callback));
2171
+ break;
2172
+ }
2173
+ default: {
2174
+ const genericToken = token;
2175
+ if (this.defaults.extensions?.childTokens?.[genericToken.type]) {
2176
+ this.defaults.extensions.childTokens[genericToken.type].forEach((childTokens) => {
2177
+ const tokens = genericToken[childTokens].flat(Infinity);
2178
+ values = values.concat(this.walkTokens(tokens, callback));
2179
+ });
2180
+ }
2181
+ else if (genericToken.tokens) {
2182
+ values = values.concat(this.walkTokens(genericToken.tokens, callback));
2183
+ }
2184
+ }
2185
+ }
2186
+ }
2187
+ return values;
2188
+ }
2189
+ use(...args) {
2190
+ const extensions = this.defaults.extensions || { renderers: {}, childTokens: {} };
2191
+ args.forEach((pack) => {
2192
+ // copy options to new object
2193
+ const opts = { ...pack };
2194
+ // set async to true if it was set to true before
2195
+ opts.async = this.defaults.async || opts.async || false;
2196
+ // ==-- Parse "addon" extensions --== //
2197
+ if (pack.extensions) {
2198
+ pack.extensions.forEach((ext) => {
2199
+ if (!ext.name) {
2200
+ throw new Error('extension name required');
2201
+ }
2202
+ if ('renderer' in ext) { // Renderer extensions
2203
+ const prevRenderer = extensions.renderers[ext.name];
2204
+ if (prevRenderer) {
2205
+ // Replace extension with func to run new extension but fall back if false
2206
+ extensions.renderers[ext.name] = function (...args) {
2207
+ let ret = ext.renderer.apply(this, args);
2208
+ if (ret === false) {
2209
+ ret = prevRenderer.apply(this, args);
2210
+ }
2211
+ return ret;
2212
+ };
2213
+ }
2214
+ else {
2215
+ extensions.renderers[ext.name] = ext.renderer;
2216
+ }
2217
+ }
2218
+ if ('tokenizer' in ext) { // Tokenizer Extensions
2219
+ if (!ext.level || (ext.level !== 'block' && ext.level !== 'inline')) {
2220
+ throw new Error("extension level must be 'block' or 'inline'");
2221
+ }
2222
+ const extLevel = extensions[ext.level];
2223
+ if (extLevel) {
2224
+ extLevel.unshift(ext.tokenizer);
2225
+ }
2226
+ else {
2227
+ extensions[ext.level] = [ext.tokenizer];
2228
+ }
2229
+ if (ext.start) { // Function to check for start of token
2230
+ if (ext.level === 'block') {
2231
+ if (extensions.startBlock) {
2232
+ extensions.startBlock.push(ext.start);
2233
+ }
2234
+ else {
2235
+ extensions.startBlock = [ext.start];
2236
+ }
2237
+ }
2238
+ else if (ext.level === 'inline') {
2239
+ if (extensions.startInline) {
2240
+ extensions.startInline.push(ext.start);
2241
+ }
2242
+ else {
2243
+ extensions.startInline = [ext.start];
2244
+ }
2245
+ }
2246
+ }
2247
+ }
2248
+ if ('childTokens' in ext && ext.childTokens) { // Child tokens to be visited by walkTokens
2249
+ extensions.childTokens[ext.name] = ext.childTokens;
2250
+ }
2251
+ });
2252
+ opts.extensions = extensions;
2253
+ }
2254
+ // ==-- Parse "overwrite" extensions --== //
2255
+ if (pack.renderer) {
2256
+ const renderer = this.defaults.renderer || new _Renderer(this.defaults);
2257
+ for (const prop in pack.renderer) {
2258
+ if (!(prop in renderer)) {
2259
+ throw new Error(`renderer '${prop}' does not exist`);
2260
+ }
2261
+ if (['options', 'parser'].includes(prop)) {
2262
+ // ignore options property
2263
+ continue;
2264
+ }
2265
+ const rendererProp = prop;
2266
+ const rendererFunc = pack.renderer[rendererProp];
2267
+ const prevRenderer = renderer[rendererProp];
2268
+ // Replace renderer with func to run extension, but fall back if false
2269
+ renderer[rendererProp] = (...args) => {
2270
+ let ret = rendererFunc.apply(renderer, args);
2271
+ if (ret === false) {
2272
+ ret = prevRenderer.apply(renderer, args);
2273
+ }
2274
+ return ret || '';
2275
+ };
2276
+ }
2277
+ opts.renderer = renderer;
2278
+ }
2279
+ if (pack.tokenizer) {
2280
+ const tokenizer = this.defaults.tokenizer || new _Tokenizer(this.defaults);
2281
+ for (const prop in pack.tokenizer) {
2282
+ if (!(prop in tokenizer)) {
2283
+ throw new Error(`tokenizer '${prop}' does not exist`);
2284
+ }
2285
+ if (['options', 'rules', 'lexer'].includes(prop)) {
2286
+ // ignore options, rules, and lexer properties
2287
+ continue;
2288
+ }
2289
+ const tokenizerProp = prop;
2290
+ const tokenizerFunc = pack.tokenizer[tokenizerProp];
2291
+ const prevTokenizer = tokenizer[tokenizerProp];
2292
+ // Replace tokenizer with func to run extension, but fall back if false
2293
+ // @ts-expect-error cannot type tokenizer function dynamically
2294
+ tokenizer[tokenizerProp] = (...args) => {
2295
+ let ret = tokenizerFunc.apply(tokenizer, args);
2296
+ if (ret === false) {
2297
+ ret = prevTokenizer.apply(tokenizer, args);
2298
+ }
2299
+ return ret;
2300
+ };
2301
+ }
2302
+ opts.tokenizer = tokenizer;
2303
+ }
2304
+ // ==-- Parse Hooks extensions --== //
2305
+ if (pack.hooks) {
2306
+ const hooks = this.defaults.hooks || new _Hooks();
2307
+ for (const prop in pack.hooks) {
2308
+ if (!(prop in hooks)) {
2309
+ throw new Error(`hook '${prop}' does not exist`);
2310
+ }
2311
+ if (['options', 'block'].includes(prop)) {
2312
+ // ignore options and block properties
2313
+ continue;
2314
+ }
2315
+ const hooksProp = prop;
2316
+ const hooksFunc = pack.hooks[hooksProp];
2317
+ const prevHook = hooks[hooksProp];
2318
+ if (_Hooks.passThroughHooks.has(prop)) {
2319
+ // @ts-expect-error cannot type hook function dynamically
2320
+ hooks[hooksProp] = (arg) => {
2321
+ if (this.defaults.async) {
2322
+ return Promise.resolve(hooksFunc.call(hooks, arg)).then(ret => {
2323
+ return prevHook.call(hooks, ret);
2324
+ });
2325
+ }
2326
+ const ret = hooksFunc.call(hooks, arg);
2327
+ return prevHook.call(hooks, ret);
2328
+ };
2329
+ }
2330
+ else {
2331
+ // @ts-expect-error cannot type hook function dynamically
2332
+ hooks[hooksProp] = (...args) => {
2333
+ let ret = hooksFunc.apply(hooks, args);
2334
+ if (ret === false) {
2335
+ ret = prevHook.apply(hooks, args);
2336
+ }
2337
+ return ret;
2338
+ };
2339
+ }
2340
+ }
2341
+ opts.hooks = hooks;
2342
+ }
2343
+ // ==-- Parse WalkTokens extensions --== //
2344
+ if (pack.walkTokens) {
2345
+ const walkTokens = this.defaults.walkTokens;
2346
+ const packWalktokens = pack.walkTokens;
2347
+ opts.walkTokens = function (token) {
2348
+ let values = [];
2349
+ values.push(packWalktokens.call(this, token));
2350
+ if (walkTokens) {
2351
+ values = values.concat(walkTokens.call(this, token));
2352
+ }
2353
+ return values;
2354
+ };
2355
+ }
2356
+ this.defaults = { ...this.defaults, ...opts };
2357
+ });
2358
+ return this;
2359
+ }
2360
+ setOptions(opt) {
2361
+ this.defaults = { ...this.defaults, ...opt };
2362
+ return this;
2363
+ }
2364
+ lexer(src, options) {
2365
+ return _Lexer.lex(src, options ?? this.defaults);
2366
+ }
2367
+ parser(tokens, options) {
2368
+ return _Parser.parse(tokens, options ?? this.defaults);
2369
+ }
2370
+ parseMarkdown(blockType) {
2371
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
2372
+ const parse = (src, options) => {
2373
+ const origOpt = { ...options };
2374
+ const opt = { ...this.defaults, ...origOpt };
2375
+ const throwError = this.onError(!!opt.silent, !!opt.async);
2376
+ // throw error if an extension set async to true but parse was called with async: false
2377
+ if (this.defaults.async === true && origOpt.async === false) {
2378
+ return throwError(new Error('marked(): The async option was set to true by an extension. Remove async: false from the parse options object to return a Promise.'));
2379
+ }
2380
+ // throw error in case of non string input
2381
+ if (typeof src === 'undefined' || src === null) {
2382
+ return throwError(new Error('marked(): input parameter is undefined or null'));
2383
+ }
2384
+ if (typeof src !== 'string') {
2385
+ return throwError(new Error('marked(): input parameter is of type '
2386
+ + Object.prototype.toString.call(src) + ', string expected'));
2387
+ }
2388
+ if (opt.hooks) {
2389
+ opt.hooks.options = opt;
2390
+ opt.hooks.block = blockType;
2391
+ }
2392
+ const lexer = opt.hooks ? opt.hooks.provideLexer() : (blockType ? _Lexer.lex : _Lexer.lexInline);
2393
+ const parser = opt.hooks ? opt.hooks.provideParser() : (blockType ? _Parser.parse : _Parser.parseInline);
2394
+ if (opt.async) {
2395
+ return Promise.resolve(opt.hooks ? opt.hooks.preprocess(src) : src)
2396
+ .then(src => lexer(src, opt))
2397
+ .then(tokens => opt.hooks ? opt.hooks.processAllTokens(tokens) : tokens)
2398
+ .then(tokens => opt.walkTokens ? Promise.all(this.walkTokens(tokens, opt.walkTokens)).then(() => tokens) : tokens)
2399
+ .then(tokens => parser(tokens, opt))
2400
+ .then(html => opt.hooks ? opt.hooks.postprocess(html) : html)
2401
+ .catch(throwError);
2402
+ }
2403
+ try {
2404
+ if (opt.hooks) {
2405
+ src = opt.hooks.preprocess(src);
2406
+ }
2407
+ let tokens = lexer(src, opt);
2408
+ if (opt.hooks) {
2409
+ tokens = opt.hooks.processAllTokens(tokens);
2410
+ }
2411
+ if (opt.walkTokens) {
2412
+ this.walkTokens(tokens, opt.walkTokens);
2413
+ }
2414
+ let html = parser(tokens, opt);
2415
+ if (opt.hooks) {
2416
+ html = opt.hooks.postprocess(html);
2417
+ }
2418
+ return html;
2419
+ }
2420
+ catch (e) {
2421
+ return throwError(e);
2422
+ }
2423
+ };
2424
+ return parse;
2425
+ }
2426
+ onError(silent, async) {
2427
+ return (e) => {
2428
+ e.message += '\nPlease report this to https://github.com/markedjs/marked.';
2429
+ if (silent) {
2430
+ const msg = '<p>An error occurred:</p><pre>'
2431
+ + escape$1(e.message + '', true)
2432
+ + '</pre>';
2433
+ if (async) {
2434
+ return Promise.resolve(msg);
2435
+ }
2436
+ return msg;
2437
+ }
2438
+ if (async) {
2439
+ return Promise.reject(e);
2440
+ }
2441
+ throw e;
2442
+ };
2443
+ }
2444
+ }
2445
+
2446
+ const markedInstance = new Marked();
2447
+ function marked(src, opt) {
2448
+ return markedInstance.parse(src, opt);
2449
+ }
2450
+ /**
2451
+ * Sets the default options.
2452
+ *
2453
+ * @param options Hash of options
2454
+ */
2455
+ marked.options =
2456
+ marked.setOptions = function (options) {
2457
+ markedInstance.setOptions(options);
2458
+ marked.defaults = markedInstance.defaults;
2459
+ changeDefaults(marked.defaults);
2460
+ return marked;
2461
+ };
2462
+ /**
2463
+ * Gets the original marked default options.
2464
+ */
2465
+ marked.getDefaults = _getDefaults;
2466
+ marked.defaults = _defaults;
2467
+ /**
2468
+ * Use Extension
2469
+ */
2470
+ marked.use = function (...args) {
2471
+ markedInstance.use(...args);
2472
+ marked.defaults = markedInstance.defaults;
2473
+ changeDefaults(marked.defaults);
2474
+ return marked;
2475
+ };
2476
+ /**
2477
+ * Run callback for every token
2478
+ */
2479
+ marked.walkTokens = function (tokens, callback) {
2480
+ return markedInstance.walkTokens(tokens, callback);
2481
+ };
2482
+ /**
2483
+ * Compiles markdown to HTML without enclosing `p` tag.
2484
+ *
2485
+ * @param src String of markdown source to be compiled
2486
+ * @param options Hash of options
2487
+ * @return String of compiled HTML
2488
+ */
2489
+ marked.parseInline = markedInstance.parseInline;
2490
+ /**
2491
+ * Expose
2492
+ */
2493
+ marked.Parser = _Parser;
2494
+ marked.parser = _Parser.parse;
2495
+ marked.Renderer = _Renderer;
2496
+ marked.TextRenderer = _TextRenderer;
2497
+ marked.Lexer = _Lexer;
2498
+ marked.lexer = _Lexer.lex;
2499
+ marked.Tokenizer = _Tokenizer;
2500
+ marked.Hooks = _Hooks;
2501
+ marked.parse = marked;
2502
+ marked.options;
2503
+ marked.setOptions;
2504
+ marked.use;
2505
+ marked.walkTokens;
2506
+ marked.parseInline;
2507
+ _Parser.parse;
2508
+ _Lexer.lex;
2509
+
2510
+ function extend(destination) {
2511
+ for (var i = 1; i < arguments.length; i++) {
2512
+ var source = arguments[i];
2513
+ for (var key in source) {
2514
+ if (Object.prototype.hasOwnProperty.call(source, key)) destination[key] = source[key];
2515
+ }
2516
+ }
2517
+ return destination;
2518
+ }
2519
+ function repeat(character, count) {
2520
+ return Array(count + 1).join(character);
2521
+ }
2522
+ function trimLeadingNewlines(string) {
2523
+ return string.replace(/^\n*/, '');
2524
+ }
2525
+ function trimTrailingNewlines(string) {
2526
+ // avoid match-at-end regexp bottleneck, see #370
2527
+ var indexEnd = string.length;
2528
+ while (indexEnd > 0 && string[indexEnd - 1] === '\n') indexEnd--;
2529
+ return string.substring(0, indexEnd);
2530
+ }
2531
+ function trimNewlines(string) {
2532
+ return trimTrailingNewlines(trimLeadingNewlines(string));
2533
+ }
2534
+ var blockElements = ['ADDRESS', 'ARTICLE', 'ASIDE', 'AUDIO', 'BLOCKQUOTE', 'BODY', 'CANVAS', 'CENTER', 'DD', 'DIR', 'DIV', 'DL', 'DT', 'FIELDSET', 'FIGCAPTION', 'FIGURE', 'FOOTER', 'FORM', 'FRAMESET', 'H1', 'H2', 'H3', 'H4', 'H5', 'H6', 'HEADER', 'HGROUP', 'HR', 'HTML', 'ISINDEX', 'LI', 'MAIN', 'MENU', 'NAV', 'NOFRAMES', 'NOSCRIPT', 'OL', 'OUTPUT', 'P', 'PRE', 'SECTION', 'TABLE', 'TBODY', 'TD', 'TFOOT', 'TH', 'THEAD', 'TR', 'UL'];
2535
+ function isBlock(node) {
2536
+ return is(node, blockElements);
2537
+ }
2538
+ var voidElements = ['AREA', 'BASE', 'BR', 'COL', 'COMMAND', 'EMBED', 'HR', 'IMG', 'INPUT', 'KEYGEN', 'LINK', 'META', 'PARAM', 'SOURCE', 'TRACK', 'WBR'];
2539
+ function isVoid(node) {
2540
+ return is(node, voidElements);
2541
+ }
2542
+ function hasVoid(node) {
2543
+ return has(node, voidElements);
2544
+ }
2545
+ var meaningfulWhenBlankElements = ['A', 'TABLE', 'THEAD', 'TBODY', 'TFOOT', 'TH', 'TD', 'IFRAME', 'SCRIPT', 'AUDIO', 'VIDEO'];
2546
+ function isMeaningfulWhenBlank(node) {
2547
+ return is(node, meaningfulWhenBlankElements);
2548
+ }
2549
+ function hasMeaningfulWhenBlank(node) {
2550
+ return has(node, meaningfulWhenBlankElements);
2551
+ }
2552
+ function is(node, tagNames) {
2553
+ return tagNames.indexOf(node.nodeName) >= 0;
2554
+ }
2555
+ function has(node, tagNames) {
2556
+ return node.getElementsByTagName && tagNames.some(function (tagName) {
2557
+ return node.getElementsByTagName(tagName).length;
2558
+ });
2559
+ }
2560
+ var markdownEscapes = [[/\\/g, '\\\\'], [/\*/g, '\\*'], [/^-/g, '\\-'], [/^\+ /g, '\\+ '], [/^(=+)/g, '\\$1'], [/^(#{1,6}) /g, '\\$1 '], [/`/g, '\\`'], [/^~~~/g, '\\~~~'], [/\[/g, '\\['], [/\]/g, '\\]'], [/^>/g, '\\>'], [/_/g, '\\_'], [/^(\d+)\. /g, '$1\\. ']];
2561
+ function escapeMarkdown(string) {
2562
+ return markdownEscapes.reduce(function (accumulator, escape) {
2563
+ return accumulator.replace(escape[0], escape[1]);
2564
+ }, string);
2565
+ }
2566
+
2567
+ var rules = {};
2568
+ rules.paragraph = {
2569
+ filter: 'p',
2570
+ replacement: function (content) {
2571
+ return '\n\n' + content + '\n\n';
2572
+ }
2573
+ };
2574
+ rules.lineBreak = {
2575
+ filter: 'br',
2576
+ replacement: function (content, node, options) {
2577
+ return options.br + '\n';
2578
+ }
2579
+ };
2580
+ rules.heading = {
2581
+ filter: ['h1', 'h2', 'h3', 'h4', 'h5', 'h6'],
2582
+ replacement: function (content, node, options) {
2583
+ var hLevel = Number(node.nodeName.charAt(1));
2584
+ if (options.headingStyle === 'setext' && hLevel < 3) {
2585
+ var underline = repeat(hLevel === 1 ? '=' : '-', content.length);
2586
+ return '\n\n' + content + '\n' + underline + '\n\n';
2587
+ } else {
2588
+ return '\n\n' + repeat('#', hLevel) + ' ' + content + '\n\n';
2589
+ }
2590
+ }
2591
+ };
2592
+ rules.blockquote = {
2593
+ filter: 'blockquote',
2594
+ replacement: function (content) {
2595
+ content = trimNewlines(content).replace(/^/gm, '> ');
2596
+ return '\n\n' + content + '\n\n';
2597
+ }
2598
+ };
2599
+ rules.list = {
2600
+ filter: ['ul', 'ol'],
2601
+ replacement: function (content, node) {
2602
+ var parent = node.parentNode;
2603
+ if (parent.nodeName === 'LI' && parent.lastElementChild === node) {
2604
+ return '\n' + content;
2605
+ } else {
2606
+ return '\n\n' + content + '\n\n';
2607
+ }
2608
+ }
2609
+ };
2610
+ rules.listItem = {
2611
+ filter: 'li',
2612
+ replacement: function (content, node, options) {
2613
+ var prefix = options.bulletListMarker + ' ';
2614
+ var parent = node.parentNode;
2615
+ if (parent.nodeName === 'OL') {
2616
+ var start = parent.getAttribute('start');
2617
+ var index = Array.prototype.indexOf.call(parent.children, node);
2618
+ prefix = (start ? Number(start) + index : index + 1) + '. ';
2619
+ }
2620
+ var isParagraph = /\n$/.test(content);
2621
+ content = trimNewlines(content) + (isParagraph ? '\n' : '');
2622
+ content = content.replace(/\n/gm, '\n' + ' '.repeat(prefix.length)); // indent
2623
+ return prefix + content + (node.nextSibling ? '\n' : '');
2624
+ }
2625
+ };
2626
+ rules.indentedCodeBlock = {
2627
+ filter: function (node, options) {
2628
+ return options.codeBlockStyle === 'indented' && node.nodeName === 'PRE' && node.firstChild && node.firstChild.nodeName === 'CODE';
2629
+ },
2630
+ replacement: function (content, node, options) {
2631
+ return '\n\n ' + node.firstChild.textContent.replace(/\n/g, '\n ') + '\n\n';
2632
+ }
2633
+ };
2634
+ rules.fencedCodeBlock = {
2635
+ filter: function (node, options) {
2636
+ return options.codeBlockStyle === 'fenced' && node.nodeName === 'PRE' && node.firstChild && node.firstChild.nodeName === 'CODE';
2637
+ },
2638
+ replacement: function (content, node, options) {
2639
+ var className = node.firstChild.getAttribute('class') || '';
2640
+ var language = (className.match(/language-(\S+)/) || [null, ''])[1];
2641
+ var code = node.firstChild.textContent;
2642
+ var fenceChar = options.fence.charAt(0);
2643
+ var fenceSize = 3;
2644
+ var fenceInCodeRegex = new RegExp('^' + fenceChar + '{3,}', 'gm');
2645
+ var match;
2646
+ while (match = fenceInCodeRegex.exec(code)) {
2647
+ if (match[0].length >= fenceSize) {
2648
+ fenceSize = match[0].length + 1;
2649
+ }
2650
+ }
2651
+ var fence = repeat(fenceChar, fenceSize);
2652
+ return '\n\n' + fence + language + '\n' + code.replace(/\n$/, '') + '\n' + fence + '\n\n';
2653
+ }
2654
+ };
2655
+ rules.horizontalRule = {
2656
+ filter: 'hr',
2657
+ replacement: function (content, node, options) {
2658
+ return '\n\n' + options.hr + '\n\n';
2659
+ }
2660
+ };
2661
+ rules.inlineLink = {
2662
+ filter: function (node, options) {
2663
+ return options.linkStyle === 'inlined' && node.nodeName === 'A' && node.getAttribute('href');
2664
+ },
2665
+ replacement: function (content, node) {
2666
+ var href = escapeLinkDestination(node.getAttribute('href'));
2667
+ var title = escapeLinkTitle(cleanAttribute(node.getAttribute('title')));
2668
+ var titlePart = title ? ' "' + title + '"' : '';
2669
+ return '[' + content + '](' + href + titlePart + ')';
2670
+ }
2671
+ };
2672
+ rules.referenceLink = {
2673
+ filter: function (node, options) {
2674
+ return options.linkStyle === 'referenced' && node.nodeName === 'A' && node.getAttribute('href');
2675
+ },
2676
+ replacement: function (content, node, options) {
2677
+ var href = escapeLinkDestination(node.getAttribute('href'));
2678
+ var title = cleanAttribute(node.getAttribute('title'));
2679
+ if (title) title = ' "' + escapeLinkTitle(title) + '"';
2680
+ var replacement;
2681
+ var reference;
2682
+ switch (options.linkReferenceStyle) {
2683
+ case 'collapsed':
2684
+ replacement = '[' + content + '][]';
2685
+ reference = '[' + content + ']: ' + href + title;
2686
+ break;
2687
+ case 'shortcut':
2688
+ replacement = '[' + content + ']';
2689
+ reference = '[' + content + ']: ' + href + title;
2690
+ break;
2691
+ default:
2692
+ var id = this.references.length + 1;
2693
+ replacement = '[' + content + '][' + id + ']';
2694
+ reference = '[' + id + ']: ' + href + title;
2695
+ }
2696
+ this.references.push(reference);
2697
+ return replacement;
2698
+ },
2699
+ references: [],
2700
+ append: function (options) {
2701
+ var references = '';
2702
+ if (this.references.length) {
2703
+ references = '\n\n' + this.references.join('\n') + '\n\n';
2704
+ this.references = []; // Reset references
2705
+ }
2706
+ return references;
2707
+ }
2708
+ };
2709
+ rules.emphasis = {
2710
+ filter: ['em', 'i'],
2711
+ replacement: function (content, node, options) {
2712
+ if (!content.trim()) return '';
2713
+ return options.emDelimiter + content + options.emDelimiter;
2714
+ }
2715
+ };
2716
+ rules.strong = {
2717
+ filter: ['strong', 'b'],
2718
+ replacement: function (content, node, options) {
2719
+ if (!content.trim()) return '';
2720
+ return options.strongDelimiter + content + options.strongDelimiter;
2721
+ }
2722
+ };
2723
+ rules.code = {
2724
+ filter: function (node) {
2725
+ var hasSiblings = node.previousSibling || node.nextSibling;
2726
+ var isCodeBlock = node.parentNode.nodeName === 'PRE' && !hasSiblings;
2727
+ return node.nodeName === 'CODE' && !isCodeBlock;
2728
+ },
2729
+ replacement: function (content) {
2730
+ if (!content) return '';
2731
+ content = content.replace(/\r?\n|\r/g, ' ');
2732
+ var extraSpace = /^`|^ .*?[^ ].* $|`$/.test(content) ? ' ' : '';
2733
+ var delimiter = '`';
2734
+ var matches = content.match(/`+/gm) || [];
2735
+ while (matches.indexOf(delimiter) !== -1) delimiter = delimiter + '`';
2736
+ return delimiter + extraSpace + content + extraSpace + delimiter;
2737
+ }
2738
+ };
2739
+ rules.image = {
2740
+ filter: 'img',
2741
+ replacement: function (content, node) {
2742
+ var alt = escapeMarkdown(cleanAttribute(node.getAttribute('alt')));
2743
+ var src = escapeLinkDestination(node.getAttribute('src') || '');
2744
+ var title = cleanAttribute(node.getAttribute('title'));
2745
+ var titlePart = title ? ' "' + escapeLinkTitle(title) + '"' : '';
2746
+ return src ? '![' + alt + ']' + '(' + src + titlePart + ')' : '';
2747
+ }
2748
+ };
2749
+ function cleanAttribute(attribute) {
2750
+ return attribute ? attribute.replace(/(\n+\s*)+/g, '\n') : '';
2751
+ }
2752
+ function escapeLinkDestination(destination) {
2753
+ var escaped = destination.replace(/([<>()])/g, '\\$1');
2754
+ return escaped.indexOf(' ') >= 0 ? '<' + escaped + '>' : escaped;
2755
+ }
2756
+ function escapeLinkTitle(title) {
2757
+ return title.replace(/"/g, '\\"');
2758
+ }
2759
+
2760
+ /**
2761
+ * Manages a collection of rules used to convert HTML to Markdown
2762
+ */
2763
+
2764
+ function Rules(options) {
2765
+ this.options = options;
2766
+ this._keep = [];
2767
+ this._remove = [];
2768
+ this.blankRule = {
2769
+ replacement: options.blankReplacement
2770
+ };
2771
+ this.keepReplacement = options.keepReplacement;
2772
+ this.defaultRule = {
2773
+ replacement: options.defaultReplacement
2774
+ };
2775
+ this.array = [];
2776
+ for (var key in options.rules) this.array.push(options.rules[key]);
2777
+ }
2778
+ Rules.prototype = {
2779
+ add: function (key, rule) {
2780
+ this.array.unshift(rule);
2781
+ },
2782
+ keep: function (filter) {
2783
+ this._keep.unshift({
2784
+ filter: filter,
2785
+ replacement: this.keepReplacement
2786
+ });
2787
+ },
2788
+ remove: function (filter) {
2789
+ this._remove.unshift({
2790
+ filter: filter,
2791
+ replacement: function () {
2792
+ return '';
2793
+ }
2794
+ });
2795
+ },
2796
+ forNode: function (node) {
2797
+ if (node.isBlank) return this.blankRule;
2798
+ var rule;
2799
+ if (rule = findRule(this.array, node, this.options)) return rule;
2800
+ if (rule = findRule(this._keep, node, this.options)) return rule;
2801
+ if (rule = findRule(this._remove, node, this.options)) return rule;
2802
+ return this.defaultRule;
2803
+ },
2804
+ forEach: function (fn) {
2805
+ for (var i = 0; i < this.array.length; i++) fn(this.array[i], i);
2806
+ }
2807
+ };
2808
+ function findRule(rules, node, options) {
2809
+ for (var i = 0; i < rules.length; i++) {
2810
+ var rule = rules[i];
2811
+ if (filterValue(rule, node, options)) return rule;
2812
+ }
2813
+ return undefined;
2814
+ }
2815
+ function filterValue(rule, node, options) {
2816
+ var filter = rule.filter;
2817
+ if (typeof filter === 'string') {
2818
+ if (filter === node.nodeName.toLowerCase()) return true;
2819
+ } else if (Array.isArray(filter)) {
2820
+ if (filter.indexOf(node.nodeName.toLowerCase()) > -1) return true;
2821
+ } else if (typeof filter === 'function') {
2822
+ if (filter.call(rule, node, options)) return true;
2823
+ } else {
2824
+ throw new TypeError('`filter` needs to be a string, array, or function');
2825
+ }
2826
+ }
2827
+
2828
+ /**
2829
+ * The collapseWhitespace function is adapted from collapse-whitespace
2830
+ * by Luc Thevenard.
2831
+ *
2832
+ * The MIT License (MIT)
2833
+ *
2834
+ * Copyright (c) 2014 Luc Thevenard <lucthevenard@gmail.com>
2835
+ *
2836
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
2837
+ * of this software and associated documentation files (the "Software"), to deal
2838
+ * in the Software without restriction, including without limitation the rights
2839
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
2840
+ * copies of the Software, and to permit persons to whom the Software is
2841
+ * furnished to do so, subject to the following conditions:
2842
+ *
2843
+ * The above copyright notice and this permission notice shall be included in
2844
+ * all copies or substantial portions of the Software.
2845
+ *
2846
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
2847
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
2848
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
2849
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
2850
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
2851
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
2852
+ * THE SOFTWARE.
2853
+ */
2854
+
2855
+ /**
2856
+ * collapseWhitespace(options) removes extraneous whitespace from an the given element.
2857
+ *
2858
+ * @param {Object} options
2859
+ */
2860
+ function collapseWhitespace(options) {
2861
+ var element = options.element;
2862
+ var isBlock = options.isBlock;
2863
+ var isVoid = options.isVoid;
2864
+ var isPre = options.isPre || function (node) {
2865
+ return node.nodeName === 'PRE';
2866
+ };
2867
+ if (!element.firstChild || isPre(element)) return;
2868
+ var prevText = null;
2869
+ var keepLeadingWs = false;
2870
+ var prev = null;
2871
+ var node = next(prev, element, isPre);
2872
+ while (node !== element) {
2873
+ if (node.nodeType === 3 || node.nodeType === 4) {
2874
+ // Node.TEXT_NODE or Node.CDATA_SECTION_NODE
2875
+ var text = node.data.replace(/[ \r\n\t]+/g, ' ');
2876
+ if ((!prevText || / $/.test(prevText.data)) && !keepLeadingWs && text[0] === ' ') {
2877
+ text = text.substr(1);
2878
+ }
2879
+
2880
+ // `text` might be empty at this point.
2881
+ if (!text) {
2882
+ node = remove(node);
2883
+ continue;
2884
+ }
2885
+ node.data = text;
2886
+ prevText = node;
2887
+ } else if (node.nodeType === 1) {
2888
+ // Node.ELEMENT_NODE
2889
+ if (isBlock(node) || node.nodeName === 'BR') {
2890
+ if (prevText) {
2891
+ prevText.data = prevText.data.replace(/ $/, '');
2892
+ }
2893
+ prevText = null;
2894
+ keepLeadingWs = false;
2895
+ } else if (isVoid(node) || isPre(node)) {
2896
+ // Avoid trimming space around non-block, non-BR void elements and inline PRE.
2897
+ prevText = null;
2898
+ keepLeadingWs = true;
2899
+ } else if (prevText) {
2900
+ // Drop protection if set previously.
2901
+ keepLeadingWs = false;
2902
+ }
2903
+ } else {
2904
+ node = remove(node);
2905
+ continue;
2906
+ }
2907
+ var nextNode = next(prev, node, isPre);
2908
+ prev = node;
2909
+ node = nextNode;
2910
+ }
2911
+ if (prevText) {
2912
+ prevText.data = prevText.data.replace(/ $/, '');
2913
+ if (!prevText.data) {
2914
+ remove(prevText);
2915
+ }
2916
+ }
2917
+ }
2918
+
2919
+ /**
2920
+ * remove(node) removes the given node from the DOM and returns the
2921
+ * next node in the sequence.
2922
+ *
2923
+ * @param {Node} node
2924
+ * @return {Node} node
2925
+ */
2926
+ function remove(node) {
2927
+ var next = node.nextSibling || node.parentNode;
2928
+ node.parentNode.removeChild(node);
2929
+ return next;
2930
+ }
2931
+
2932
+ /**
2933
+ * next(prev, current, isPre) returns the next node in the sequence, given the
2934
+ * current and previous nodes.
2935
+ *
2936
+ * @param {Node} prev
2937
+ * @param {Node} current
2938
+ * @param {Function} isPre
2939
+ * @return {Node}
2940
+ */
2941
+ function next(prev, current, isPre) {
2942
+ if (prev && prev.parentNode === current || isPre(current)) {
2943
+ return current.nextSibling || current.parentNode;
2944
+ }
2945
+ return current.firstChild || current.nextSibling || current.parentNode;
2946
+ }
2947
+
2948
+ /*
2949
+ * Set up window for Node.js
2950
+ */
2951
+
2952
+ var root = typeof window !== 'undefined' ? window : {};
2953
+
2954
+ /*
2955
+ * Parsing HTML strings
2956
+ */
2957
+
2958
+ function canParseHTMLNatively() {
2959
+ var Parser = root.DOMParser;
2960
+ var canParse = false;
2961
+
2962
+ // Adapted from https://gist.github.com/1129031
2963
+ // Firefox/Opera/IE throw errors on unsupported types
2964
+ try {
2965
+ // WebKit returns null on unsupported types
2966
+ if (new Parser().parseFromString('', 'text/html')) {
2967
+ canParse = true;
2968
+ }
2969
+ } catch (e) {}
2970
+ return canParse;
2971
+ }
2972
+ function createHTMLParser() {
2973
+ var Parser = function () {};
2974
+ {
2975
+ var domino = require('@mixmark-io/domino');
2976
+ Parser.prototype.parseFromString = function (string) {
2977
+ return domino.createDocument(string);
2978
+ };
2979
+ }
2980
+ return Parser;
2981
+ }
2982
+ var HTMLParser = canParseHTMLNatively() ? root.DOMParser : createHTMLParser();
2983
+
2984
+ function RootNode(input, options) {
2985
+ var root;
2986
+ if (typeof input === 'string') {
2987
+ var doc = htmlParser().parseFromString(
2988
+ // DOM parsers arrange elements in the <head> and <body>.
2989
+ // Wrapping in a custom element ensures elements are reliably arranged in
2990
+ // a single element.
2991
+ '<x-turndown id="turndown-root">' + input + '</x-turndown>', 'text/html');
2992
+ root = doc.getElementById('turndown-root');
2993
+ } else {
2994
+ root = input.cloneNode(true);
2995
+ }
2996
+ collapseWhitespace({
2997
+ element: root,
2998
+ isBlock: isBlock,
2999
+ isVoid: isVoid,
3000
+ isPre: options.preformattedCode ? isPreOrCode : null
3001
+ });
3002
+ return root;
3003
+ }
3004
+ var _htmlParser;
3005
+ function htmlParser() {
3006
+ _htmlParser = _htmlParser || new HTMLParser();
3007
+ return _htmlParser;
3008
+ }
3009
+ function isPreOrCode(node) {
3010
+ return node.nodeName === 'PRE' || node.nodeName === 'CODE';
3011
+ }
3012
+
3013
+ function Node$1(node, options) {
3014
+ node.isBlock = isBlock(node);
3015
+ node.isCode = node.nodeName === 'CODE' || node.parentNode.isCode;
3016
+ node.isBlank = isBlank(node);
3017
+ node.flankingWhitespace = flankingWhitespace(node, options);
3018
+ return node;
3019
+ }
3020
+ function isBlank(node) {
3021
+ return !isVoid(node) && !isMeaningfulWhenBlank(node) && /^\s*$/i.test(node.textContent) && !hasVoid(node) && !hasMeaningfulWhenBlank(node);
3022
+ }
3023
+ function flankingWhitespace(node, options) {
3024
+ if (node.isBlock || options.preformattedCode && node.isCode) {
3025
+ return {
3026
+ leading: '',
3027
+ trailing: ''
3028
+ };
3029
+ }
3030
+ var edges = edgeWhitespace(node.textContent);
3031
+
3032
+ // abandon leading ASCII WS if left-flanked by ASCII WS
3033
+ if (edges.leadingAscii && isFlankedByWhitespace('left', node, options)) {
3034
+ edges.leading = edges.leadingNonAscii;
3035
+ }
3036
+
3037
+ // abandon trailing ASCII WS if right-flanked by ASCII WS
3038
+ if (edges.trailingAscii && isFlankedByWhitespace('right', node, options)) {
3039
+ edges.trailing = edges.trailingNonAscii;
3040
+ }
3041
+ return {
3042
+ leading: edges.leading,
3043
+ trailing: edges.trailing
3044
+ };
3045
+ }
3046
+ function edgeWhitespace(string) {
3047
+ var m = string.match(/^(([ \t\r\n]*)(\s*))(?:(?=\S)[\s\S]*\S)?((\s*?)([ \t\r\n]*))$/);
3048
+ return {
3049
+ leading: m[1],
3050
+ // whole string for whitespace-only strings
3051
+ leadingAscii: m[2],
3052
+ leadingNonAscii: m[3],
3053
+ trailing: m[4],
3054
+ // empty for whitespace-only strings
3055
+ trailingNonAscii: m[5],
3056
+ trailingAscii: m[6]
3057
+ };
3058
+ }
3059
+ function isFlankedByWhitespace(side, node, options) {
3060
+ var sibling;
3061
+ var regExp;
3062
+ var isFlanked;
3063
+ if (side === 'left') {
3064
+ sibling = node.previousSibling;
3065
+ regExp = / $/;
3066
+ } else {
3067
+ sibling = node.nextSibling;
3068
+ regExp = /^ /;
3069
+ }
3070
+ if (sibling) {
3071
+ if (sibling.nodeType === 3) {
3072
+ isFlanked = regExp.test(sibling.nodeValue);
3073
+ } else if (options.preformattedCode && sibling.nodeName === 'CODE') {
3074
+ isFlanked = false;
3075
+ } else if (sibling.nodeType === 1 && !isBlock(sibling)) {
3076
+ isFlanked = regExp.test(sibling.textContent);
3077
+ }
3078
+ }
3079
+ return isFlanked;
3080
+ }
3081
+
3082
+ var reduce = Array.prototype.reduce;
3083
+ function TurndownService(options) {
3084
+ if (!(this instanceof TurndownService)) return new TurndownService(options);
3085
+ var defaults = {
3086
+ rules: rules,
3087
+ headingStyle: 'setext',
3088
+ hr: '* * *',
3089
+ bulletListMarker: '*',
3090
+ codeBlockStyle: 'indented',
3091
+ fence: '```',
3092
+ emDelimiter: '_',
3093
+ strongDelimiter: '**',
3094
+ linkStyle: 'inlined',
3095
+ linkReferenceStyle: 'full',
3096
+ br: ' ',
3097
+ preformattedCode: false,
3098
+ blankReplacement: function (content, node) {
3099
+ return node.isBlock ? '\n\n' : '';
3100
+ },
3101
+ keepReplacement: function (content, node) {
3102
+ return node.isBlock ? '\n\n' + node.outerHTML + '\n\n' : node.outerHTML;
3103
+ },
3104
+ defaultReplacement: function (content, node) {
3105
+ return node.isBlock ? '\n\n' + content + '\n\n' : content;
3106
+ }
3107
+ };
3108
+ this.options = extend({}, defaults, options);
3109
+ this.rules = new Rules(this.options);
3110
+ }
3111
+ TurndownService.prototype = {
3112
+ /**
3113
+ * The entry point for converting a string or DOM node to Markdown
3114
+ * @public
3115
+ * @param {String|HTMLElement} input The string or DOM node to convert
3116
+ * @returns A Markdown representation of the input
3117
+ * @type String
3118
+ */
3119
+
3120
+ turndown: function (input) {
3121
+ if (!canConvert(input)) {
3122
+ throw new TypeError(input + ' is not a string, or an element/document/fragment node.');
3123
+ }
3124
+ if (input === '') return '';
3125
+ var output = process.call(this, new RootNode(input, this.options));
3126
+ return postProcess.call(this, output);
3127
+ },
3128
+ /**
3129
+ * Add one or more plugins
3130
+ * @public
3131
+ * @param {Function|Array} plugin The plugin or array of plugins to add
3132
+ * @returns The Turndown instance for chaining
3133
+ * @type Object
3134
+ */
3135
+
3136
+ use: function (plugin) {
3137
+ if (Array.isArray(plugin)) {
3138
+ for (var i = 0; i < plugin.length; i++) this.use(plugin[i]);
3139
+ } else if (typeof plugin === 'function') {
3140
+ plugin(this);
3141
+ } else {
3142
+ throw new TypeError('plugin must be a Function or an Array of Functions');
3143
+ }
3144
+ return this;
3145
+ },
3146
+ /**
3147
+ * Adds a rule
3148
+ * @public
3149
+ * @param {String} key The unique key of the rule
3150
+ * @param {Object} rule The rule
3151
+ * @returns The Turndown instance for chaining
3152
+ * @type Object
3153
+ */
3154
+
3155
+ addRule: function (key, rule) {
3156
+ this.rules.add(key, rule);
3157
+ return this;
3158
+ },
3159
+ /**
3160
+ * Keep a node (as HTML) that matches the filter
3161
+ * @public
3162
+ * @param {String|Array|Function} filter The unique key of the rule
3163
+ * @returns The Turndown instance for chaining
3164
+ * @type Object
3165
+ */
3166
+
3167
+ keep: function (filter) {
3168
+ this.rules.keep(filter);
3169
+ return this;
3170
+ },
3171
+ /**
3172
+ * Remove a node that matches the filter
3173
+ * @public
3174
+ * @param {String|Array|Function} filter The unique key of the rule
3175
+ * @returns The Turndown instance for chaining
3176
+ * @type Object
3177
+ */
3178
+
3179
+ remove: function (filter) {
3180
+ this.rules.remove(filter);
3181
+ return this;
3182
+ },
3183
+ /**
3184
+ * Escapes Markdown syntax
3185
+ * @public
3186
+ * @param {String} string The string to escape
3187
+ * @returns A string with Markdown syntax escaped
3188
+ * @type String
3189
+ */
3190
+
3191
+ escape: function (string) {
3192
+ return escapeMarkdown(string);
3193
+ }
3194
+ };
3195
+
3196
+ /**
3197
+ * Reduces a DOM node down to its Markdown string equivalent
3198
+ * @private
3199
+ * @param {HTMLElement} parentNode The node to convert
3200
+ * @returns A Markdown representation of the node
3201
+ * @type String
3202
+ */
3203
+
3204
+ function process(parentNode) {
3205
+ var self = this;
3206
+ return reduce.call(parentNode.childNodes, function (output, node) {
3207
+ node = new Node$1(node, self.options);
3208
+ var replacement = '';
3209
+ if (node.nodeType === 3) {
3210
+ replacement = node.isCode ? node.nodeValue : self.escape(node.nodeValue);
3211
+ } else if (node.nodeType === 1) {
3212
+ replacement = replacementForNode.call(self, node);
3213
+ }
3214
+ return join(output, replacement);
3215
+ }, '');
3216
+ }
3217
+
3218
+ /**
3219
+ * Appends strings as each rule requires and trims the output
3220
+ * @private
3221
+ * @param {String} output The conversion output
3222
+ * @returns A trimmed version of the ouput
3223
+ * @type String
3224
+ */
3225
+
3226
+ function postProcess(output) {
3227
+ var self = this;
3228
+ this.rules.forEach(function (rule) {
3229
+ if (typeof rule.append === 'function') {
3230
+ output = join(output, rule.append(self.options));
3231
+ }
3232
+ });
3233
+ return output.replace(/^[\t\r\n]+/, '').replace(/[\t\r\n\s]+$/, '');
3234
+ }
3235
+
3236
+ /**
3237
+ * Converts an element node to its Markdown equivalent
3238
+ * @private
3239
+ * @param {HTMLElement} node The node to convert
3240
+ * @returns A Markdown representation of the node
3241
+ * @type String
3242
+ */
3243
+
3244
+ function replacementForNode(node) {
3245
+ var rule = this.rules.forNode(node);
3246
+ var content = process.call(this, node);
3247
+ var whitespace = node.flankingWhitespace;
3248
+ if (whitespace.leading || whitespace.trailing) content = content.trim();
3249
+ return whitespace.leading + rule.replacement(content, node, this.options) + whitespace.trailing;
3250
+ }
3251
+
3252
+ /**
3253
+ * Joins replacement to the current output with appropriate number of new lines
3254
+ * @private
3255
+ * @param {String} output The current conversion output
3256
+ * @param {String} replacement The string to append to the output
3257
+ * @returns Joined output
3258
+ * @type String
3259
+ */
3260
+
3261
+ function join(output, replacement) {
3262
+ var s1 = trimTrailingNewlines(output);
3263
+ var s2 = trimLeadingNewlines(replacement);
3264
+ var nls = Math.max(output.length - s1.length, replacement.length - s2.length);
3265
+ var separator = '\n\n'.substring(0, nls);
3266
+ return s1 + separator + s2;
3267
+ }
3268
+
3269
+ /**
3270
+ * Determines whether an input can be converted
3271
+ * @private
3272
+ * @param {String|HTMLElement} input Describe this parameter
3273
+ * @returns Describe what it returns
3274
+ * @type String|Object|Array|Boolean|Number
3275
+ */
3276
+
3277
+ function canConvert(input) {
3278
+ return input != null && (typeof input === 'string' || input.nodeType && (input.nodeType === 1 || input.nodeType === 9 || input.nodeType === 11));
3279
+ }
3280
+
3281
+ var css_248z = i`* {
3282
+ box-sizing: border-box;
3283
+ -webkit-tap-highlight-color: transparent;
3284
+ }
3285
+
3286
+ .screen-reader-only {
3287
+ display: none !important;
3288
+ }
3289
+
3290
+ [hidden] {
3291
+ display: none !important;
3292
+ }
3293
+
3294
+ :host {
3295
+ display: block;
3296
+ width: 100%;
3297
+ position: relative;
3298
+ }
3299
+
3300
+ .markdown-editor-field {
3301
+ --field-height: auto;
3302
+ --field-padding-block: 0;
3303
+ --code-editor-height: var(--markdown-editor-min-height, 12rem);
3304
+ width: 100%;
3305
+ }
3306
+
3307
+ .markdown-editor-content {
3308
+ min-height: var(--markdown-editor-min-height, 12rem);
3309
+ padding: var(--spacing-200, 1rem) var(--spacing-200, 1rem) var(--spacing-200, 1rem) 2.5rem;
3310
+ outline: none;
3311
+ color: var(--color-on-surface, #1c1b1f);
3312
+ font-family: var(--typography-body-large-font-family, inherit);
3313
+ font-size: var(--typography-body-large-font-size, 1rem);
3314
+ line-height: var(--typography-body-large-line-height, 1.6);
3315
+ cursor: text;
3316
+ word-break: break-word;
3317
+ overflow-wrap: break-word;
3318
+ }
3319
+ .markdown-editor-content.hidden {
3320
+ display: none;
3321
+ }
3322
+ .markdown-editor-content .tiptap-root,
3323
+ .markdown-editor-content .ProseMirror {
3324
+ outline: none;
3325
+ min-height: calc(var(--markdown-editor-min-height, 12rem) - 2rem);
3326
+ }
3327
+ .markdown-editor-content .ProseMirror p.is-editor-empty:first-child::before {
3328
+ content: attr(data-placeholder);
3329
+ color: var(--color-on-surface-variant, #49454f);
3330
+ opacity: 0.55;
3331
+ pointer-events: none;
3332
+ float: left;
3333
+ height: 0;
3334
+ }
3335
+ .markdown-editor-content .ProseMirror h1 {
3336
+ font-size: 1.875rem;
3337
+ font-weight: 700;
3338
+ line-height: 1.25;
3339
+ margin: 1.4rem 0 0.4rem;
3340
+ }
3341
+ .markdown-editor-content .ProseMirror h2 {
3342
+ font-size: 1.5rem;
3343
+ font-weight: 700;
3344
+ line-height: 1.3;
3345
+ margin: 1.2rem 0 0.35rem;
3346
+ }
3347
+ .markdown-editor-content .ProseMirror h3 {
3348
+ font-size: 1.25rem;
3349
+ font-weight: 600;
3350
+ line-height: 1.35;
3351
+ margin: 1rem 0 0.3rem;
3352
+ }
3353
+ .markdown-editor-content .ProseMirror p {
3354
+ margin: 0.25rem 0;
3355
+ }
3356
+ .markdown-editor-content .ProseMirror ul,
3357
+ .markdown-editor-content .ProseMirror ol {
3358
+ padding-inline-start: 1.5rem;
3359
+ margin: 0.35rem 0;
3360
+ }
3361
+ .markdown-editor-content .ProseMirror li > p {
3362
+ margin: 0.1rem 0;
3363
+ }
3364
+ .markdown-editor-content .ProseMirror blockquote {
3365
+ margin: 0.6rem 0;
3366
+ padding: 0.25rem 0 0.25rem 0.85rem;
3367
+ border-inline-start: 3px solid var(--color-outline-variant, #cac4d0);
3368
+ color: var(--color-on-surface-variant, #49454f);
3369
+ }
3370
+ .markdown-editor-content .ProseMirror pre {
3371
+ background: var(--color-surface-container-high, #ece6f0);
3372
+ color: var(--color-on-surface, #1c1b1f);
3373
+ padding: 0.75rem 1rem;
3374
+ border-radius: var(--shape-corner-small, 0.5rem);
3375
+ font-family: var(--typography-code-font-family, monospace);
3376
+ font-size: 0.85rem;
3377
+ line-height: 1.5;
3378
+ overflow-x: auto;
3379
+ margin: 0.6rem 0;
3380
+ }
3381
+ .markdown-editor-content .ProseMirror code {
3382
+ font-family: var(--typography-code-font-family, monospace);
3383
+ font-size: 0.85em;
3384
+ background: color-mix(in srgb, var(--color-on-surface, #1c1b1f) 8%, transparent);
3385
+ padding: 0.1em 0.35em;
3386
+ border-radius: var(--shape-corner-extra-small, 0.25rem);
3387
+ }
3388
+ .markdown-editor-content .ProseMirror pre code {
3389
+ background: transparent;
3390
+ padding: 0;
3391
+ border-radius: 0;
3392
+ }
3393
+ .markdown-editor-content .ProseMirror hr {
3394
+ border: none;
3395
+ border-top: 1px solid var(--color-outline-variant, #cac4d0);
3396
+ margin: 1rem 0;
3397
+ }
3398
+ .markdown-editor-content .ProseMirror a {
3399
+ color: var(--color-primary, #6750a4);
3400
+ text-decoration: underline;
3401
+ }
3402
+ .markdown-editor-content .ProseMirror strong,
3403
+ .markdown-editor-content .ProseMirror b {
3404
+ font-weight: 600;
3405
+ }
3406
+
3407
+ .markdown-source.hidden {
3408
+ display: none;
3409
+ }
3410
+
3411
+ .mode-switcher {
3412
+ display: flex;
3413
+ justify-content: flex-end;
3414
+ padding: var(--spacing-050, 0.25rem) var(--spacing-100, 0.5rem) var(--spacing-075, 0.375rem);
3415
+ border-block-start: 1px solid var(--color-outline-variant, #cac4d0);
3416
+ }
3417
+
3418
+ .bubble-menu {
3419
+ position: fixed;
3420
+ z-index: 50;
3421
+ display: none;
3422
+ align-items: center;
3423
+ gap: var(--spacing-025, 0.125rem);
3424
+ padding: var(--spacing-025, 0.125rem);
3425
+ background: var(--markdown-editor-bubble-background, var(--color-surface-container-highest, #e6e0e9));
3426
+ border: 1px solid var(--color-outline-variant, #cac4d0);
3427
+ border-radius: var(--shape-corner-small, 0.5rem);
3428
+ box-shadow: var(--elevation-2, 0 2px 6px rgba(0, 0, 0, 0.12), 0 1px 2px rgba(0, 0, 0, 0.08));
3429
+ }
3430
+ .bubble-menu.open {
3431
+ display: inline-flex;
3432
+ }
3433
+
3434
+ .slash-menu {
3435
+ position: fixed;
3436
+ z-index: 50;
3437
+ display: none;
3438
+ flex-direction: column;
3439
+ min-width: 14rem;
3440
+ max-height: 18rem;
3441
+ overflow-y: auto;
3442
+ padding: var(--spacing-050, 0.25rem);
3443
+ background: var(--markdown-editor-slash-background, var(--color-surface-container-highest, #e6e0e9));
3444
+ border: 1px solid var(--color-outline-variant, #cac4d0);
3445
+ border-radius: var(--shape-corner-small, 0.5rem);
3446
+ box-shadow: var(--elevation-2, 0 4px 10px rgba(0, 0, 0, 0.14), 0 1px 3px rgba(0, 0, 0, 0.08));
3447
+ }
3448
+ .slash-menu.open {
3449
+ display: flex;
3450
+ }
3451
+
3452
+ .slash-item {
3453
+ display: flex;
3454
+ align-items: center;
3455
+ gap: var(--spacing-100, 0.5rem);
3456
+ padding: var(--spacing-075, 0.375rem) var(--spacing-100, 0.5rem);
3457
+ border: none;
3458
+ background: transparent;
3459
+ border-radius: var(--shape-corner-extra-small, 0.25rem);
3460
+ cursor: pointer;
3461
+ color: var(--color-on-surface, #1c1b1f);
3462
+ font-size: 0.875rem;
3463
+ text-align: start;
3464
+ }
3465
+ .slash-item:hover, .slash-item.active {
3466
+ background: color-mix(in srgb, var(--color-primary, #6750a4) 12%, transparent);
3467
+ }
3468
+ .slash-item .slash-item-label {
3469
+ font-weight: 500;
3470
+ }
3471
+ .slash-item .slash-item-hint {
3472
+ margin-inline-start: auto;
3473
+ color: var(--color-on-surface-variant, #49454f);
3474
+ font-size: 0.75rem;
3475
+ opacity: 0.75;
3476
+ }
3477
+
3478
+ .toolbar-btn {
3479
+ display: inline-flex;
3480
+ align-items: center;
3481
+ justify-content: center;
3482
+ width: 1.75rem;
3483
+ height: 1.75rem;
3484
+ padding: 0;
3485
+ border: none;
3486
+ border-radius: var(--shape-corner-extra-small, 0.25rem);
3487
+ background: transparent;
3488
+ color: var(--color-on-surface-variant, #49454f);
3489
+ cursor: pointer;
3490
+ transition: background 120ms ease, color 120ms ease;
3491
+ }
3492
+ .toolbar-btn:hover:not(:disabled) {
3493
+ background: color-mix(in srgb, var(--color-on-surface-variant, #49454f) 10%, transparent);
3494
+ }
3495
+ .toolbar-btn.active {
3496
+ background: color-mix(in srgb, var(--color-primary, #6750a4) 16%, transparent);
3497
+ color: var(--color-primary, #6750a4);
3498
+ }
3499
+ .toolbar-btn:disabled {
3500
+ opacity: 0.38;
3501
+ cursor: not-allowed;
3502
+ }
3503
+ .toolbar-btn wc-icon {
3504
+ pointer-events: none;
3505
+ }
3506
+
3507
+ .block-handle {
3508
+ position: fixed;
3509
+ z-index: 50;
3510
+ display: none;
3511
+ flex-direction: column;
3512
+ gap: var(--spacing-025, 0.125rem);
3513
+ }
3514
+ .block-handle.visible {
3515
+ display: flex;
3516
+ }
3517
+
3518
+ .block-handle-btn {
3519
+ display: inline-flex;
3520
+ align-items: center;
3521
+ justify-content: center;
3522
+ width: 1.75rem;
3523
+ height: 1.75rem;
3524
+ padding: 0;
3525
+ border: 1px solid var(--color-outline-variant, #cac4d0);
3526
+ border-radius: var(--shape-corner-extra-small, 0.25rem);
3527
+ background: var(--color-surface-container-highest, #e6e0e9);
3528
+ color: var(--color-on-surface-variant, #49454f);
3529
+ cursor: pointer;
3530
+ transition: background 120ms ease, color 120ms ease;
3531
+ }
3532
+ .block-handle-btn:hover:not(:disabled) {
3533
+ background: color-mix(in srgb, var(--color-on-surface-variant, #49454f) 12%, transparent);
3534
+ }
3535
+ .block-handle-btn:disabled {
3536
+ opacity: 0.38;
3537
+ cursor: not-allowed;
3538
+ }
3539
+ .block-handle-btn.drag-btn {
3540
+ cursor: grab;
3541
+ }
3542
+ .block-handle-btn.drag-btn:active {
3543
+ cursor: grabbing;
3544
+ }
3545
+ .block-handle-btn wc-icon {
3546
+ pointer-events: none;
3547
+ }
3548
+
3549
+ .ProseMirror-dropcursor {
3550
+ border-top: 2px solid var(--color-primary, #6750a4) !important;
3551
+ }
3552
+
3553
+ .read-only-tag {
3554
+ margin: var(--spacing-050, 0.25rem);
3555
+ }
3556
+
3557
+ :host([disabled]) .markdown-editor-content,
3558
+ :host([readonly]) .markdown-editor-content {
3559
+ cursor: not-allowed;
3560
+ opacity: 0.6;
3561
+ }
3562
+
3563
+ :host([disabled]) .markdown-source,
3564
+ :host([readonly]) .markdown-source {
3565
+ opacity: 0.7;
3566
+ }`;
3567
+
3568
+ var MarkdownEditor_1;
3569
+ const SLASH_ITEMS = [
3570
+ {
3571
+ title: 'Heading 1',
3572
+ hint: '#',
3573
+ icon: 'title',
3574
+ command: ({ editor, range }) => editor
3575
+ .chain()
3576
+ .focus()
3577
+ .deleteRange(range)
3578
+ .setNode('heading', { level: 1 })
3579
+ .run(),
3580
+ },
3581
+ {
3582
+ title: 'Heading 2',
3583
+ hint: '##',
3584
+ icon: 'title',
3585
+ command: ({ editor, range }) => editor
3586
+ .chain()
3587
+ .focus()
3588
+ .deleteRange(range)
3589
+ .setNode('heading', { level: 2 })
3590
+ .run(),
3591
+ },
3592
+ {
3593
+ title: 'Heading 3',
3594
+ hint: '###',
3595
+ icon: 'title',
3596
+ command: ({ editor, range }) => editor
3597
+ .chain()
3598
+ .focus()
3599
+ .deleteRange(range)
3600
+ .setNode('heading', { level: 3 })
3601
+ .run(),
3602
+ },
3603
+ {
3604
+ title: 'Bulleted list',
3605
+ hint: '-',
3606
+ icon: 'format_list_bulleted',
3607
+ command: ({ editor, range }) => editor.chain().focus().deleteRange(range).toggleBulletList().run(),
3608
+ },
3609
+ {
3610
+ title: 'Numbered list',
3611
+ hint: '1.',
3612
+ icon: 'format_list_numbered',
3613
+ command: ({ editor, range }) => editor.chain().focus().deleteRange(range).toggleOrderedList().run(),
3614
+ },
3615
+ {
3616
+ title: 'Quote',
3617
+ hint: '>',
3618
+ icon: 'format_quote',
3619
+ command: ({ editor, range }) => editor.chain().focus().deleteRange(range).toggleBlockquote().run(),
3620
+ },
3621
+ {
3622
+ title: 'Code block',
3623
+ hint: '```',
3624
+ icon: 'code',
3625
+ command: ({ editor, range }) => editor.chain().focus().deleteRange(range).toggleCodeBlock().run(),
3626
+ },
3627
+ {
3628
+ title: 'Divider',
3629
+ hint: '---',
3630
+ icon: 'horizontal_rule',
3631
+ command: ({ editor, range }) => editor.chain().focus().deleteRange(range).setHorizontalRule().run(),
3632
+ },
3633
+ ];
3634
+ /**
3635
+ * @label Markdown Editor
3636
+ * @tag wc-markdown-editor
3637
+ * @rawTag markdown-editor
3638
+ *
3639
+ * @summary A Tiptap-powered Notion-like Markdown editor with a bottom toggle
3640
+ * between rendered and raw markdown views.
3641
+ * @overview
3642
+ * <p>The Markdown Editor provides a block-based, Notion-like writing surface
3643
+ * built on Tiptap. Type <code>/</code> to open a slash menu for inserting
3644
+ * headings, lists, quotes, code blocks, and dividers. Select text to reveal
3645
+ * a floating bubble toolbar with inline formatting actions.</p>
3646
+ *
3647
+ * <p>The canonical <code>value</code> is Markdown. Use the bottom segmented
3648
+ * switch to toggle between the rendered editor and the raw markdown source.
3649
+ * The component dispatches a <code>change</code> event whenever content
3650
+ * changes.</p>
3651
+ *
3652
+ * @cssprop --markdown-editor-min-height - Minimum height of the editable area. Defaults to 12rem.
3653
+ * @cssprop --markdown-editor-bubble-background - Background color of the selection bubble menu.
3654
+ * @cssprop --markdown-editor-slash-background - Background color of the slash command menu.
3655
+ *
3656
+ * @fires {Event} change - Fired whenever the markdown content changes.
3657
+ *
3658
+ * @example
3659
+ * ```html
3660
+ * <wc-markdown-editor
3661
+ * label="Notes"
3662
+ * value="# Hello\n\nType a slash on a new line to insert blocks."
3663
+ * ></wc-markdown-editor>
3664
+ * ```
3665
+ * @tags input editor
3666
+ */
3667
+ let MarkdownEditor = MarkdownEditor_1 = class MarkdownEditor extends BaseInput {
3668
+ constructor() {
3669
+ // ── Static ────────────────────────────────────────────────────────────────
3670
+ super(...arguments);
3671
+ // ── Properties ────────────────────────────────────────────────────────────
3672
+ /** Current Markdown value of the editor. */
3673
+ this.value = '';
3674
+ /** Label displayed above the editor. */
3675
+ this.label = '';
3676
+ /** Placeholder text shown when the editor is empty. */
3677
+ this.placeholder = "Type '/' for commands…";
3678
+ /** Visual style of the wrapping field. */
3679
+ this.variant = 'default';
3680
+ /** Helper text displayed below the editor. */
3681
+ this.helperText = '';
3682
+ /** Whether to show an error state. */
3683
+ this.error = false;
3684
+ /** Error message text. */
3685
+ this.errorText = '';
3686
+ /** Debounce in milliseconds for dispatching `change`. */
3687
+ this.debounce = 250;
3688
+ // ── State ─────────────────────────────────────────────────────────────────
3689
+ /** Whether the editor currently has focus. */
3690
+ this._focused = false;
3691
+ /** Current view mode: rendered editor or raw markdown. */
3692
+ this._mode = 'editor';
3693
+ /** Whether the bubble toolbar is visible. */
3694
+ this._bubbleOpen = false;
3695
+ /** Whether the slash command menu is visible. */
3696
+ this._slashOpen = false;
3697
+ /** Filtered slash menu items. */
3698
+ this._slashItems = [];
3699
+ /** Currently highlighted slash menu index. */
3700
+ this._slashIndex = 0;
3701
+ /** Whether the block handle panel is visible. */
3702
+ this._blockHandleVisible = false;
3703
+ /** Most recent slash-suggestion bounding rect (for popup placement). */
3704
+ this._slashClientRect = null;
3705
+ /** ProseMirror doc position (inside-block) of the block under the handle. */
3706
+ this._blockHandleNodePos = -1;
3707
+ /** Reusable Turndown serializer instance. */
3708
+ this._turndown = new TurndownService({
3709
+ headingStyle: 'atx',
3710
+ codeBlockStyle: 'fenced',
3711
+ bulletListMarker: '-',
3712
+ emDelimiter: '_',
3713
+ });
3714
+ this._focusEditorOnContainerClick = (event) => {
3715
+ if (!this._editor)
3716
+ return;
3717
+ if (event.target === this._editorEl) {
3718
+ this._editor.commands.focus('end');
3719
+ }
3720
+ };
3721
+ this._onSlashItemClick = (event) => {
3722
+ event.preventDefault();
3723
+ const target = event.currentTarget ?? null;
3724
+ if (!target)
3725
+ return;
3726
+ const index = Number(target.dataset.index ?? '-1');
3727
+ const item = this._slashItems[index];
3728
+ if (item && this._slashCommand) {
3729
+ this._slashCommand(item);
3730
+ }
3731
+ };
3732
+ this._onBlockHandleMouseEnter = () => {
3733
+ window.clearTimeout(this._blockHandleHideTimeout);
3734
+ this._blockHandleHideTimeout = undefined;
3735
+ };
3736
+ this._onBlockHandleMouseLeave = (event) => {
3737
+ const rel = event.relatedTarget;
3738
+ if (this._editorEl?.contains(rel))
3739
+ return;
3740
+ window.clearTimeout(this._blockHandleHideTimeout);
3741
+ this._blockHandleHideTimeout = window.setTimeout(() => {
3742
+ this._blockHandleVisible = false;
3743
+ }, 150);
3744
+ };
3745
+ this._onInsertBlockClick = () => {
3746
+ if (!this._editor || this.disabled || this.readonly)
3747
+ return;
3748
+ const { view } = this._editor;
3749
+ const { state } = view;
3750
+ try {
3751
+ const $pos = state.doc.resolve(this._blockHandleNodePos);
3752
+ const nodeEnd = $pos.after(1);
3753
+ const safePos = Math.min(nodeEnd - 1, state.doc.content.size - 1);
3754
+ const coords = view.coordsAtPos(safePos);
3755
+ const rect = new DOMRect(coords.left, coords.bottom, 0, 0);
3756
+ this._slashItems = [...SLASH_ITEMS];
3757
+ this._slashIndex = 0;
3758
+ this._slashClientRect = () => rect;
3759
+ this._slashCommand = item => {
3760
+ if (!this._editor)
3761
+ return;
3762
+ const end = nodeEnd;
3763
+ this._editor
3764
+ .chain()
3765
+ .focus()
3766
+ .insertContentAt(end, { type: 'paragraph' })
3767
+ .setTextSelection(end + 1)
3768
+ .run();
3769
+ const { from } = this._editor.state.selection;
3770
+ item.command({ editor: this._editor, range: { from, to: from } });
3771
+ this._slashOpen = false;
3772
+ this._slashClientRect = null;
3773
+ this._slashCommand = undefined;
3774
+ };
3775
+ this._slashOpen = true;
3776
+ this._positionSlashMenu();
3777
+ }
3778
+ catch { /* ignore */ }
3779
+ };
3780
+ this._onDragHandleMouseDown = (event) => {
3781
+ event.preventDefault();
3782
+ if (!this._editor)
3783
+ return;
3784
+ const { view } = this._editor;
3785
+ const { state } = view;
3786
+ try {
3787
+ const $pos = state.doc.resolve(this._blockHandleNodePos);
3788
+ const nodePos = $pos.depth > 0 ? $pos.before(1) : this._blockHandleNodePos;
3789
+ const sel = NodeSelection.create(state.doc, nodePos);
3790
+ view.dispatch(state.tr.setSelection(sel));
3791
+ }
3792
+ catch { /* ignore */ }
3793
+ };
3794
+ this._onDragHandleDragStart = (event) => {
3795
+ if (!this._editor || !event.dataTransfer)
3796
+ return;
3797
+ const { view } = this._editor;
3798
+ const { state } = view;
3799
+ try {
3800
+ const $pos = state.doc.resolve(this._blockHandleNodePos);
3801
+ const nodePos = $pos.depth > 0 ? $pos.before(1) : this._blockHandleNodePos;
3802
+ const node = state.doc.nodeAt(nodePos);
3803
+ if (!node)
3804
+ return;
3805
+ const slice = new Slice(Fragment.from(node), 0, 0);
3806
+ const container = document.createElement('div');
3807
+ container.appendChild(DOMSerializer.fromSchema(state.schema).serializeFragment(slice.content));
3808
+ event.dataTransfer.clearData();
3809
+ event.dataTransfer.setData('text/html', container.innerHTML);
3810
+ event.dataTransfer.setData('text/plain', container.textContent ?? '');
3811
+ event.dataTransfer.effectAllowed = 'move';
3812
+ view.dragging = { slice, move: true };
3813
+ }
3814
+ catch { /* ignore */ }
3815
+ };
3816
+ this._onDragHandleDragEnd = () => {
3817
+ if (this._editor)
3818
+ this._editor.view.dragging = null;
3819
+ };
3820
+ this._switchMode = (event) => {
3821
+ event.stopPropagation();
3822
+ const nextMode = event.detail?.value === 'markdown' ? 'markdown' : 'editor';
3823
+ if (nextMode === this._mode)
3824
+ return;
3825
+ if (nextMode === 'markdown' && this._editor) {
3826
+ const nextMd = MarkdownEditor_1._normalizeMd(this._htmlToMarkdown(this._editor.getHTML()));
3827
+ if (nextMd !== this.value) {
3828
+ this.value = nextMd;
3829
+ }
3830
+ this._bubbleOpen = false;
3831
+ }
3832
+ this._mode = nextMode;
3833
+ };
3834
+ this._handleSourceChange = (event) => {
3835
+ event.stopPropagation();
3836
+ const target = event.currentTarget;
3837
+ const nextValue = target.value ?? '';
3838
+ if (nextValue === this.value)
3839
+ return;
3840
+ this.value = nextValue;
3841
+ this._dispatchDebouncedChange();
3842
+ };
3843
+ }
3844
+ // ── Lifecycle ─────────────────────────────────────────────────────────────
3845
+ firstUpdated() {
3846
+ this._initializeEditor();
3847
+ }
3848
+ disconnectedCallback() {
3849
+ super.disconnectedCallback();
3850
+ if (this._changeTimeout) {
3851
+ window.clearTimeout(this._changeTimeout);
3852
+ this._changeTimeout = undefined;
3853
+ }
3854
+ if (this._blockHandleHideTimeout) {
3855
+ window.clearTimeout(this._blockHandleHideTimeout);
3856
+ this._blockHandleHideTimeout = undefined;
3857
+ }
3858
+ this._destroyEditor();
3859
+ }
3860
+ updated(changed) {
3861
+ if (changed.has('value') && this._editor) {
3862
+ const currentMd = MarkdownEditor_1._normalizeMd(this._htmlToMarkdown(this._editor.getHTML()));
3863
+ const nextMd = MarkdownEditor_1._normalizeMd(this.value);
3864
+ if (currentMd !== nextMd) {
3865
+ this._editor.commands.setContent(this._markdownToHtml(this.value), false);
3866
+ }
3867
+ }
3868
+ if ((changed.has('disabled') || changed.has('readonly')) && this._editor) {
3869
+ this._editor.setEditable(!(this.disabled || this.readonly));
3870
+ }
3871
+ if (changed.has('placeholder') && this._editor) {
3872
+ this._destroyEditor();
3873
+ this._initializeEditor();
3874
+ }
3875
+ }
3876
+ // ── Private methods: conversion ───────────────────────────────────────────
3877
+ static _normalizeMd(value) {
3878
+ return (value ?? '').replace(/\r\n/g, '\n').replace(/\s+$/g, '');
3879
+ }
3880
+ _markdownToHtml(md) {
3881
+ return marked.parse(md ?? '', {
3882
+ gfm: true,
3883
+ breaks: true,
3884
+ async: false,
3885
+ });
3886
+ }
3887
+ _htmlToMarkdown(htmlStr) {
3888
+ return this._turndown.turndown(htmlStr ?? '');
3889
+ }
3890
+ // ── Private methods: TipTap setup ─────────────────────────────────────────
3891
+ _destroyEditor() {
3892
+ if (!this._editor)
3893
+ return;
3894
+ this._editorEl?.removeEventListener('click', this._focusEditorOnContainerClick);
3895
+ this._editor.destroy();
3896
+ this._editor = undefined;
3897
+ }
3898
+ _initializeEditor() {
3899
+ if (!this._editorEl || this._editor)
3900
+ return;
3901
+ this._editor = new Editor({
3902
+ element: this._editorEl,
3903
+ extensions: [
3904
+ StarterKit,
3905
+ Underline,
3906
+ Placeholder.configure({
3907
+ placeholder: this.placeholder,
3908
+ }),
3909
+ this._buildSlashExtension(),
3910
+ this._buildBlockHandleExtension(),
3911
+ ],
3912
+ content: this._markdownToHtml(this.value),
3913
+ editable: !(this.disabled || this.readonly),
3914
+ onFocus: () => {
3915
+ this._focused = true;
3916
+ },
3917
+ onBlur: () => {
3918
+ this._focused = false;
3919
+ window.setTimeout(() => {
3920
+ this._bubbleOpen = false;
3921
+ }, 150);
3922
+ },
3923
+ onUpdate: () => {
3924
+ if (!this._editor)
3925
+ return;
3926
+ const nextMd = MarkdownEditor_1._normalizeMd(this._htmlToMarkdown(this._editor.getHTML()));
3927
+ if (nextMd !== this.value) {
3928
+ this.value = nextMd;
3929
+ }
3930
+ this._dispatchDebouncedChange();
3931
+ },
3932
+ onSelectionUpdate: () => {
3933
+ this._updateBubbleMenu();
3934
+ },
3935
+ });
3936
+ this._editorEl.addEventListener('click', this._focusEditorOnContainerClick);
3937
+ }
3938
+ // ── Private methods: slash command ────────────────────────────────────────
3939
+ _buildSlashExtension() {
3940
+ const host = this;
3941
+ return Extension.create({
3942
+ name: 'slashCommand',
3943
+ addProseMirrorPlugins() {
3944
+ return [
3945
+ Suggestion({
3946
+ editor: this.editor,
3947
+ char: '/',
3948
+ startOfLine: false,
3949
+ allowSpaces: false,
3950
+ items: ({ query: slashQuery }) => {
3951
+ const q = slashQuery.toLowerCase();
3952
+ return SLASH_ITEMS.filter(item => item.title.toLowerCase().includes(q)).slice(0, 10);
3953
+ },
3954
+ command: ({ editor, range, props }) => {
3955
+ props.command({ editor, range });
3956
+ },
3957
+ render: () => ({
3958
+ onStart: props => {
3959
+ host._slashItems = props.items;
3960
+ host._slashIndex = 0;
3961
+ host._slashClientRect =
3962
+ props.clientRect;
3963
+ host._slashCommand = item => {
3964
+ props.command({
3965
+ ...item,
3966
+ command: item.command,
3967
+ });
3968
+ };
3969
+ host._slashOpen = props.items.length > 0;
3970
+ host._positionSlashMenu();
3971
+ },
3972
+ onUpdate: props => {
3973
+ host._slashItems = props.items;
3974
+ host._slashIndex = 0;
3975
+ host._slashClientRect =
3976
+ props.clientRect;
3977
+ host._slashOpen = props.items.length > 0;
3978
+ host._positionSlashMenu();
3979
+ },
3980
+ onKeyDown: ({ event }) => {
3981
+ if (!host._slashOpen)
3982
+ return false;
3983
+ if (event.key === 'ArrowDown') {
3984
+ host._slashIndex =
3985
+ (host._slashIndex + 1) % host._slashItems.length;
3986
+ return true;
3987
+ }
3988
+ if (event.key === 'ArrowUp') {
3989
+ host._slashIndex =
3990
+ (host._slashIndex - 1 + host._slashItems.length) %
3991
+ host._slashItems.length;
3992
+ return true;
3993
+ }
3994
+ if (event.key === 'Enter') {
3995
+ const item = host._slashItems[host._slashIndex];
3996
+ if (item && host._slashCommand) {
3997
+ host._slashCommand(item);
3998
+ }
3999
+ return true;
4000
+ }
4001
+ if (event.key === 'Escape') {
4002
+ host._slashOpen = false;
4003
+ return true;
4004
+ }
4005
+ return false;
4006
+ },
4007
+ onExit: () => {
4008
+ host._slashOpen = false;
4009
+ host._slashClientRect = null;
4010
+ host._slashCommand = undefined;
4011
+ },
4012
+ }),
4013
+ }),
4014
+ ];
4015
+ },
4016
+ });
4017
+ }
4018
+ async _positionSlashMenu() {
4019
+ await this.updateComplete;
4020
+ if (!this._slashEl || !this._slashClientRect)
4021
+ return;
4022
+ const rect = this._slashClientRect();
4023
+ if (!rect)
4024
+ return;
4025
+ const virtual = {
4026
+ getBoundingClientRect: () => rect,
4027
+ };
4028
+ const { x, y } = await computePosition(virtual, this._slashEl, {
4029
+ placement: 'bottom-start',
4030
+ strategy: 'fixed',
4031
+ middleware: [offset(6), flip(), shift({ padding: 8 })],
4032
+ });
4033
+ this._slashEl.style.left = `${x}px`;
4034
+ this._slashEl.style.top = `${y}px`;
4035
+ }
4036
+ // ── Private methods: block handle ─────────────────────────────────────────
4037
+ _buildBlockHandleExtension() {
4038
+ const host = this;
4039
+ return Extension.create({
4040
+ name: 'blockHandle',
4041
+ addProseMirrorPlugins() {
4042
+ return [
4043
+ new Plugin({
4044
+ props: {
4045
+ handleDOMEvents: {
4046
+ mousemove: (view, event) => {
4047
+ if (host.disabled || host.readonly || host._mode !== 'editor') {
4048
+ host._blockHandleVisible = false;
4049
+ return false;
4050
+ }
4051
+ const coords = view.posAtCoords({
4052
+ left: event.clientX,
4053
+ top: event.clientY,
4054
+ });
4055
+ if (!coords) {
4056
+ host._blockHandleVisible = false;
4057
+ return false;
4058
+ }
4059
+ try {
4060
+ // Store the inside-block position (not before(1)) so that
4061
+ // domAtPos() resolves to the block element, not its parent.
4062
+ host._blockHandleNodePos = coords.pos;
4063
+ window.clearTimeout(host._blockHandleHideTimeout);
4064
+ host._blockHandleHideTimeout = undefined;
4065
+ host._blockHandleVisible = true;
4066
+ host._positionBlockHandle();
4067
+ }
4068
+ catch {
4069
+ host._blockHandleVisible = false;
4070
+ }
4071
+ return false;
4072
+ },
4073
+ mouseleave: (_view, event) => {
4074
+ const rel = event.relatedTarget;
4075
+ if (host._blockHandleEl?.contains(rel) ||
4076
+ rel === host._blockHandleEl)
4077
+ return false;
4078
+ // Delay so the mouse can travel to the handle without it vanishing.
4079
+ window.clearTimeout(host._blockHandleHideTimeout);
4080
+ host._blockHandleHideTimeout = window.setTimeout(() => {
4081
+ host._blockHandleVisible = false;
4082
+ }, 400);
4083
+ return false;
4084
+ },
4085
+ },
4086
+ },
4087
+ }),
4088
+ ];
4089
+ },
4090
+ });
4091
+ }
4092
+ _positionBlockHandle() {
4093
+ if (!this._editor || !this._blockHandleEl)
4094
+ return;
4095
+ const { view } = this._editor;
4096
+ const pos = this._blockHandleNodePos;
4097
+ if (pos < 0)
4098
+ return;
4099
+ try {
4100
+ const domRef = view.domAtPos(pos);
4101
+ let el = domRef.node.nodeType === Node.TEXT_NODE
4102
+ ? domRef.node.parentElement
4103
+ : domRef.node;
4104
+ while (el && el !== view.dom) {
4105
+ const d = getComputedStyle(el).display;
4106
+ if (d === 'block' || d === 'list-item')
4107
+ break;
4108
+ el = el.parentElement;
4109
+ }
4110
+ if (!el || el === view.dom) {
4111
+ this._blockHandleVisible = false;
4112
+ return;
4113
+ }
4114
+ const blockRect = el.getBoundingClientRect();
4115
+ // Use .markdown-editor-content (grandparent of .ProseMirror) as the
4116
+ // left anchor so the handle sits inside the left padding area and is
4117
+ // never clipped by a sidebar or page margin.
4118
+ const contentEl = view.dom.parentElement?.parentElement;
4119
+ const contentLeft = contentEl
4120
+ ? contentEl.getBoundingClientRect().left
4121
+ : view.dom.getBoundingClientRect().left - 16;
4122
+ const handleH = this._blockHandleEl.offsetHeight || 60;
4123
+ const top = blockRect.top + blockRect.height / 2 - handleH / 2;
4124
+ const left = contentLeft + 4;
4125
+ this._blockHandleEl.style.top = `${top}px`;
4126
+ this._blockHandleEl.style.left = `${left}px`;
4127
+ }
4128
+ catch {
4129
+ this._blockHandleVisible = false;
4130
+ }
4131
+ }
4132
+ // ── Private methods: bubble menu ──────────────────────────────────────────
4133
+ async _updateBubbleMenu() {
4134
+ if (!this._editor || this.disabled || this.readonly) {
4135
+ this._bubbleOpen = false;
4136
+ return;
4137
+ }
4138
+ if (this._mode !== 'editor') {
4139
+ this._bubbleOpen = false;
4140
+ return;
4141
+ }
4142
+ const { from, to, empty } = this._editor.state.selection;
4143
+ if (empty || from === to) {
4144
+ this._bubbleOpen = false;
4145
+ return;
4146
+ }
4147
+ this._bubbleOpen = true;
4148
+ await this.updateComplete;
4149
+ if (!this._bubbleEl)
4150
+ return;
4151
+ const { view } = this._editor;
4152
+ const start = view.coordsAtPos(from);
4153
+ const end = view.coordsAtPos(to);
4154
+ const rect = {
4155
+ x: Math.min(start.left, end.left),
4156
+ y: start.top,
4157
+ left: Math.min(start.left, end.left),
4158
+ top: start.top,
4159
+ right: Math.max(start.right, end.right),
4160
+ bottom: end.bottom,
4161
+ width: Math.max(start.right, end.right) - Math.min(start.left, end.left),
4162
+ height: end.bottom - start.top,
4163
+ toJSON: () => ({}),
4164
+ };
4165
+ const virtual = {
4166
+ getBoundingClientRect: () => rect,
4167
+ };
4168
+ const { x, y } = await computePosition(virtual, this._bubbleEl, {
4169
+ placement: 'top',
4170
+ strategy: 'fixed',
4171
+ middleware: [offset(8), flip(), shift({ padding: 8 })],
4172
+ });
4173
+ this._bubbleEl.style.left = `${x}px`;
4174
+ this._bubbleEl.style.top = `${y}px`;
4175
+ }
4176
+ // ── Private methods: events / mode ────────────────────────────────────────
4177
+ _dispatchDebouncedChange() {
4178
+ if (this._changeTimeout) {
4179
+ window.clearTimeout(this._changeTimeout);
4180
+ }
4181
+ this._changeTimeout = window.setTimeout(() => {
4182
+ redispatchEvent(this, new Event('change', { bubbles: true, composed: true }));
4183
+ }, this.debounce);
4184
+ }
4185
+ _execCommand(command) {
4186
+ if (this.disabled || this.readonly || !this._editor)
4187
+ return;
4188
+ command();
4189
+ this._editor.commands.focus();
4190
+ }
4191
+ // ── Render helpers ────────────────────────────────────────────────────────
4192
+ _renderToolbarButton(icon, title, action, active = false) {
4193
+ return b `
4194
+ <button
4195
+ class=${e$1({ 'toolbar-btn': true, active })}
4196
+ title=${title}
4197
+ aria-label=${title}
4198
+ ?disabled=${this.disabled || this.readonly}
4199
+ @mousedown=${(e) => e.preventDefault()}
4200
+ @click=${(e) => {
4201
+ e.preventDefault();
4202
+ this._execCommand(action);
4203
+ }}
4204
+ >
4205
+ <wc-icon name=${icon} size="sm"></wc-icon>
4206
+ </button>
4207
+ `;
4208
+ }
4209
+ _renderBubbleMenu() {
4210
+ if (!this._editor)
4211
+ return A;
4212
+ return b `
4213
+ <div
4214
+ class=${e$1({ 'bubble-menu': true, open: this._bubbleOpen })}
4215
+ role="toolbar"
4216
+ aria-label="Inline formatting"
4217
+ >
4218
+ ${this._renderToolbarButton('format_bold', 'Bold', () => this._editor?.chain().focus().toggleBold().run(), this._editor.isActive('bold'))}
4219
+ ${this._renderToolbarButton('format_italic', 'Italic', () => this._editor?.chain().focus().toggleItalic().run(), this._editor.isActive('italic'))}
4220
+ ${this._renderToolbarButton('format_underlined', 'Underline', () => this._editor?.chain().focus().toggleUnderline().run(), this._editor.isActive('underline'))}
4221
+ ${this._renderToolbarButton('format_strikethrough', 'Strikethrough', () => this._editor?.chain().focus().toggleStrike().run(), this._editor.isActive('strike'))}
4222
+ ${this._renderToolbarButton('code', 'Inline code', () => this._editor?.chain().focus().toggleCode().run(), this._editor.isActive('code'))}
4223
+ </div>
4224
+ `;
4225
+ }
4226
+ _renderSlashMenu() {
4227
+ return b `
4228
+ <div
4229
+ class=${e$1({ 'slash-menu': true, open: this._slashOpen })}
4230
+ role="listbox"
4231
+ aria-label="Insert block"
4232
+ >
4233
+ ${this._slashItems.map((item, index) => b `
4234
+ <button
4235
+ type="button"
4236
+ class=${e$1({
4237
+ 'slash-item': true,
4238
+ active: index === this._slashIndex,
4239
+ })}
4240
+ role="option"
4241
+ aria-selected=${index === this._slashIndex}
4242
+ data-index=${index}
4243
+ @mousedown=${(e) => e.preventDefault()}
4244
+ @click=${this._onSlashItemClick}
4245
+ >
4246
+ <wc-icon name=${item.icon} size="sm"></wc-icon>
4247
+ <span class="slash-item-label">${item.title}</span>
4248
+ <span class="slash-item-hint">${item.hint}</span>
4249
+ </button>
4250
+ `)}
4251
+ </div>
4252
+ `;
4253
+ }
4254
+ _renderBlockHandle() {
4255
+ if (this._mode !== 'editor')
4256
+ return A;
4257
+ return b `
4258
+ <div
4259
+ class=${e$1({
4260
+ 'block-handle': true,
4261
+ visible: this._blockHandleVisible,
4262
+ })}
4263
+ @mouseenter=${this._onBlockHandleMouseEnter}
4264
+ @mouseleave=${this._onBlockHandleMouseLeave}
4265
+ >
4266
+ <button
4267
+ class="block-handle-btn drag-btn"
4268
+ title="Drag to reorder"
4269
+ aria-label="Drag to reorder"
4270
+ draggable="true"
4271
+ ?disabled=${this.disabled || this.readonly}
4272
+ @mousedown=${this._onDragHandleMouseDown}
4273
+ @dragstart=${this._onDragHandleDragStart}
4274
+ @dragend=${this._onDragHandleDragEnd}
4275
+ >
4276
+ <wc-icon name="drag_indicator" size="sm"></wc-icon>
4277
+ </button>
4278
+ <button
4279
+ class="block-handle-btn insert-btn"
4280
+ title="Insert block below"
4281
+ aria-label="Insert block below"
4282
+ ?disabled=${this.disabled || this.readonly}
4283
+ @mousedown=${(e) => e.preventDefault()}
4284
+ @click=${this._onInsertBlockClick}
4285
+ >
4286
+ <wc-icon name="add" size="sm"></wc-icon>
4287
+ </button>
4288
+ </div>
4289
+ `;
4290
+ }
4291
+ _renderReadonlyTag() {
4292
+ if (this.disabled) {
4293
+ return b `<wc-tag class="read-only-tag" color="red">Disabled</wc-tag>`;
4294
+ }
4295
+ if (this.readonly) {
4296
+ return b `<wc-tag class="read-only-tag" color="red">Read Only</wc-tag>`;
4297
+ }
4298
+ return A;
4299
+ }
4300
+ // ── Render ────────────────────────────────────────────────────────────────
4301
+ render() {
4302
+ const isEmpty = !this.value || this.value.trim() === '';
4303
+ return b `
4304
+ <wc-field
4305
+ label=${this.label}
4306
+ ?required=${this.required}
4307
+ ?disabled=${this.disabled}
4308
+ ?readonly=${this.readonly}
4309
+ ?skeleton=${this.skeleton}
4310
+ ?focused=${this._focused}
4311
+ ?error=${this.error}
4312
+ error-text=${this.errorText}
4313
+ helper-text=${this.helperText}
4314
+ variant=${this.variant}
4315
+ ?populated=${!isEmpty}
4316
+ .host=${this}
4317
+ class=${e$1({
4318
+ 'markdown-editor-field': true,
4319
+ disabled: this.disabled,
4320
+ readonly: this.readonly,
4321
+ })}
4322
+ >
4323
+ <div
4324
+ class=${e$1({
4325
+ 'markdown-editor-content': true,
4326
+ 'is-empty': isEmpty,
4327
+ hidden: this._mode !== 'editor',
4328
+ })}
4329
+ data-placeholder=${this.placeholder}
4330
+ >
4331
+ <div class="tiptap-root"></div>
4332
+ </div>
4333
+
4334
+ <div
4335
+ class=${e$1({
4336
+ 'markdown-source': true,
4337
+ hidden: this._mode !== 'markdown',
4338
+ })}
4339
+ >
4340
+ <wc-code-editor
4341
+ language="markdown"
4342
+ .value=${this.value}
4343
+ ?readonly=${this.readonly}
4344
+ ?disabled=${this.disabled}
4345
+ @change=${this._handleSourceChange}
4346
+ ></wc-code-editor>
4347
+ </div>
4348
+
4349
+ <div class="mode-switcher">
4350
+ <wc-segmented-button-group @change=${this._switchMode}>
4351
+ <wc-segmented-button
4352
+ value="editor"
4353
+ ?selected=${this._mode === 'editor'}
4354
+ ?disabled=${this.disabled}
4355
+ >
4356
+ Editor
4357
+ </wc-segmented-button>
4358
+ <wc-segmented-button
4359
+ value="markdown"
4360
+ ?selected=${this._mode === 'markdown'}
4361
+ ?disabled=${this.disabled}
4362
+ >
4363
+ Markdown
4364
+ </wc-segmented-button>
4365
+ </wc-segmented-button-group>
4366
+ </div>
4367
+
4368
+ ${this._renderReadonlyTag()}
4369
+ </wc-field>
4370
+
4371
+ ${this._renderBubbleMenu()} ${this._renderSlashMenu()}
4372
+ ${this._renderBlockHandle()}
4373
+ `;
4374
+ }
4375
+ };
4376
+ MarkdownEditor.styles = [css_248z];
4377
+ __decorate([
4378
+ n({ type: String })
4379
+ ], MarkdownEditor.prototype, "value", void 0);
4380
+ __decorate([
4381
+ n({ type: String })
4382
+ ], MarkdownEditor.prototype, "label", void 0);
4383
+ __decorate([
4384
+ n({ type: String })
4385
+ ], MarkdownEditor.prototype, "placeholder", void 0);
4386
+ __decorate([
4387
+ n({ type: String })
4388
+ ], MarkdownEditor.prototype, "variant", void 0);
4389
+ __decorate([
4390
+ n({ type: String, attribute: 'helper-text' })
4391
+ ], MarkdownEditor.prototype, "helperText", void 0);
4392
+ __decorate([
4393
+ n({ type: Boolean })
4394
+ ], MarkdownEditor.prototype, "error", void 0);
4395
+ __decorate([
4396
+ n({ type: String, attribute: 'error-text' })
4397
+ ], MarkdownEditor.prototype, "errorText", void 0);
4398
+ __decorate([
4399
+ n({ type: Number })
4400
+ ], MarkdownEditor.prototype, "debounce", void 0);
4401
+ __decorate([
4402
+ r()
4403
+ ], MarkdownEditor.prototype, "_focused", void 0);
4404
+ __decorate([
4405
+ r()
4406
+ ], MarkdownEditor.prototype, "_mode", void 0);
4407
+ __decorate([
4408
+ r()
4409
+ ], MarkdownEditor.prototype, "_bubbleOpen", void 0);
4410
+ __decorate([
4411
+ r()
4412
+ ], MarkdownEditor.prototype, "_slashOpen", void 0);
4413
+ __decorate([
4414
+ r()
4415
+ ], MarkdownEditor.prototype, "_slashItems", void 0);
4416
+ __decorate([
4417
+ r()
4418
+ ], MarkdownEditor.prototype, "_slashIndex", void 0);
4419
+ __decorate([
4420
+ r()
4421
+ ], MarkdownEditor.prototype, "_blockHandleVisible", void 0);
4422
+ __decorate([
4423
+ e('.tiptap-root')
4424
+ ], MarkdownEditor.prototype, "_editorEl", void 0);
4425
+ __decorate([
4426
+ e('.bubble-menu')
4427
+ ], MarkdownEditor.prototype, "_bubbleEl", void 0);
4428
+ __decorate([
4429
+ e('.slash-menu')
4430
+ ], MarkdownEditor.prototype, "_slashEl", void 0);
4431
+ __decorate([
4432
+ e('.block-handle')
4433
+ ], MarkdownEditor.prototype, "_blockHandleEl", void 0);
4434
+ MarkdownEditor = MarkdownEditor_1 = __decorate([
4435
+ IndividualComponent
4436
+ ], MarkdownEditor);
4437
+
4438
+ export { MarkdownEditor };
4439
+ //# sourceMappingURL=markdown-editor.js.map