This repository has been archived by the owner on Nov 4, 2019. It is now read-only.
forked from quantizor/markdown-to-jsx
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
1564 lines (1373 loc) · 43.3 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* @jsx h */
/**
* markdown-to-jsx@6 is a fork of [simple-markdown v0.2.2](https://github.com/Khan/simple-markdown)
* from Khan Academy. Thank you Khan devs for making such an awesome and extensible
* parsing infra... without it, half of the optimizations here wouldn't be feasible. 🙏🏼
*/
import React from 'react';
import unquote from 'unquote';
/** TODO: Drop for React 16? */
const ATTRIBUTE_TO_JSX_PROP_MAP = {
accesskey: 'accessKey',
allowfullscreen: 'allowFullScreen',
allowtransparency: 'allowTransparency',
autocomplete: 'autoComplete',
autofocus: 'autoFocus',
autoplay: 'autoPlay',
cellpadding: 'cellPadding',
cellspacing: 'cellSpacing',
charset: 'charSet',
class: 'className',
classid: 'classId',
colspan: 'colSpan',
contenteditable: 'contentEditable',
contextmenu: 'contextMenu',
crossorigin: 'crossOrigin',
enctype: 'encType',
for: 'htmlFor',
formaction: 'formAction',
formenctype: 'formEncType',
formmethod: 'formMethod',
formnovalidate: 'formNoValidate',
formtarget: 'formTarget',
frameborder: 'frameBorder',
hreflang: 'hrefLang',
inputmode: 'inputMode',
keyparams: 'keyParams',
keytype: 'keyType',
marginheight: 'marginHeight',
marginwidth: 'marginWidth',
maxlength: 'maxLength',
mediagroup: 'mediaGroup',
minlength: 'minLength',
novalidate: 'noValidate',
radiogroup: 'radioGroup',
readonly: 'readOnly',
rowspan: 'rowSpan',
spellcheck: 'spellCheck',
srcdoc: 'srcDoc',
srclang: 'srcLang',
srcset: 'srcSet',
tabindex: 'tabIndex',
usemap: 'useMap',
};
const namedCodesToUnicode = {
amp: '\u0026',
apos: '\u0027',
gt: '\u003e',
lt: '\u003c',
nbsp: '\u00a0',
quot: '\u201c',
};
const DO_NOT_PROCESS_HTML_ELEMENTS = ['style', 'script'];
/**
* the attribute extractor regex looks for a valid attribute name,
* followed by an equal sign (whitespace around the equal sign is allowed), followed
* by one of the following:
*
* 1. a single quote-bounded string, e.g. 'foo'
* 2. a double quote-bounded string, e.g. "bar"
* 3. an interpolation, e.g. {something}
*
* JSX can be be interpolated into itself and is passed through the compiler using
* the same options and setup as the current run.
*
* <Something children={<SomeOtherThing />} />
* ==================
* ↳ children: [<SomeOtherThing />]
*
* Otherwise, interpolations are handled as strings or simple booleans
* unless HTML syntax is detected.
*
* <Something color={green} disabled={true} />
* ===== ====
* ↓ ↳ disabled: true
* ↳ color: "green"
*
* Numbers are not parsed at this time due to complexities around int, float,
* and the upcoming bigint functionality that would make handling it unwieldy.
* Parse the string in your component as desired.
*
* <Something someBigNumber={123456789123456789} />
* ==================
* ↳ someBigNumber: "123456789123456789"
*/
const ATTR_EXTRACTOR_R = /([-A-Z0-9_:]+)(?:\s*=\s*(?:(?:"((?:\\.|[^"])*)")|(?:'((?:\\.|[^'])*)')|(?:\{((?:\\.|{[^}]*?}|[^}])*)\})))?/gi;
/** TODO: Write explainers for each of these */
const AUTOLINK_MAILTO_CHECK_R = /mailto:/i;
const BLOCK_END_R = /\n{2,}$/;
const BLOCKQUOTE_R = /^( *>[^\n]+(\n[^\n]+)*\n*)+\n{2,}/;
const BLOCKQUOTE_TRIM_LEFT_MULTILINE_R = /^ *> ?/gm;
const BREAK_LINE_R = /^ {2,}\n/;
const BREAK_THEMATIC_R = /^(?:( *[-*_]) *){3,}(?:\n *)+\n/;
const CODE_BLOCK_FENCED_R = /^\s*(`{3,}|~{3,}) *(\S+)? *\n([\s\S]+?)\s*\1 *(?:\n *)+\n?/;
const CODE_BLOCK_R = /^(?: {4}[^\n]+\n*)+(?:\n *)+\n?/;
const CODE_INLINE_R = /^(`+)\s*([\s\S]*?[^`])\s*\1(?!`)/;
const CONSECUTIVE_NEWLINE_R = /^(?:\n *)*\n/;
const CR_NEWLINE_R = /\r\n?/g;
const FOOTNOTE_R = /^\[\^(.*)\](:.*)\n/;
const FOOTNOTE_REFERENCE_R = /^\[\^(.*)\]/;
const FORMFEED_R = /\f/g;
const GFM_TASK_R = /^\s*?\[(x|\s)\]/;
const HEADING_R = /^ *(#{1,6}) *([^\n]+)\n{0,2}/;
const HEADING_SETEXT_R = /^([^\n]+)\n *(=|-){3,} *(?:\n *)+\n/;
/**
* Explanation:
*
* 1. Look for a starting tag, preceeded by any amount of spaces
* ^ *<
*
* 2. Capture the tag name (capture 1)
* ([^ >/]+)
*
* 3. Ignore a space after the starting tag and capture the attribute portion of the tag (capture 2)
* ?([^>]*)\/{0}>
*
* 4. Ensure a matching closing tag is present in the rest of the input string
* (?=[\s\S]*<\/\1>)
*
* 5. Capture everything until the matching closing tag -- this might include additional pairs
* of the same tag type found in step 2 (capture 3)
* ((?:[\s\S]*?(?:<\1[^>]*>[\s\S]*?<\/\1>)*[\s\S]*?)*?)<\/\1>
*
* 6. Capture excess newlines afterward
* \n*
*/
const HTML_BLOCK_ELEMENT_R = /^ *(?!<[a-z][^ >/]* ?\/>)<([a-z][^ >/]*) ?([^>]*)\/{0}>\n?(\s*(?:<\1[^>]*?>[\s\S]*?<\/\1>|(?!<\1)[\s\S])*?)<\/\1>\n*/i;
const HTML_CHAR_CODE_R = /&([a-z]+);/g;
const HTML_COMMENT_R = /^<!--.*?-->/;
/**
* borrowed from React 15(https://github.com/facebook/react/blob/894d20744cba99383ffd847dbd5b6e0800355a5c/src/renderers/dom/shared/HTMLDOMPropertyConfig.js)
*/
const HTML_CUSTOM_ATTR_R = /^(data|aria|x)-[a-z_][a-z\d_.-]*$/;
const HTML_SELF_CLOSING_ELEMENT_R = /^ *<([a-z][a-z0-9:]*)(?:\s+((?:<.*?>|[^>])*))?\/?>(?!<\/\1>)(\s*\n)?/i;
const INTERPOLATION_R = /^\{.*\}$/;
const LINK_AUTOLINK_BARE_URL_R = /^(https?:\/\/[^\s<]+[^<.,:;"')\]\s])/;
const LINK_AUTOLINK_MAILTO_R = /^<([^ >]+@[^ >]+)>/;
const LINK_AUTOLINK_R = /^<([^ >]+:\/[^ >]+)>/;
const LIST_ITEM_END_R = / *\n+$/;
const LIST_LOOKBEHIND_R = /(?:^|\n)( *)$/;
const CAPTURE_LETTER_AFTER_HYPHEN = /-([a-z])?/gi;
const NP_TABLE_R = /^(.*\|?.*)\n *(\|? *[-:]+ *\|[-| :]*)\n((?:.*\|.*\n)*)\n?/;
const PARAGRAPH_R = /^((?:[^\n]|\n(?! *\n))+)(?:\n *)+\n/;
const REFERENCE_IMAGE_OR_LINK = /^\[([^\]]*)\]:\s*(\S+)\s*("([^"]*)")?/;
const REFERENCE_IMAGE_R = /^!\[([^\]]*)\] ?\[([^\]]*)\]/;
const REFERENCE_LINK_R = /^\[([^\]]*)\] ?\[([^\]]*)\]/;
const SQUARE_BRACKETS_R = /(\[|\])/g;
const SHOULD_RENDER_AS_BLOCK_R = /(\n|^[-*]\s|^#|^ {2,}|^-{2,}|^>\s)/;
const TAB_R = /\t/g;
const TABLE_TRIM_PIPES = /(^ *\||\| *$)/g;
const TABLE_CENTER_ALIGN = /^ *:-+: *$/;
const TABLE_LEFT_ALIGN = /^ *:-+ *$/;
const TABLE_RIGHT_ALIGN = /^ *-+: *$/;
const TABLE_ROW_SPLIT = / *\| */;
const TEXT_BOLD_R = /^([*_])\1((?:\[.*?\][([].*?[)\]]|<.*?>(?:.*?<.*?>)?|`.*?`|~+.*?~+|.)*?)\1\1(?!\1)/;
const TEXT_EMPHASIZED_R = /^([*_])((?:\[.*?\][([].*?[)\]]|<.*?>(?:.*?<.*?>)?|`.*?`|~+.*?~+|.)*?)\1(?!\1)/;
const TEXT_STRIKETHROUGHED_R = /^~~((?:\[.*?\]|<.*?>(?:.*?<.*?>)?|`.*?`|.)*?)~~/;
const TEXT_ESCAPED_R = /^\\([^0-9A-Za-z\s])/;
const TEXT_PLAIN_R = /^[\s\S]+?(?=[^0-9A-Z\s\u00c0-\uffff&;.()'"]|\d+\.|\n\n| {2,}\n|\w+:\S|$)/i;
const TRIM_NEWLINES_AND_TRAILING_WHITESPACE_R = /(^\n+|(\n|\s)+$)/g;
const HTML_LEFT_TRIM_AMOUNT_R = /^([ \t]*)/;
const UNESCAPE_URL_R = /\\([^0-9A-Z\s])/gi;
// recognize a `*` `-`, `+`, `1.`, `2.`... list bullet
const LIST_BULLET = '(?:[*+-]|\\d+\\.)';
// recognize the start of a list item:
// leading space plus a bullet plus a space (` * `)
const LIST_ITEM_PREFIX = '( *)(' + LIST_BULLET + ') +';
const LIST_ITEM_PREFIX_R = new RegExp('^' + LIST_ITEM_PREFIX);
// recognize an individual list item:
// * hi
// this is part of the same item
//
// as is this, which is a new paragraph in the same item
//
// * but this is not part of the same item
const LIST_ITEM_R = new RegExp(
LIST_ITEM_PREFIX +
'[^\\n]*(?:\\n' +
'(?!\\1' +
LIST_BULLET +
' )[^\\n]*)*(\\n|$)',
'gm'
);
// check whether a list item has paragraphs: if it does,
// we leave the newlines at the end
const LIST_R = new RegExp(
'^( *)(' +
LIST_BULLET +
') ' +
'[\\s\\S]+?(?:\\n{2,}(?! )' +
'(?!\\1' +
LIST_BULLET +
' (?!' +
LIST_BULLET +
' ))\\n*' +
// the \\s*$ here is so that we can parse the inside of nested
// lists, where our content might end before we receive two `\n`s
'|\\s*\\n*$)'
);
const LINK_INSIDE = '(?:\\[[^\\]]*\\]|[^\\[\\]]|\\](?=[^\\[]*\\]))*';
const LINK_HREF_AND_TITLE =
'\\s*<?((?:[^\\s\\\\]|\\\\.)*?)>?(?:\\s+[\'"]([\\s\\S]*?)[\'"])?\\s*';
const LINK_R = new RegExp(
'^\\[(' + LINK_INSIDE + ')\\]\\(' + LINK_HREF_AND_TITLE + '\\)'
);
const IMAGE_R = new RegExp(
'^!\\[(' + LINK_INSIDE + ')\\]\\(' + LINK_HREF_AND_TITLE + '\\)'
);
const BLOCK_SYNTAXES = [
BLOCKQUOTE_R,
CODE_BLOCK_R,
CODE_BLOCK_FENCED_R,
HEADING_R,
HEADING_SETEXT_R,
HTML_BLOCK_ELEMENT_R,
HTML_COMMENT_R,
HTML_SELF_CLOSING_ELEMENT_R,
LIST_ITEM_R,
LIST_R,
NP_TABLE_R,
PARAGRAPH_R,
];
function containsBlockSyntax(input) {
return BLOCK_SYNTAXES.some(r => r.test(input));
}
// based on https://stackoverflow.com/a/18123682/1141611
// not complete, but probably good enough
function slugify(str) {
return str
.replace(/[ÀÁÂÃÄÅàáâãäåæÆ]/g, 'a')
.replace(/[çÇ]/g, 'c')
.replace(/[ðÐ]/g, 'd')
.replace(/[ÈÉÊËéèêë]/g, 'e')
.replace(/[ÏïÎîÍíÌì]/g, 'i')
.replace(/[Ññ]/g, 'n')
.replace(/[øØœŒÕõÔôÓóÒò]/g, 'o')
.replace(/[ÜüÛûÚúÙù]/g, 'u')
.replace(/[ŸÿÝý]/g, 'y')
.replace(/[^a-z0-9- ]/gi, '')
.replace(/ /gi, '-')
.toLowerCase();
}
function parseTableAlignCapture(alignCapture) {
if (TABLE_RIGHT_ALIGN.test(alignCapture)) {
return 'right';
} else if (TABLE_CENTER_ALIGN.test(alignCapture)) {
return 'center';
} else if (TABLE_LEFT_ALIGN.test(alignCapture)) {
return 'left';
}
return null;
}
function parseTableHeader(capture, parse, state) {
const headerText = capture[1]
.replace(TABLE_TRIM_PIPES, '')
.trim()
.split(TABLE_ROW_SPLIT);
return headerText.map(function(text) {
return parse(text, state);
});
}
function parseTableAlign(capture /*, parse, state*/) {
const alignText = capture[2]
.replace(TABLE_TRIM_PIPES, '')
.trim()
.split(TABLE_ROW_SPLIT);
return alignText.map(parseTableAlignCapture);
}
function parseTableCells(capture, parse, state) {
const rowsText = capture[3]
.trim()
.split('\n');
return rowsText.map(function(rowText) {
return rowText
.replace(TABLE_TRIM_PIPES, '')
.split(TABLE_ROW_SPLIT)
.map(function(text) {
return parse(text.trim(), state);
});
});
}
function parseTable(capture, parse, state) {
state.inline = true;
const header = parseTableHeader(capture, parse, state);
const align = parseTableAlign(capture, parse, state);
const cells = parseTableCells(capture, parse, state);
state.inline = false;
return {
align: align,
cells: cells,
header: header,
type: 'table',
};
}
function getTableStyle(node, colIndex) {
return node.align[colIndex] == null
? {}
: {
textAlign: node.align[colIndex],
};
}
/** TODO: remove for react 16 */
function normalizeAttributeKey(key) {
const hyphenIndex = key.indexOf('-');
if (hyphenIndex !== -1 && key.match(HTML_CUSTOM_ATTR_R) === null) {
key = key.replace(CAPTURE_LETTER_AFTER_HYPHEN, function(_, letter) {
return letter.toUpperCase();
});
}
return key;
}
function attributeValueToJSXPropValue(key, value) {
if (key === 'style') {
return value.split(/;\s?/).reduce(function(styles, kvPair) {
const key = kvPair.slice(0, kvPair.indexOf(':'));
// snake-case to camelCase
// also handles PascalCasing vendor prefixes
const camelCasedKey = key.replace(/(-[a-z])/g, substr =>
substr[1].toUpperCase()
);
// key.length + 1 to skip over the colon
styles[camelCasedKey] = kvPair.slice(key.length + 1).trim();
return styles;
}, {});
} else if (value.match(INTERPOLATION_R)) {
// return as a string and let the consumer decide what to do with it
value = value.slice(1, value.length - 1);
}
if (value === 'true') {
return true;
} else if (value === 'false') {
return false;
}
return value;
}
function normalizeWhitespace(source) {
return source
.replace(CR_NEWLINE_R, '\n')
.replace(FORMFEED_R, '')
.replace(TAB_R, ' ');
}
/**
* Creates a parser for a given set of rules, with the precedence
* specified as a list of rules.
*
* @rules: an object containing
* rule type -> {match, order, parse} objects
* (lower order is higher precedence)
* (Note: `order` is added to defaultRules after creation so that
* the `order` of defaultRules in the source matches the `order`
* of defaultRules in terms of `order` fields.)
*
* @returns The resulting parse function, with the following parameters:
* @source: the input source string to be parsed
* @state: an optional object to be threaded through parse
* calls. Allows clients to add stateful operations to
* parsing, such as keeping track of how many levels deep
* some nesting is. For an example use-case, see passage-ref
* parsing in src/widgets/passage/passage-markdown.jsx
*/
function parserFor(rules) {
// Sorts rules in order of increasing order, then
// ascending rule name in case of ties.
let ruleList = Object.keys(rules);
/* istanbul ignore next */
if (process.env.NODE_ENV !== 'production') {
ruleList.forEach(function(type) {
let order = rules[type].order;
if (
process.env.NODE_ENV !== 'production' &&
(typeof order !== 'number' || !isFinite(order))
) {
console.warn(
'markdown-to-jsx: Invalid order for rule `' + type + '`: ' + order
);
}
});
}
ruleList.sort(function(typeA, typeB) {
let orderA = rules[typeA].order;
let orderB = rules[typeB].order;
// First sort based on increasing order
if (orderA !== orderB) {
return orderA - orderB;
// Then based on increasing unicode lexicographic ordering
} else if (typeA < typeB) {
return -1;
}
return 1;
});
function nestedParse(source, state) {
let result = [];
// We store the previous capture so that match functions can
// use some limited amount of lookbehind. Lists use this to
// ensure they don't match arbitrary '- ' or '* ' in inline
// text (see the list rule for more information).
let prevCapture = '';
while (source) {
let i = 0;
while (i < ruleList.length) {
const ruleType = ruleList[i];
const rule = rules[ruleType];
const capture = rule.match(source, state, prevCapture);
if (capture) {
const currCaptureString = capture[0];
source = source.substring(currCaptureString.length);
const parsed = rule.parse(capture, nestedParse, state);
// We also let rules override the default type of
// their parsed node if they would like to, so that
// there can be a single output function for all links,
// even if there are several rules to parse them.
if (parsed.type == null) {
parsed.type = ruleType;
}
result.push(parsed);
prevCapture = currCaptureString;
break;
}
i++;
}
}
return result;
}
return function outerParse(source, state) {
return nestedParse(normalizeWhitespace(source), state);
};
}
// Creates a match function for an inline scoped or simple element from a regex
function inlineRegex(regex) {
return function match(source, state) {
if (state.inline) {
return regex.exec(source);
} else {
return null;
}
};
}
// basically any inline element except links
function simpleInlineRegex(regex) {
return function match(source, state) {
if (state.inline || state.simple) {
return regex.exec(source);
} else {
return null;
}
};
}
// Creates a match function for a block scoped element from a regex
function blockRegex(regex) {
return function match(source, state) {
if (state.inline || state.simple) {
return null;
} else {
return regex.exec(source);
}
};
}
// Creates a match function from a regex, ignoring block/inline scope
function anyScopeRegex(regex) {
return function match(source /*, state*/) {
return regex.exec(source);
};
}
function reactFor(outputFunc) {
return function nestedReactOutput(ast, state) {
state = state || {};
if (Array.isArray(ast)) {
const oldKey = state.key;
const result = [];
// map nestedOutput over the ast, except group any text
// nodes together into a single string output.
let lastWasString = false;
for (let i = 0; i < ast.length; i++) {
state.key = i;
const nodeOut = nestedReactOutput(ast[i], state);
const isString = typeof nodeOut === 'string';
if (isString && lastWasString) {
result[result.length - 1] += nodeOut;
} else {
result.push(nodeOut);
}
lastWasString = isString;
}
state.key = oldKey;
return result;
}
return outputFunc(ast, nestedReactOutput, state);
};
}
function sanitizeUrl(url) {
try {
const decoded = decodeURIComponent(url);
if (decoded.match(/^\s*javascript:/i)) {
if (process.env.NODE_ENV !== 'production') {
console.warn(
'Anchor URL contains an unsafe JavaScript expression, it will not be rendered.',
decoded
);
}
return null;
}
} catch (e) {
if (process.env.NODE_ENV !== 'production') {
console.warn(
'Anchor URL could not be decoded due to malformed syntax or characters, it will not be rendered.',
url
);
}
// decodeURIComponent sometimes throws a URIError
// See `decodeURIComponent('a%AFc');`
// http://stackoverflow.com/questions/9064536/javascript-decodeuricomponent-malformed-uri-exception
return null;
}
return url;
}
function unescapeUrl(rawUrlString) {
return rawUrlString.replace(UNESCAPE_URL_R, '$1');
}
/**
* Everything inline, including links.
*/
function parseInline(parse, content, state) {
const isCurrentlyInline = state.inline || false;
const isCurrentlySimple = state.simple || false;
state.inline = true;
state.simple = true;
const result = parse(content, state);
state.inline = isCurrentlyInline;
state.simple = isCurrentlySimple;
return result;
}
/**
* Anything inline that isn't a link.
*/
function parseSimpleInline(parse, content, state) {
const isCurrentlyInline = state.inline || false;
const isCurrentlySimple = state.simple || false;
state.inline = false;
state.simple = true;
const result = parse(content, state);
state.inline = isCurrentlyInline;
state.simple = isCurrentlySimple;
return result;
}
function parseBlock(parse, content, state) {
state.inline = false;
return parse(content + '\n\n', state);
}
function parseCaptureInline(capture, parse, state) {
return {
content: parseInline(parse, capture[1], state),
};
}
function captureNothing() {
return {};
}
function renderNothing() {
return null;
}
function ruleOutput(rules) {
return function nestedRuleOutput(ast, outputFunc, state) {
return rules[ast.type].react(ast, outputFunc, state);
};
}
function cx(...args) {
return args.filter(Boolean).join(' ');
}
function get(src, path, fb) {
let ptr = src;
const frags = path.split('.');
while (frags.length) {
ptr = ptr[frags[0]];
if (ptr === undefined) break;
else frags.shift();
}
return ptr || fb;
}
function getTag(tag, overrides) {
const override = get(overrides, tag);
if (!override) return tag;
return typeof override === 'function' || (typeof override === 'object' && 'render' in override)
? override
: get(overrides, `${tag}.component`, tag);
}
/**
* anything that must scan the tree before everything else
*/
const PARSE_PRIORITY_MAX = 1;
/**
* scans for block-level constructs
*/
const PARSE_PRIORITY_HIGH = 2;
/**
* inline w/ more priority than other inline
*/
const PARSE_PRIORITY_MED = 3;
/**
* inline elements
*/
const PARSE_PRIORITY_LOW = 4;
/**
* bare text and stuff that is considered leftovers
*/
const PARSE_PRIORITY_MIN = 5;
export function compiler(markdown, options) {
options = options || {};
options.overrides = options.overrides || {};
options.slugify = options.slugify || slugify;
const createElementFn = options.createElement || React.createElement;
// eslint-disable-next-line no-unused-vars
function h(tag, props, ...children) {
const overrideProps = get(options.overrides, `${tag}.props`, {});
return createElementFn(
getTag(tag, options.overrides),
{
...props,
...overrideProps,
className:
cx(props && props.className, overrideProps.className) || undefined,
},
...children
);
}
function compile(input) {
let inline = false;
if (options.forceInline) {
inline = true;
} else if (!options.forceBlock) {
/**
* should not contain any block-level markdown like newlines, lists, headings,
* thematic breaks, blockquotes, tables, etc
*/
inline = SHOULD_RENDER_AS_BLOCK_R.test(input) === false;
}
const arr = emitter(
parser(
inline
? input
: `${input.replace(TRIM_NEWLINES_AND_TRAILING_WHITESPACE_R, '')}\n\n`,
{ inline }
)
);
let jsx;
if (arr.length > 1) {
jsx = inline ? <span key="outer">{arr}</span> : <div key="outer">{arr}</div>;
} else if (arr.length === 1) {
jsx = arr[0];
// TODO: remove this for React 16
if (typeof jsx === 'string') {
jsx = <span key="outer">{jsx}</span>;
}
} else {
// TODO: return null for React 16
jsx = <span key="outer" />;
}
return jsx;
}
function attrStringToMap(str) {
const attributes = str.match(ATTR_EXTRACTOR_R);
return attributes
? attributes.reduce(function(map, raw, index) {
const delimiterIdx = raw.indexOf('=');
if (delimiterIdx !== -1) {
const key = normalizeAttributeKey(
raw.slice(0, delimiterIdx)
).trim();
const value = unquote(raw.slice(delimiterIdx + 1).trim());
const mappedKey = ATTRIBUTE_TO_JSX_PROP_MAP[key] || key;
const normalizedValue = (map[
mappedKey
] = attributeValueToJSXPropValue(key, value));
if (
HTML_BLOCK_ELEMENT_R.test(normalizedValue) ||
HTML_SELF_CLOSING_ELEMENT_R.test(normalizedValue)
) {
map[mappedKey] = React.cloneElement(
compile(normalizedValue.trim()),
{ key: index }
);
}
} else {
map[ATTRIBUTE_TO_JSX_PROP_MAP[raw] || raw] = true;
}
return map;
}, {})
: undefined;
}
/* istanbul ignore next */
if (process.env.NODE_ENV !== 'production') {
if (typeof markdown !== 'string') {
throw new Error(`markdown-to-jsx: the first argument must be
a string`);
}
if (
Object.prototype.toString.call(options.overrides) !== '[object Object]'
) {
throw new Error(`markdown-to-jsx: options.overrides (second argument property) must be
undefined or an object literal with shape:
{
htmltagname: {
component: string|ReactComponent(optional),
props: object(optional)
}
}`);
}
}
const footnotes = [];
const refs = {};
/**
* each rule's react() output function goes through our custom h() JSX pragma;
* this allows the override functionality to be automatically applied
*/
const rules = {
blockQuote: {
match: blockRegex(BLOCKQUOTE_R),
order: PARSE_PRIORITY_HIGH,
parse(capture, parse, state) {
return {
content: parse(
capture[0].replace(BLOCKQUOTE_TRIM_LEFT_MULTILINE_R, ''),
state
),
};
},
react(node, output, state) {
return (
<blockquote key={state.key}>{output(node.content, state)}</blockquote>
);
},
},
breakLine: {
match: anyScopeRegex(BREAK_LINE_R),
order: PARSE_PRIORITY_HIGH,
parse: captureNothing,
react(_, __, state) {
return <br key={state.key} />;
},
},
breakThematic: {
match: blockRegex(BREAK_THEMATIC_R),
order: PARSE_PRIORITY_HIGH,
parse: captureNothing,
react(_, __, state) {
return <hr key={state.key} />;
},
},
codeBlock: {
match: blockRegex(CODE_BLOCK_R),
order: PARSE_PRIORITY_MAX,
parse(capture /*, parse, state*/) {
let content = capture[0].replace(/^ {4}/gm, '').replace(/\n+$/, '');
return {
content: content,
lang: undefined,
};
},
react(node, output, state) {
return (
<pre key={state.key}>
<code className={node.lang ? `lang-${node.lang}` : ''}>
{node.content}
</code>
</pre>
);
},
},
codeFenced: {
match: blockRegex(CODE_BLOCK_FENCED_R),
order: PARSE_PRIORITY_MAX,
parse(capture /*, parse, state*/) {
return {
content: capture[3],
lang: capture[2] || undefined,
type: 'codeBlock',
};
},
},
codeInline: {
match: simpleInlineRegex(CODE_INLINE_R),
order: PARSE_PRIORITY_LOW,
parse(capture /*, parse, state*/) {
return {
content: capture[2],
};
},
react(node, output, state) {
return <code key={state.key}>{node.content}</code>;
},
},
/**
* footnotes are emitted at the end of compilation in a special <footer> block
*/
footnote: {
match: blockRegex(FOOTNOTE_R),
order: PARSE_PRIORITY_MAX,
parse(capture /*, parse, state*/) {
footnotes.push({
footnote: capture[2],
identifier: capture[1],
});
return {};
},
react: renderNothing,
},
footnoteReference: {
match: inlineRegex(FOOTNOTE_REFERENCE_R),
order: PARSE_PRIORITY_HIGH,
parse(capture /*, parse*/) {
return {
content: capture[1],
target: `#${capture[1]}`,
};
},
react(node, output, state) {
return (
<a key={state.key} href={sanitizeUrl(node.target)}>
<sup key={state.key}>{node.content}</sup>
</a>
);
},
},
gfmTask: {
match: inlineRegex(GFM_TASK_R),
order: PARSE_PRIORITY_HIGH,
parse(capture /*, parse, state*/) {
return {
completed: capture[1].toLowerCase() === 'x',
};
},
react(node, output, state) {
return (
<input
checked={node.completed}
key={state.key}
readOnly
type="checkbox"
/>
);
},
},
heading: {
match: blockRegex(HEADING_R),
order: PARSE_PRIORITY_HIGH,
parse(capture, parse, state) {
return {
content: parseInline(parse, capture[2], state),
id: options.slugify(capture[2]),
level: capture[1].length,
};
},
react(node, output, state) {
const Tag = `h${node.level}`;
return (
<Tag id={node.id} key={state.key}>
{output(node.content, state)}
</Tag>
);
},
},