@khanacademy/simple-markdown 0.14.0 → 1.0.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.
package/dist/es/index.js DELETED
@@ -1,1457 +0,0 @@
1
- /**
2
- * Adds the given perseus library version information to the __perseus_debug__
3
- * object and ensures that the object is attached to `globalThis` (`window` in
4
- * browser environments).
5
- *
6
- * This allows each library to provide runtime version information to assist in
7
- * debugging in production environments.
8
- */
9
- const addLibraryVersionToPerseusDebug = (libraryName, libraryVersion) => {
10
- // If the library version is the default value, then we don't want to
11
- // prefix it with a "v" to indicate that it is a version number.
12
- let prefix = "v";
13
- if (libraryVersion === "__lib_version__") {
14
- prefix = "";
15
- }
16
- const formattedVersion = `${prefix}${libraryVersion}`;
17
- if (typeof globalThis !== "undefined") {
18
- var _globalThis$__perseus;
19
- globalThis.__perseus_debug__ = (_globalThis$__perseus = globalThis.__perseus_debug__) != null ? _globalThis$__perseus : {};
20
- const existingVersionEntry = globalThis.__perseus_debug__[libraryName];
21
- if (existingVersionEntry) {
22
- // If we already have an entry and it doesn't match the registered
23
- // version, we morph the entry into an array and log a warning.
24
- if (existingVersionEntry !== formattedVersion) {
25
- // Existing entry might be an array already (oops, at least 2
26
- // versions of the library already loaded!).
27
- const allVersions = Array.isArray(existingVersionEntry) ? existingVersionEntry : [existingVersionEntry];
28
- allVersions.push(formattedVersion);
29
- globalThis.__perseus_debug__[libraryName] = allVersions;
30
-
31
- // eslint-disable-next-line no-console
32
- console.warn(`Multiple versions of ${libraryName} loaded on this page: ${allVersions.sort().join(", ")}`);
33
- }
34
- } else {
35
- globalThis.__perseus_debug__[libraryName] = formattedVersion;
36
- }
37
- } else {
38
- // eslint-disable-next-line no-console
39
- console.warn(`globalThis not found found (${formattedVersion})`);
40
- }
41
- };
42
-
43
- // This file is processed by a Rollup plugin (replace) to inject the production
44
- const libName = "@khanacademy/simple-markdown";
45
- const libVersion = "0.14.0";
46
- addLibraryVersionToPerseusDebug(libName, libVersion);
47
-
48
- /* eslint-disable prefer-spread, no-regex-spaces, guard-for-in, no-console, no-var */
49
-
50
- // Type Definitions:
51
-
52
- // We want to clarify our defaultRules types a little bit more so clients can
53
- // reuse defaultRules built-ins. So we make some stronger guarantess when
54
- // we can:
55
-
56
- // End TypeScript Definitions
57
-
58
- var CR_NEWLINE_R = /\r\n?/g;
59
- var TAB_R = /\t/g;
60
- var FORMFEED_R = /\f/g;
61
-
62
- /**
63
- * Turn various whitespace into easy-to-process whitespace
64
- */
65
- var preprocess = function preprocess(source) {
66
- return source.replace(CR_NEWLINE_R, "\n").replace(FORMFEED_R, "").replace(TAB_R, " ");
67
- };
68
- var populateInitialState = function populateInitialState(givenState, defaultState) {
69
- var state = givenState || {};
70
- if (defaultState != null) {
71
- for (var prop in defaultState) {
72
- if (Object.prototype.hasOwnProperty.call(defaultState, prop)) {
73
- state[prop] = defaultState[prop];
74
- }
75
- }
76
- }
77
- return state;
78
- };
79
-
80
- /**
81
- * Creates a parser for a given set of rules, with the precedence
82
- * specified as a list of rules.
83
- *
84
- * @param {SimpleMarkdown.ParserRules} rules
85
- * an object containing
86
- * rule type -> {match, order, parse} objects
87
- * (lower order is higher precedence)
88
- * @param {SimpleMarkdown.OptionalState} [defaultState]
89
- *
90
- * @returns {SimpleMarkdown.Parser}
91
- * The resulting parse function, with the following parameters:
92
- * @source: the input source string to be parsed
93
- * @state: an optional object to be threaded through parse
94
- * calls. Allows clients to add stateful operations to
95
- * parsing, such as keeping track of how many levels deep
96
- * some nesting is. For an example use-case, see passage-ref
97
- * parsing in src/widgets/passage/passage-markdown.jsx
98
- */
99
- var parserFor = function parserFor(rules, defaultState) {
100
- // Sorts rules in order of increasing order, then
101
- // ascending rule name in case of ties.
102
- var ruleList = Object.keys(rules).filter(function (type) {
103
- var rule = rules[type];
104
- if (rule == null || rule.match == null) {
105
- return false;
106
- }
107
- var order = rule.order;
108
- if ((typeof order !== "number" || !isFinite(order)) && typeof console !== "undefined") {
109
- console.warn("simple-markdown: Invalid order for rule `" + type + "`: " + String(order));
110
- }
111
- return true;
112
- });
113
- ruleList.sort(function (typeA, typeB) {
114
- var ruleA = rules[typeA];
115
- var ruleB = rules[typeB];
116
- var orderA = ruleA.order;
117
- var orderB = ruleB.order;
118
-
119
- // First sort based on increasing order
120
- if (orderA !== orderB) {
121
- return orderA - orderB;
122
- }
123
- var secondaryOrderA = ruleA.quality ? 0 : 1;
124
- var secondaryOrderB = ruleB.quality ? 0 : 1;
125
- if (secondaryOrderA !== secondaryOrderB) {
126
- return secondaryOrderA - secondaryOrderB;
127
-
128
- // Then based on increasing unicode lexicographic ordering
129
- } else if (typeA < typeB) {
130
- return -1;
131
- } else if (typeA > typeB) {
132
- return 1;
133
- } else {
134
- // Rules should never have the same name,
135
- // but this is provided for completeness.
136
- return 0;
137
- }
138
- });
139
- var latestState;
140
- var nestedParse = function nestedParse(source, state) {
141
- var result = [];
142
- state = state || latestState;
143
- latestState = state;
144
- while (source) {
145
- // store the best match, it's rule, and quality:
146
- var ruleType = null;
147
- var rule = null;
148
- var capture = null;
149
- var quality = NaN;
150
-
151
- // loop control variables:
152
- var i = 0;
153
- var currRuleType = ruleList[0];
154
- var currRule = rules[currRuleType];
155
- do {
156
- var currOrder = currRule.order;
157
- var prevCaptureStr = state.prevCapture == null ? "" : state.prevCapture[0];
158
- var currCapture = currRule.match(source, state, prevCaptureStr);
159
- if (currCapture) {
160
- var currQuality = currRule.quality ? currRule.quality(currCapture, state, prevCaptureStr) : 0;
161
- // This should always be true the first time because
162
- // the initial quality is NaN (that's why there's the
163
- // condition negation).
164
- if (!(currQuality <= quality)) {
165
- // @ts-expect-error - TS2322 - Type 'string' is not assignable to type 'null'.
166
- ruleType = currRuleType;
167
- // @ts-expect-error - TS2322 - Type 'ParserRule' is not assignable to type 'null'.
168
- rule = currRule;
169
- // @ts-expect-error - TS2322 - Type 'Capture' is not assignable to type 'null'.
170
- capture = currCapture;
171
- quality = currQuality;
172
- }
173
- }
174
-
175
- // Move on to the next item.
176
- // Note that this makes `currRule` be the next item
177
- i++;
178
- currRuleType = ruleList[i];
179
- currRule = rules[currRuleType];
180
- } while (
181
- // keep looping while we're still within the ruleList
182
- currRule && (
183
- // if we don't have a match yet, continue
184
- !capture ||
185
- // or if we have a match, but the next rule is
186
- // at the same order, and has a quality measurement
187
- // functions, then this rule must have a quality
188
- // measurement function (since they are sorted before
189
- // those without), and we need to check if there is
190
- // a better quality match
191
- currRule.order === currOrder && currRule.quality));
192
-
193
- // TODO(aria): Write tests for these
194
- if (rule == null || capture == null) {
195
- throw new Error("Could not find a matching rule for the below " + "content. The rule with highest `order` should " + "always match content provided to it. Check " + "the definition of `match` for '" + ruleList[ruleList.length - 1] + "'. It seems to not match the following source:\n" + source);
196
- }
197
- // @ts-expect-error - TS2339 - Property 'index' does not exist on type 'never'.
198
- if (capture.index) {
199
- // If present and non-zero, i.e. a non-^ regexp result:
200
- throw new Error("`match` must return a capture starting at index 0 " + "(the current parse index). Did you forget a ^ at the " + "start of the RegExp?");
201
- }
202
-
203
- // @ts-expect-error - TS2339 - Property 'parse' does not exist on type 'never'.
204
- var parsed = rule.parse(capture, nestedParse, state);
205
- // We maintain the same object here so that rules can
206
- // store references to the objects they return and
207
- // modify them later. (oops sorry! but this adds a lot
208
- // of power--see reflinks.)
209
- if (Array.isArray(parsed)) {
210
- Array.prototype.push.apply(result, parsed);
211
- } else {
212
- if (parsed == null || typeof parsed !== "object") {
213
- throw new Error(`parse() function returned invalid parse result: '${parsed}'`);
214
- }
215
-
216
- // We also let rules override the default type of
217
- // their parsed node if they would like to, so that
218
- // there can be a single output function for all links,
219
- // even if there are several rules to parse them.
220
- if (parsed.type == null) {
221
- parsed.type = ruleType;
222
- }
223
- result.push(parsed);
224
- }
225
- state.prevCapture = capture;
226
- source = source.substring(state.prevCapture[0].length);
227
- }
228
- return result;
229
- };
230
- var outerParse = function outerParse(source, state) {
231
- latestState = populateInitialState(state, defaultState);
232
- if (!latestState.inline && !latestState.disableAutoBlockNewlines) {
233
- source = source + "\n\n";
234
- }
235
- // We store the previous capture so that match functions can
236
- // use some limited amount of lookbehind. Lists use this to
237
- // ensure they don't match arbitrary '- ' or '* ' in inline
238
- // text (see the list rule for more information). This stores
239
- // the full regex capture object, if there is one.
240
- latestState.prevCapture = null;
241
- return nestedParse(preprocess(source), latestState);
242
- };
243
- return outerParse;
244
- };
245
-
246
- // Creates a match function for an inline scoped element from a regex
247
- var inlineRegex = function inlineRegex(regex) {
248
- var match = function match(source, state, prevCapture) {
249
- if (state.inline) {
250
- return regex.exec(source);
251
- } else {
252
- return null;
253
- }
254
- };
255
- // @ts-expect-error - TS2339 - Property 'regex' does not exist on type '(source: string, state: State, prevCapture: string) => Capture | null | undefined'.
256
- match.regex = regex;
257
- return match;
258
- };
259
-
260
- // Creates a match function for a block scoped element from a regex
261
- var blockRegex = function blockRegex(regex) {
262
- var match = function match(source, state) {
263
- if (state.inline) {
264
- return null;
265
- } else {
266
- return regex.exec(source);
267
- }
268
- };
269
- match.regex = regex;
270
- return match;
271
- };
272
-
273
- // Creates a match function from a regex, ignoring block/inline scope
274
- var anyScopeRegex = function anyScopeRegex(regex) {
275
- var match = function match(source, state) {
276
- return regex.exec(source);
277
- };
278
- match.regex = regex;
279
- return match;
280
- };
281
- var TYPE_SYMBOL = typeof Symbol === "function" && Symbol.for && Symbol.for("react.element") || 0xeac7;
282
- var reactElement = function reactElement(type, key, props) {
283
- var element = {
284
- $$typeof: TYPE_SYMBOL,
285
- type: type,
286
- key: key == null ? undefined : key,
287
- ref: null,
288
- props: props,
289
- _owner: null
290
- };
291
- return element;
292
- };
293
-
294
- /** Returns a closed HTML tag.
295
- * @param {string} tagName - Name of HTML tag (eg. "em" or "a")
296
- * @param {string} content - Inner content of tag
297
- * @param {{ [attr: string]: SimpleMarkdown.Attr }} [attributes] - Optional extra attributes of tag as an object of key-value pairs
298
- * eg. { "href": "http://google.com" }. Falsey attributes are filtered out.
299
- * @param {boolean} [isClosed] - boolean that controls whether tag is closed or not (eg. img tags).
300
- * defaults to true
301
- */
302
- var htmlTag = function htmlTag(tagName, content, attributes, isClosed) {
303
- attributes = attributes || {};
304
- isClosed = typeof isClosed !== "undefined" ? isClosed : true;
305
- var attributeString = "";
306
- for (var attr in attributes) {
307
- var attribute = attributes[attr];
308
- // Removes falsey attributes
309
- if (Object.prototype.hasOwnProperty.call(attributes, attr) && attribute) {
310
- attributeString += " " + sanitizeText(attr) + '="' + sanitizeText(attribute) + '"';
311
- }
312
- }
313
- var unclosedTag = "<" + tagName + attributeString + ">";
314
- if (isClosed) {
315
- return unclosedTag + content + "</" + tagName + ">";
316
- } else {
317
- return unclosedTag;
318
- }
319
- };
320
- var EMPTY_PROPS = {};
321
-
322
- /**
323
- * @param {string | null | undefined} url - url to sanitize
324
- * @returns {string | null} - url if safe, or null if a safe url could not be made
325
- */
326
- var sanitizeUrl = function sanitizeUrl(url) {
327
- if (url == null) {
328
- return null;
329
- }
330
- try {
331
- var prot = new URL(url, "https://localhost").protocol;
332
- if (prot.indexOf("javascript:") === 0 || prot.indexOf("vbscript:") === 0 || prot.indexOf("data:") === 0) {
333
- return null;
334
- }
335
- } catch (_unused) {
336
- // invalid URLs should throw a TypeError
337
- // see for instance: `new URL("");`
338
- return null;
339
- }
340
- return url;
341
- };
342
- var SANITIZE_TEXT_R = /[<>&"']/g;
343
- var SANITIZE_TEXT_CODES = {
344
- "<": "&lt;",
345
- ">": "&gt;",
346
- "&": "&amp;",
347
- '"': "&quot;",
348
- "'": "&#x27;",
349
- "/": "&#x2F;",
350
- "`": "&#96;"
351
- };
352
- var sanitizeText = function sanitizeText(text) {
353
- return String(text).replace(SANITIZE_TEXT_R, function (chr) {
354
- return SANITIZE_TEXT_CODES[chr];
355
- });
356
- };
357
- var UNESCAPE_URL_R = /\\([^0-9A-Za-z\s])/g;
358
- var unescapeUrl = function unescapeUrl(rawUrlString) {
359
- return rawUrlString.replace(UNESCAPE_URL_R, "$1");
360
- };
361
-
362
- /**
363
- * Parse some content with the parser `parse`, with state.inline
364
- * set to true. Useful for block elements; not generally necessary
365
- * to be used by inline elements (where state.inline is already true.
366
- */
367
- var parseInline = function parseInline(parse, content, state) {
368
- var isCurrentlyInline = state.inline || false;
369
- state.inline = true;
370
- var result = parse(content, state);
371
- state.inline = isCurrentlyInline;
372
- return result;
373
- };
374
- var parseBlock = function parseBlock(parse, content, state) {
375
- var isCurrentlyInline = state.inline || false;
376
- state.inline = false;
377
- var result = parse(content + "\n\n", state);
378
- state.inline = isCurrentlyInline;
379
- return result;
380
- };
381
- var parseCaptureInline = function parseCaptureInline(capture, parse, state) {
382
- return {
383
- content: parseInline(parse, capture[1], state)
384
- };
385
- };
386
- var ignoreCapture = function ignoreCapture() {
387
- return {};
388
- };
389
-
390
- // recognize a `*` `-`, `+`, `1.`, `2.`... list bullet
391
- var LIST_BULLET = "(?:[*+-]|\\d+\\.)";
392
- // recognize the start of a list item:
393
- // leading space plus a bullet plus a space (` * `)
394
- var LIST_ITEM_PREFIX = "( *)(" + LIST_BULLET + ") +";
395
- var LIST_ITEM_PREFIX_R = new RegExp("^" + LIST_ITEM_PREFIX);
396
- // recognize an individual list item:
397
- // * hi
398
- // this is part of the same item
399
- //
400
- // as is this, which is a new paragraph in the same item
401
- //
402
- // * but this is not part of the same item
403
- var LIST_ITEM_R = new RegExp(LIST_ITEM_PREFIX + "[^\\n]*(?:\\n" + "(?!\\1" + LIST_BULLET + " )[^\\n]*)*(\n|$)", "gm");
404
- var BLOCK_END_R = /\n{2,}$/;
405
- var INLINE_CODE_ESCAPE_BACKTICKS_R = /^ (?= *`)|(` *) $/g;
406
- // recognize the end of a paragraph block inside a list item:
407
- // two or more newlines at end end of the item
408
- var LIST_BLOCK_END_R = BLOCK_END_R;
409
- var LIST_ITEM_END_R = / *\n+$/;
410
- // check whether a list item has paragraphs: if it does,
411
- // we leave the newlines at the end
412
- var LIST_R = new RegExp("^( *)(" + LIST_BULLET + ") " + "[\\s\\S]+?(?:\n{2,}(?! )" + "(?!\\1" + LIST_BULLET + " )\\n*" +
413
- // the \\s*$ here is so that we can parse the inside of nested
414
- // lists, where our content might end before we receive two `\n`s
415
- "|\\s*\n*$)");
416
- var LIST_LOOKBEHIND_R = /(?:^|\n)( *)$/;
417
- var TABLES = function () {
418
- // predefine regexes so we don't have to create them inside functions
419
- // sure, regex literals should be fast, even inside functions, but they
420
- // aren't in all browsers.
421
- var TABLE_ROW_SEPARATOR_TRIM = /^ *\| *| *\| *$/g;
422
- var TABLE_CELL_END_TRIM = / *$/;
423
- var TABLE_RIGHT_ALIGN = /^ *-+: *$/;
424
- var TABLE_CENTER_ALIGN = /^ *:-+: *$/;
425
- var TABLE_LEFT_ALIGN = /^ *:-+ *$/;
426
-
427
- // TODO: This needs a real type
428
-
429
- var parseTableAlignCapture = function parseTableAlignCapture(alignCapture) {
430
- if (TABLE_RIGHT_ALIGN.test(alignCapture)) {
431
- return "right";
432
- } else if (TABLE_CENTER_ALIGN.test(alignCapture)) {
433
- return "center";
434
- } else if (TABLE_LEFT_ALIGN.test(alignCapture)) {
435
- return "left";
436
- } else {
437
- return null;
438
- }
439
- };
440
- var parseTableAlign = function parseTableAlign(source, parse, state, trimEndSeparators) {
441
- if (trimEndSeparators) {
442
- source = source.replace(TABLE_ROW_SEPARATOR_TRIM, "");
443
- }
444
- var alignText = source.trim().split("|");
445
- return alignText.map(parseTableAlignCapture);
446
- };
447
- var parseTableRow = function parseTableRow(source, parse, state, trimEndSeparators) {
448
- var prevInTable = state.inTable;
449
- state.inTable = true;
450
- var tableRow = parse(source.trim(), state);
451
- state.inTable = prevInTable;
452
- var cells = [[]];
453
- tableRow.forEach(function (node, i) {
454
- if (node.type === "tableSeparator") {
455
- // Filter out empty table separators at the start/end:
456
- if (!trimEndSeparators || i !== 0 && i !== tableRow.length - 1) {
457
- // Split the current row:
458
- cells.push([]);
459
- }
460
- } else {
461
- if (node.type === "text" && (tableRow[i + 1] == null || tableRow[i + 1].type === "tableSeparator")) {
462
- node.content = node.content.replace(TABLE_CELL_END_TRIM, "");
463
- }
464
- // @ts-expect-error - TS2345 - Argument of type 'SingleASTNode' is not assignable to parameter of type 'never'.
465
- cells[cells.length - 1].push(node);
466
- }
467
- });
468
- return cells;
469
- };
470
-
471
- /**
472
- * @param {string} source
473
- * @param {SimpleMarkdown.Parser} parse
474
- * @param {SimpleMarkdown.State} state
475
- * @param {boolean} trimEndSeparators
476
- * @returns {SimpleMarkdown.ASTNode[][]}
477
- */
478
- var parseTableCells = function parseTableCells(source, parse, state, trimEndSeparators) {
479
- var rowsText = source.trim().split("\n");
480
- return rowsText.map(function (rowText) {
481
- return parseTableRow(rowText, parse, state, trimEndSeparators);
482
- });
483
- };
484
-
485
- /**
486
- * @param {boolean} trimEndSeparators
487
- * @returns {SimpleMarkdown.SingleNodeParseFunction}
488
- */
489
- var parseTable = function parseTable(trimEndSeparators) {
490
- return function (capture, parse, state) {
491
- state.inline = true;
492
- var header = parseTableRow(capture[1], parse, state, trimEndSeparators);
493
- var align = parseTableAlign(capture[2], parse, state, trimEndSeparators);
494
- var cells = parseTableCells(capture[3], parse, state, trimEndSeparators);
495
- state.inline = false;
496
- return {
497
- type: "table",
498
- header: header,
499
- align: align,
500
- cells: cells
501
- };
502
- };
503
- };
504
- return {
505
- parseTable: parseTable(true),
506
- parseNpTable: parseTable(false),
507
- TABLE_REGEX: /^ *(\|.+)\n *\|( *[-:]+[-| :]*)\n((?: *\|.*(?:\n|$))*)\n*/,
508
- NPTABLE_REGEX: /^ *(\S.*\|.*)\n *([-:]+ *\|[-| :]*)\n((?:.*\|.*(?:\n|$))*)\n*/
509
- };
510
- }();
511
- var LINK_INSIDE = "(?:\\[[^\\]]*\\]|[^\\[\\]]|\\](?=[^\\[]*\\]))*";
512
- var LINK_HREF_AND_TITLE = "\\s*<?((?:\\([^)]*\\)|[^\\s\\\\]|\\\\.)*?)>?(?:\\s+['\"]([\\s\\S]*?)['\"])?\\s*";
513
- var AUTOLINK_MAILTO_CHECK_R = /mailto:/i;
514
- var parseRef = function parseRef(capture, state, refNode) {
515
- var ref = (capture[2] || capture[1]).replace(/\s+/g, " ").toLowerCase();
516
-
517
- // We store information about previously seen defs on
518
- // state._defs (_ to deconflict with client-defined
519
- // state). If the def for this reflink/refimage has
520
- // already been seen, we can use its target/source
521
- // and title here:
522
- if (state._defs && state._defs[ref]) {
523
- var def = state._defs[ref];
524
- // `refNode` can be a link or an image. Both use
525
- // target and title properties.
526
- refNode.target = def.target;
527
- refNode.title = def.title;
528
- }
529
-
530
- // In case we haven't seen our def yet (or if someone
531
- // overwrites that def later on), we add this node
532
- // to the list of ref nodes for that def. Then, when
533
- // we find the def, we can modify this link/image AST
534
- // node :).
535
- // I'm sorry.
536
- state._refs = state._refs || {};
537
- state._refs[ref] = state._refs[ref] || [];
538
- state._refs[ref].push(refNode);
539
- return refNode;
540
- };
541
- var currOrder = 0;
542
- var defaultRules = {
543
- Array: {
544
- react: function (arr, output, state) {
545
- var oldKey = state.key;
546
- var result = [];
547
-
548
- // map output over the ast, except group any text
549
- // nodes together into a single string output.
550
- for (var i = 0, key = 0; i < arr.length; i++, key++) {
551
- // `key` is our numerical `state.key`, which we increment for
552
- // every output node, but don't change for joined text nodes.
553
- // (i, however, must change for joined text nodes)
554
- state.key = "" + i;
555
- var node = arr[i];
556
- if (node.type === "text") {
557
- node = {
558
- type: "text",
559
- content: node.content
560
- };
561
- for (; i + 1 < arr.length && arr[i + 1].type === "text"; i++) {
562
- node.content += arr[i + 1].content;
563
- }
564
- }
565
- result.push(output(node, state));
566
- }
567
- state.key = oldKey;
568
- return result;
569
- },
570
- html: function (arr, output, state) {
571
- var result = "";
572
-
573
- // map output over the ast, except group any text
574
- // nodes together into a single string output.
575
- for (var i = 0; i < arr.length; i++) {
576
- var node = arr[i];
577
- if (node.type === "text") {
578
- node = {
579
- type: "text",
580
- content: node.content
581
- };
582
- for (; i + 1 < arr.length && arr[i + 1].type === "text"; i++) {
583
- node.content += arr[i + 1].content;
584
- }
585
- }
586
- result += output(node, state);
587
- }
588
- return result;
589
- }
590
- },
591
- heading: {
592
- order: currOrder++,
593
- match: blockRegex(/^ *(#{1,6})([^\n]+?)#* *(?:\n *)+\n/),
594
- parse: function (capture, parse, state) {
595
- return {
596
- level: capture[1].length,
597
- content: parseInline(parse, capture[2].trim(), state)
598
- };
599
- },
600
- react: function (node, output, state) {
601
- return reactElement("h" + node.level, state.key, {
602
- children: output(node.content, state)
603
- });
604
- },
605
- html: function (node, output, state) {
606
- return htmlTag("h" + node.level, output(node.content, state));
607
- }
608
- },
609
- nptable: {
610
- order: currOrder++,
611
- match: blockRegex(TABLES.NPTABLE_REGEX),
612
- parse: TABLES.parseNpTable,
613
- react: null,
614
- html: null
615
- },
616
- lheading: {
617
- order: currOrder++,
618
- match: blockRegex(/^([^\n]+)\n *(=|-){3,} *(?:\n *)+\n/),
619
- parse: function (capture, parse, state) {
620
- return {
621
- type: "heading",
622
- level: capture[2] === "=" ? 1 : 2,
623
- content: parseInline(parse, capture[1], state)
624
- };
625
- },
626
- react: null,
627
- html: null
628
- },
629
- hr: {
630
- order: currOrder++,
631
- match: blockRegex(/^( *[-*_]){3,} *(?:\n *)+\n/),
632
- parse: ignoreCapture,
633
- react: function (node, output, state) {
634
- return reactElement("hr", state.key, {
635
- "aria-hidden": true
636
- });
637
- },
638
- html: function (node, output, state) {
639
- return '<hr aria-hidden="true">';
640
- }
641
- },
642
- codeBlock: {
643
- order: currOrder++,
644
- match: blockRegex(/^(?: [^\n]+\n*)+(?:\n *)+\n/),
645
- parse: function (capture, parse, state) {
646
- var content = capture[0].replace(/^ /gm, "").replace(/\n+$/, "");
647
- return {
648
- lang: undefined,
649
- content: content
650
- };
651
- },
652
- react: function (node, output, state) {
653
- var className = node.lang ? "markdown-code-" + node.lang : undefined;
654
- return reactElement("pre", state.key, {
655
- children: reactElement("code", null, {
656
- className: className,
657
- children: node.content
658
- })
659
- });
660
- },
661
- html: function (node, output, state) {
662
- var className = node.lang ? "markdown-code-" + node.lang : undefined;
663
- var codeBlock = htmlTag("code", sanitizeText(node.content), {
664
- class: className
665
- });
666
- return htmlTag("pre", codeBlock);
667
- }
668
- },
669
- fence: {
670
- order: currOrder++,
671
- match: blockRegex(/^ *(`{3,}|~{3,}) *(?:(\S+) *)?\n([\s\S]+?)\n?\1 *(?:\n *)+\n/),
672
- parse: function (capture, parse, state) {
673
- return {
674
- type: "codeBlock",
675
- lang: capture[2] || undefined,
676
- content: capture[3]
677
- };
678
- },
679
- react: null,
680
- html: null
681
- },
682
- blockQuote: {
683
- order: currOrder++,
684
- match: blockRegex(/^( *>[^\n]+(\n[^\n]+)*\n*)+\n{2,}/),
685
- parse: function (capture, parse, state) {
686
- var content = capture[0].replace(/^ *> ?/gm, "");
687
- return {
688
- content: parse(content, state)
689
- };
690
- },
691
- react: function (node, output, state) {
692
- return reactElement("blockquote", state.key, {
693
- children: output(node.content, state)
694
- });
695
- },
696
- html: function (node, output, state) {
697
- return htmlTag("blockquote", output(node.content, state));
698
- }
699
- },
700
- list: {
701
- order: currOrder++,
702
- match: function (source, state) {
703
- // We only want to break into a list if we are at the start of a
704
- // line. This is to avoid parsing "hi * there" with "* there"
705
- // becoming a part of a list.
706
- // You might wonder, "but that's inline, so of course it wouldn't
707
- // start a list?". You would be correct! Except that some of our
708
- // lists can be inline, because they might be inside another list,
709
- // in which case we can parse with inline scope, but need to allow
710
- // nested lists inside this inline scope.
711
- var prevCaptureStr = state.prevCapture == null ? "" : state.prevCapture[0];
712
- var isStartOfLineCapture = LIST_LOOKBEHIND_R.exec(prevCaptureStr);
713
- var isListBlock = state._list || !state.inline;
714
- if (isStartOfLineCapture && isListBlock) {
715
- source = isStartOfLineCapture[1] + source;
716
- return LIST_R.exec(source);
717
- } else {
718
- return null;
719
- }
720
- },
721
- parse: function (capture, parse, state) {
722
- var bullet = capture[2];
723
- var ordered = bullet.length > 1;
724
- var start = ordered ? +bullet : undefined;
725
- // @ts-expect-error - TS2322 - Type 'RegExpMatchArray | null' is not assignable to type 'string[]'.
726
- var items = capture[0].replace(LIST_BLOCK_END_R, "\n").match(LIST_ITEM_R);
727
-
728
- // We know this will match here, because of how the regexes are
729
- // defined
730
-
731
- var lastItemWasAParagraph = false;
732
- var itemContent = items.map(function (item, i) {
733
- // We need to see how far indented this item is:
734
- var prefixCapture = LIST_ITEM_PREFIX_R.exec(item);
735
- var space = prefixCapture ? prefixCapture[0].length : 0;
736
- // And then we construct a regex to "unindent" the subsequent
737
- // lines of the items by that amount:
738
- var spaceRegex = new RegExp("^ {1," + space + "}", "gm");
739
-
740
- // Before processing the item, we need a couple things
741
- var content = item
742
- // remove indents on trailing lines:
743
- .replace(spaceRegex, "")
744
- // remove the bullet:
745
- .replace(LIST_ITEM_PREFIX_R, "");
746
-
747
- // I'm not sur4 why this is necessary again?
748
-
749
- // Handling "loose" lists, like:
750
- //
751
- // * this is wrapped in a paragraph
752
- //
753
- // * as is this
754
- //
755
- // * as is this
756
- var isLastItem = i === items.length - 1;
757
- var containsBlocks = content.indexOf("\n\n") !== -1;
758
-
759
- // Any element in a list is a block if it contains multiple
760
- // newlines. The last element in the list can also be a block
761
- // if the previous item in the list was a block (this is
762
- // because non-last items in the list can end with \n\n, but
763
- // the last item can't, so we just "inherit" this property
764
- // from our previous element).
765
- var thisItemIsAParagraph = containsBlocks || isLastItem && lastItemWasAParagraph;
766
- lastItemWasAParagraph = thisItemIsAParagraph;
767
-
768
- // backup our state for restoration afterwards. We're going to
769
- // want to set state._list to true, and state.inline depending
770
- // on our list's looseness.
771
- var oldStateInline = state.inline;
772
- var oldStateList = state._list;
773
- state._list = true;
774
-
775
- // Parse inline if we're in a tight list, or block if we're in
776
- // a loose list.
777
- var adjustedContent;
778
- if (thisItemIsAParagraph) {
779
- state.inline = false;
780
- adjustedContent = content.replace(LIST_ITEM_END_R, "\n\n");
781
- } else {
782
- state.inline = true;
783
- adjustedContent = content.replace(LIST_ITEM_END_R, "");
784
- }
785
- var result = parse(adjustedContent, state);
786
-
787
- // Restore our state before returning
788
- state.inline = oldStateInline;
789
- state._list = oldStateList;
790
- return result;
791
- });
792
- return {
793
- ordered: ordered,
794
- start: start,
795
- items: itemContent
796
- };
797
- },
798
- react: function (node, output, state) {
799
- var ListWrapper = node.ordered ? "ol" : "ul";
800
- return reactElement(ListWrapper, state.key, {
801
- start: node.start,
802
- children: node.items.map(function (item, i) {
803
- return reactElement("li", "" + i, {
804
- children: output(item, state)
805
- });
806
- })
807
- });
808
- },
809
- html: function (node, output, state) {
810
- var listItems = node.items.map(function (item) {
811
- return htmlTag("li", output(item, state));
812
- }).join("");
813
- var listTag = node.ordered ? "ol" : "ul";
814
- var attributes = {
815
- start: node.start
816
- };
817
- return htmlTag(listTag, listItems, attributes);
818
- }
819
- },
820
- def: {
821
- order: currOrder++,
822
- // TODO(aria): This will match without a blank line before the next
823
- // block element, which is inconsistent with most of the rest of
824
- // simple-markdown.
825
- match: blockRegex(/^ *\[([^\]]+)\]: *<?([^\s>]*)>?(?: +["(]([^\n]+)[")])? *\n(?: *\n)*/),
826
- parse: function (capture, parse, state) {
827
- var def = capture[1].replace(/\s+/g, " ").toLowerCase();
828
- var target = capture[2];
829
- var title = capture[3];
830
-
831
- // Look for previous links/images using this def
832
- // If any links/images using this def have already been declared,
833
- // they will have added themselves to the state._refs[def] list
834
- // (_ to deconflict with client-defined state). We look through
835
- // that list of reflinks for this def, and modify those AST nodes
836
- // with our newly found information now.
837
- // Sorry :(.
838
- if (state._refs && state._refs[def]) {
839
- // `refNode` can be a link or an image
840
- state._refs[def].forEach(function (refNode) {
841
- refNode.target = target;
842
- refNode.title = title;
843
- });
844
- }
845
-
846
- // Add this def to our map of defs for any future links/images
847
- // In case we haven't found any or all of the refs referring to
848
- // this def yet, we add our def to the table of known defs, so
849
- // that future reflinks can modify themselves appropriately with
850
- // this information.
851
- state._defs = state._defs || {};
852
- state._defs[def] = {
853
- target: target,
854
- title: title
855
- };
856
-
857
- // return the relevant parsed information
858
- // for debugging only.
859
- return {
860
- def: def,
861
- target: target,
862
- title: title
863
- };
864
- },
865
- react: function () {
866
- return null;
867
- },
868
- html: function () {
869
- return "";
870
- }
871
- },
872
- table: {
873
- order: currOrder++,
874
- match: blockRegex(TABLES.TABLE_REGEX),
875
- parse: TABLES.parseTable,
876
- react: function (node, output, state) {
877
- var getStyle = function getStyle(colIndex) {
878
- return node.align[colIndex] == null ? {} : {
879
- textAlign: node.align[colIndex]
880
- };
881
- };
882
- var headers = node.header.map(function (content, i) {
883
- return reactElement("th", "" + i, {
884
- style: getStyle(i),
885
- scope: "col",
886
- children: output(content, state)
887
- });
888
- });
889
- var rows = node.cells.map(function (row, r) {
890
- return reactElement("tr", "" + r, {
891
- children: row.map(function (content, c) {
892
- return reactElement("td", "" + c, {
893
- style: getStyle(c),
894
- children: output(content, state)
895
- });
896
- })
897
- });
898
- });
899
- return reactElement("table", state.key, {
900
- children: [reactElement("thead", "thead", {
901
- children: reactElement("tr", null, {
902
- children: headers
903
- })
904
- }), reactElement("tbody", "tbody", {
905
- children: rows
906
- })]
907
- });
908
- },
909
- html: function (node, output, state) {
910
- var getStyle = function getStyle(colIndex) {
911
- return node.align[colIndex] == null ? "" : "text-align:" + node.align[colIndex] + ";";
912
- };
913
- var headers = node.header.map(function (content, i) {
914
- return htmlTag("th", output(content, state), {
915
- style: getStyle(i),
916
- scope: "col"
917
- });
918
- }).join("");
919
- var rows = node.cells.map(function (row) {
920
- var cols = row.map(function (content, c) {
921
- return htmlTag("td", output(content, state), {
922
- style: getStyle(c)
923
- });
924
- }).join("");
925
- return htmlTag("tr", cols);
926
- }).join("");
927
- var thead = htmlTag("thead", htmlTag("tr", headers));
928
- var tbody = htmlTag("tbody", rows);
929
- return htmlTag("table", thead + tbody);
930
- }
931
- },
932
- newline: {
933
- order: currOrder++,
934
- match: blockRegex(/^(?:\n *)*\n/),
935
- parse: ignoreCapture,
936
- react: function (node, output, state) {
937
- return "\n";
938
- },
939
- html: function (node, output, state) {
940
- return "\n";
941
- }
942
- },
943
- paragraph: {
944
- order: currOrder++,
945
- match: blockRegex(/^((?:[^\n]|\n(?! *\n))+)(?:\n *)+\n/),
946
- parse: parseCaptureInline,
947
- react: function (node, output, state) {
948
- return reactElement("div", state.key, {
949
- className: "paragraph",
950
- children: output(node.content, state)
951
- });
952
- },
953
- html: function (node, output, state) {
954
- var attributes = {
955
- class: "paragraph"
956
- };
957
- return htmlTag("div", output(node.content, state), attributes);
958
- }
959
- },
960
- escape: {
961
- order: currOrder++,
962
- // We don't allow escaping numbers, letters, or spaces here so that
963
- // backslashes used in plain text still get rendered. But allowing
964
- // escaping anything else provides a very flexible escape mechanism,
965
- // regardless of how this grammar is extended.
966
- match: inlineRegex(/^\\([^0-9A-Za-z\s])/),
967
- parse: function (capture, parse, state) {
968
- return {
969
- type: "text",
970
- content: capture[1]
971
- };
972
- },
973
- react: null,
974
- html: null
975
- },
976
- tableSeparator: {
977
- order: currOrder++,
978
- match: function (source, state) {
979
- if (!state.inTable) {
980
- return null;
981
- }
982
- return /^ *\| */.exec(source);
983
- },
984
- parse: function () {
985
- return {
986
- type: "tableSeparator"
987
- };
988
- },
989
- // These shouldn't be reached, but in case they are, be reasonable:
990
- react: function () {
991
- return " | ";
992
- },
993
- html: function () {
994
- return " &vert; ";
995
- }
996
- },
997
- autolink: {
998
- order: currOrder++,
999
- match: inlineRegex(/^<([^: >]+:\/[^ >]+)>/),
1000
- parse: function (capture, parse, state) {
1001
- return {
1002
- type: "link",
1003
- content: [{
1004
- type: "text",
1005
- content: capture[1]
1006
- }],
1007
- target: capture[1]
1008
- };
1009
- },
1010
- react: null,
1011
- html: null
1012
- },
1013
- mailto: {
1014
- order: currOrder++,
1015
- match: inlineRegex(/^<([^ >]+@[^ >]+)>/),
1016
- parse: function (capture, parse, state) {
1017
- var address = capture[1];
1018
- var target = capture[1];
1019
-
1020
- // Check for a `mailto:` already existing in the link:
1021
- if (!AUTOLINK_MAILTO_CHECK_R.test(target)) {
1022
- target = "mailto:" + target;
1023
- }
1024
- return {
1025
- type: "link",
1026
- content: [{
1027
- type: "text",
1028
- content: address
1029
- }],
1030
- target: target
1031
- };
1032
- },
1033
- react: null,
1034
- html: null
1035
- },
1036
- url: {
1037
- order: currOrder++,
1038
- match: inlineRegex(/^(https?:\/\/[^\s<]+[^<.,:;"')\]\s])/),
1039
- parse: function (capture, parse, state) {
1040
- return {
1041
- type: "link",
1042
- content: [{
1043
- type: "text",
1044
- content: capture[1]
1045
- }],
1046
- target: capture[1],
1047
- title: undefined
1048
- };
1049
- },
1050
- react: null,
1051
- html: null
1052
- },
1053
- link: {
1054
- order: currOrder++,
1055
- match: inlineRegex(new RegExp("^\\[(" + LINK_INSIDE + ")\\]\\(" + LINK_HREF_AND_TITLE + "\\)")),
1056
- parse: function (capture, parse, state) {
1057
- var link = {
1058
- content: parse(capture[1], state),
1059
- target: unescapeUrl(capture[2]),
1060
- title: capture[3]
1061
- };
1062
- return link;
1063
- },
1064
- react: function (node, output, state) {
1065
- return reactElement("a", state.key, {
1066
- href: sanitizeUrl(node.target),
1067
- title: node.title,
1068
- children: output(node.content, state)
1069
- });
1070
- },
1071
- html: function (node, output, state) {
1072
- var attributes = {
1073
- href: sanitizeUrl(node.target),
1074
- title: node.title
1075
- };
1076
- return htmlTag("a", output(node.content, state), attributes);
1077
- }
1078
- },
1079
- image: {
1080
- order: currOrder++,
1081
- match: inlineRegex(new RegExp("^!\\[(" + LINK_INSIDE + ")\\]\\(" + LINK_HREF_AND_TITLE + "\\)")),
1082
- parse: function (capture, parse, state) {
1083
- var image = {
1084
- alt: capture[1],
1085
- target: unescapeUrl(capture[2]),
1086
- title: capture[3]
1087
- };
1088
- return image;
1089
- },
1090
- react: function (node, output, state) {
1091
- return reactElement("img", state.key, {
1092
- src: sanitizeUrl(node.target),
1093
- alt: node.alt,
1094
- title: node.title
1095
- });
1096
- },
1097
- html: function (node, output, state) {
1098
- var attributes = {
1099
- src: sanitizeUrl(node.target),
1100
- alt: node.alt,
1101
- title: node.title
1102
- };
1103
- return htmlTag("img", "", attributes, false);
1104
- }
1105
- },
1106
- reflink: {
1107
- order: currOrder++,
1108
- match: inlineRegex(new RegExp(
1109
- // The first [part] of the link
1110
- "^\\[(" + LINK_INSIDE + ")\\]" +
1111
- // The [ref] target of the link
1112
- "\\s*\\[([^\\]]*)\\]")),
1113
- parse: function (capture, parse, state) {
1114
- return parseRef(capture, state, {
1115
- type: "link",
1116
- content: parse(capture[1], state)
1117
- });
1118
- },
1119
- react: null,
1120
- html: null
1121
- },
1122
- refimage: {
1123
- order: currOrder++,
1124
- match: inlineRegex(new RegExp(
1125
- // The first [part] of the link
1126
- "^!\\[(" + LINK_INSIDE + ")\\]" +
1127
- // The [ref] target of the link
1128
- "\\s*\\[([^\\]]*)\\]")),
1129
- parse: function (capture, parse, state) {
1130
- return parseRef(capture, state, {
1131
- type: "image",
1132
- alt: capture[1]
1133
- });
1134
- },
1135
- react: null,
1136
- html: null
1137
- },
1138
- em: {
1139
- order: currOrder /* same as strong/u */,
1140
- match: inlineRegex(new RegExp(
1141
- // only match _s surrounding words.
1142
- "^\\b_" + "((?:__|\\\\[\\s\\S]|[^\\\\_])+?)_" + "\\b" +
1143
- // Or match *s:
1144
- "|" +
1145
- // Only match *s that are followed by a non-space:
1146
- "^\\*(?=\\S)(" +
1147
- // Match at least one of:
1148
- "(?:" +
1149
- // - `**`: so that bolds inside italics don't close the
1150
- // italics
1151
- "\\*\\*|" +
1152
- // - escape sequence: so escaped *s don't close us
1153
- "\\\\[\\s\\S]|" +
1154
- // - whitespace: followed by a non-* (we don't
1155
- // want ' *' to close an italics--it might
1156
- // start a list)
1157
- "\\s+(?:\\\\[\\s\\S]|[^\\s\\*\\\\]|\\*\\*)|" +
1158
- // - non-whitespace, non-*, non-backslash characters
1159
- "[^\\s\\*\\\\]" + ")+?" +
1160
- // followed by a non-space, non-* then *
1161
- ")\\*(?!\\*)")),
1162
- quality: function (capture) {
1163
- // precedence by length, `em` wins ties:
1164
- return capture[0].length + 0.2;
1165
- },
1166
- parse: function (capture, parse, state) {
1167
- return {
1168
- content: parse(capture[2] || capture[1], state)
1169
- };
1170
- },
1171
- react: function (node, output, state) {
1172
- return reactElement("em", state.key, {
1173
- children: output(node.content, state)
1174
- });
1175
- },
1176
- html: function (node, output, state) {
1177
- return htmlTag("em", output(node.content, state));
1178
- }
1179
- },
1180
- strong: {
1181
- order: currOrder /* same as em */,
1182
- match: inlineRegex(/^\*\*((?:\\[\s\S]|[^\\])+?)\*\*(?!\*)/),
1183
- quality: function (capture) {
1184
- // precedence by length, wins ties vs `u`:
1185
- return capture[0].length + 0.1;
1186
- },
1187
- parse: parseCaptureInline,
1188
- react: function (node, output, state) {
1189
- return reactElement("strong", state.key, {
1190
- children: output(node.content, state)
1191
- });
1192
- },
1193
- html: function (node, output, state) {
1194
- return htmlTag("strong", output(node.content, state));
1195
- }
1196
- },
1197
- u: {
1198
- order: currOrder++ /* same as em&strong; increment for next rule */,
1199
- match: inlineRegex(/^__((?:\\[\s\S]|[^\\])+?)__(?!_)/),
1200
- quality: function (capture) {
1201
- // precedence by length, loses all ties
1202
- return capture[0].length;
1203
- },
1204
- parse: parseCaptureInline,
1205
- react: function (node, output, state) {
1206
- return reactElement("u", state.key, {
1207
- children: output(node.content, state)
1208
- });
1209
- },
1210
- html: function (node, output, state) {
1211
- return htmlTag("u", output(node.content, state));
1212
- }
1213
- },
1214
- del: {
1215
- order: currOrder++,
1216
- match: inlineRegex(/^~~(?=\S)((?:\\[\s\S]|~(?!~)|[^\s~\\]|\s(?!~~))+?)~~/),
1217
- parse: parseCaptureInline,
1218
- react: function (node, output, state) {
1219
- return reactElement("del", state.key, {
1220
- children: output(node.content, state)
1221
- });
1222
- },
1223
- html: function (node, output, state) {
1224
- return htmlTag("del", output(node.content, state));
1225
- }
1226
- },
1227
- inlineCode: {
1228
- order: currOrder++,
1229
- match: inlineRegex(/^(`+)([\s\S]*?[^`])\1(?!`)/),
1230
- parse: function (capture, parse, state) {
1231
- return {
1232
- content: capture[2].replace(INLINE_CODE_ESCAPE_BACKTICKS_R, "$1")
1233
- };
1234
- },
1235
- react: function (node, output, state) {
1236
- return reactElement("code", state.key, {
1237
- children: node.content
1238
- });
1239
- },
1240
- html: function (node, output, state) {
1241
- return htmlTag("code", sanitizeText(node.content));
1242
- }
1243
- },
1244
- br: {
1245
- order: currOrder++,
1246
- match: anyScopeRegex(/^ {2,}\n/),
1247
- parse: ignoreCapture,
1248
- react: function (node, output, state) {
1249
- return reactElement("br", state.key, EMPTY_PROPS);
1250
- },
1251
- html: function (node, output, state) {
1252
- return "<br>";
1253
- }
1254
- },
1255
- text: {
1256
- order: currOrder++,
1257
- // Here we look for anything followed by non-symbols,
1258
- // double newlines, or double-space-newlines
1259
- // We break on any symbol characters so that this grammar
1260
- // is easy to extend without needing to modify this regex
1261
- match: anyScopeRegex(/^[\s\S]+?(?=[^0-9A-Za-z\s\u00c0-\uffff]|\n\n| {2,}\n|\w+:\S|$)/),
1262
- parse: function (capture, parse, state) {
1263
- return {
1264
- content: capture[0]
1265
- };
1266
- },
1267
- react: function (node, output, state) {
1268
- return node.content;
1269
- },
1270
- html: function (node, output, state) {
1271
- return sanitizeText(node.content);
1272
- }
1273
- }
1274
- };
1275
-
1276
- /** (deprecated) */
1277
- var ruleOutput = function ruleOutput(rules, property) {
1278
- if (!property && typeof console !== "undefined") {
1279
- console.warn("simple-markdown ruleOutput should take 'react' or " + "'html' as the second argument.");
1280
- }
1281
- var nestedRuleOutput = function nestedRuleOutput(ast, outputFunc, state) {
1282
- // @ts-expect-error - TS2349 - This expression is not callable.
1283
- // Type 'unknown' has no call signatures.
1284
- return rules[ast.type][property](ast, outputFunc, state);
1285
- };
1286
- return nestedRuleOutput;
1287
- };
1288
-
1289
- /** (deprecated)
1290
- */
1291
- var reactFor = function reactFor(outputFunc) {
1292
- var nestedOutput = function nestedOutput(ast, state) {
1293
- state = state || {};
1294
- if (Array.isArray(ast)) {
1295
- var oldKey = state.key;
1296
- var result = [];
1297
-
1298
- // map nestedOutput over the ast, except group any text
1299
- // nodes together into a single string output.
1300
- var lastResult = null;
1301
- for (var i = 0; i < ast.length; i++) {
1302
- state.key = "" + i;
1303
- var nodeOut = nestedOutput(ast[i], state);
1304
- if (typeof nodeOut === "string" && typeof lastResult === "string") {
1305
- // @ts-expect-error - TS2322 - Type 'string' is not assignable to type 'null'.
1306
- lastResult = lastResult + nodeOut;
1307
- result[result.length - 1] = lastResult;
1308
- } else {
1309
- result.push(nodeOut);
1310
- // @ts-expect-error - TS2322 - Type 'ReactNode' is not assignable to type 'null'.
1311
- lastResult = nodeOut;
1312
- }
1313
- }
1314
- state.key = oldKey;
1315
- return result;
1316
- } else {
1317
- return outputFunc(ast, nestedOutput, state);
1318
- }
1319
- };
1320
- return nestedOutput;
1321
- };
1322
-
1323
- /** (deprecated)
1324
- */
1325
- var htmlFor = function htmlFor(outputFunc) {
1326
- var nestedOutput = function nestedOutput(ast, state) {
1327
- state = state || {};
1328
- if (Array.isArray(ast)) {
1329
- return ast.map(function (node) {
1330
- return nestedOutput(node, state);
1331
- }).join("");
1332
- } else {
1333
- return outputFunc(ast, nestedOutput, state);
1334
- }
1335
- };
1336
- return nestedOutput;
1337
- };
1338
- var outputFor = function outputFor(rules, property, defaultState = {}) {
1339
- if (!property) {
1340
- throw new Error("simple-markdown: outputFor: `property` must be " + "defined. " + "if you just upgraded, you probably need to replace `outputFor` " + "with `reactFor`");
1341
- }
1342
- var latestState;
1343
- var arrayRule = rules.Array || defaultRules.Array;
1344
-
1345
- // Tricks to convince tsc that this var is not null:
1346
- // @ts-expect-error - TS2538 - Type 'symbol' cannot be used as an index type.
1347
- var arrayRuleCheck = arrayRule[property];
1348
- if (!arrayRuleCheck) {
1349
- throw new Error("simple-markdown: outputFor: to join nodes of type `" +
1350
- // @ts-expect-error - TS2469 - The '+' operator cannot be applied to type 'symbol'.
1351
- property + "` you must provide an `Array:` joiner rule with that type, " + "Please see the docs for details on specifying an Array rule.");
1352
- }
1353
- var arrayRuleOutput = arrayRuleCheck;
1354
- var nestedOutput = function nestedOutput(ast, state) {
1355
- state = state || latestState;
1356
- latestState = state;
1357
- if (Array.isArray(ast)) {
1358
- return arrayRuleOutput(ast, nestedOutput, state);
1359
- } else {
1360
- // @ts-expect-error - TS2349 - This expression is not callable.
1361
- // Type 'unknown' has no call signatures.
1362
- return rules[ast.type][property](ast, nestedOutput, state);
1363
- }
1364
- };
1365
- var outerOutput = function outerOutput(ast, state) {
1366
- latestState = populateInitialState(state, defaultState);
1367
- return nestedOutput(ast, latestState);
1368
- };
1369
- return outerOutput;
1370
- };
1371
-
1372
- // @ts-expect-error - TS2345 - Argument of type 'DefaultRules' is not assignable to parameter of type 'ParserRules'.
1373
- var defaultRawParse = parserFor(defaultRules);
1374
- var defaultBlockParse = function defaultBlockParse(source, state) {
1375
- state = state || {};
1376
- state.inline = false;
1377
- return defaultRawParse(source, state);
1378
- };
1379
- var defaultInlineParse = function defaultInlineParse(source, state) {
1380
- state = state || {};
1381
- state.inline = true;
1382
- return defaultRawParse(source, state);
1383
- };
1384
- var defaultImplicitParse = function defaultImplicitParse(source, state) {
1385
- var isBlock = BLOCK_END_R.test(source);
1386
- state = state || {};
1387
- state.inline = !isBlock;
1388
- return defaultRawParse(source, state);
1389
- };
1390
- var defaultReactOutput = outputFor(defaultRules, "react");
1391
- var defaultHtmlOutput = outputFor(defaultRules, "html");
1392
- var markdownToReact = function markdownToReact(source, state) {
1393
- return defaultReactOutput(defaultBlockParse(source, state), state);
1394
- };
1395
- var markdownToHtml = function markdownToHtml(source, state) {
1396
- return defaultHtmlOutput(defaultBlockParse(source, state), state);
1397
- };
1398
-
1399
- // TODO: This needs definition
1400
-
1401
- var ReactMarkdown = function ReactMarkdown(props) {
1402
- var divProps = {};
1403
- for (var prop in props) {
1404
- if (prop !== "source" && Object.prototype.hasOwnProperty.call(props, prop)) {
1405
- divProps[prop] = props[prop];
1406
- }
1407
- }
1408
- divProps.children = markdownToReact(props.source);
1409
- return reactElement("div", null, divProps);
1410
- };
1411
- var SimpleMarkdown = {
1412
- defaultRules: defaultRules,
1413
- parserFor: parserFor,
1414
- outputFor: outputFor,
1415
- inlineRegex: inlineRegex,
1416
- blockRegex: blockRegex,
1417
- anyScopeRegex: anyScopeRegex,
1418
- parseInline: parseInline,
1419
- parseBlock: parseBlock,
1420
- // default wrappers:
1421
- markdownToReact: markdownToReact,
1422
- markdownToHtml: markdownToHtml,
1423
- ReactMarkdown: ReactMarkdown,
1424
- defaultBlockParse: defaultBlockParse,
1425
- defaultInlineParse: defaultInlineParse,
1426
- defaultImplicitParse: defaultImplicitParse,
1427
- defaultReactOutput: defaultReactOutput,
1428
- defaultHtmlOutput: defaultHtmlOutput,
1429
- preprocess: preprocess,
1430
- sanitizeText: sanitizeText,
1431
- sanitizeUrl: sanitizeUrl,
1432
- unescapeUrl: unescapeUrl,
1433
- htmlTag: htmlTag,
1434
- reactElement: reactElement,
1435
- // deprecated:
1436
- defaultRawParse: defaultRawParse,
1437
- ruleOutput: ruleOutput,
1438
- reactFor: reactFor,
1439
- htmlFor: htmlFor,
1440
- defaultParse: function (...args) {
1441
- if (typeof console !== "undefined") {
1442
- console.warn("defaultParse is deprecated, please use `defaultImplicitParse`");
1443
- }
1444
- // @ts-expect-error - Argument of type 'any[]' is not assignable to parameter of type '[node: ASTNode, state?: State | null | undefined]'. Target requires 1 element(s) but source may have fewer.
1445
- return defaultImplicitParse.apply(null, args);
1446
- },
1447
- defaultOutput: function (...args) {
1448
- if (typeof console !== "undefined") {
1449
- console.warn("defaultOutput is deprecated, please use `defaultReactOutput`");
1450
- }
1451
- // @ts-expect-error - Argument of type 'any[]' is not assignable to parameter of type '[node: ASTNode, state?: State | null | undefined]'. Target requires 1 element(s) but source may have fewer.
1452
- return defaultReactOutput.apply(null, args);
1453
- }
1454
- };
1455
-
1456
- export { SimpleMarkdown as default, libVersion };
1457
- //# sourceMappingURL=index.js.map