-
-
Notifications
You must be signed in to change notification settings - Fork 177
/
index.tsx
2451 lines (2157 loc) · 65.8 KB
/
index.tsx
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 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 * as React from 'react'
/**
* Analogous to `node.type`. Please note that the values here may change at any time,
* so do not hard code against the value directly.
*/
export const RuleType = {
blockQuote: '0',
breakLine: '1',
breakThematic: '2',
codeBlock: '3',
codeFenced: '4',
codeInline: '5',
footnote: '6',
footnoteReference: '7',
gfmTask: '8',
heading: '9',
headingSetext: '10',
/** only available if not `disableHTMLParsing` */
htmlBlock: '11',
htmlComment: '12',
/** only available if not `disableHTMLParsing` */
htmlSelfClosing: '13',
image: '14',
link: '15',
/** emits a `link` 'node', does not render directly */
linkAngleBraceStyleDetector: '16',
/** emits a `link` 'node', does not render directly */
linkBareUrlDetector: '17',
/** emits a `link` 'node', does not render directly */
linkMailtoDetector: '18',
newlineCoalescer: '19',
orderedList: '20',
paragraph: '21',
ref: '22',
refImage: '23',
refLink: '24',
table: '25',
tableSeparator: '26',
text: '27',
textBolded: '28',
textEmphasized: '29',
textEscaped: '30',
textMarked: '31',
textStrikethroughed: '32',
unorderedList: '33',
} as const
export type RuleType = (typeof RuleType)[keyof typeof RuleType]
const enum Priority {
/**
* anything that must scan the tree before everything else
*/
MAX,
/**
* scans for block-level constructs
*/
HIGH,
/**
* inline w/ more priority than other inline
*/
MED,
/**
* inline elements
*/
LOW,
/**
* bare text and stuff that is considered leftovers
*/
MIN,
}
/** TODO: Drop for React 16? */
const ATTRIBUTE_TO_JSX_PROP_MAP = [
'allowFullScreen',
'allowTransparency',
'autoComplete',
'autoFocus',
'autoPlay',
'cellPadding',
'cellSpacing',
'charSet',
'classId',
'colSpan',
'contentEditable',
'contextMenu',
'crossOrigin',
'encType',
'formAction',
'formEncType',
'formMethod',
'formNoValidate',
'formTarget',
'frameBorder',
'hrefLang',
'inputMode',
'keyParams',
'keyType',
'marginHeight',
'marginWidth',
'maxLength',
'mediaGroup',
'minLength',
'noValidate',
'radioGroup',
'readOnly',
'rowSpan',
'spellCheck',
'srcDoc',
'srcLang',
'srcSet',
'tabIndex',
'useMap',
].reduce(
(obj, x) => {
obj[x.toLowerCase()] = x
return obj
},
{ class: 'className', for: 'htmlFor' }
)
const namedCodesToUnicode = {
amp: '\u0026',
apos: '\u0027',
gt: '\u003e',
lt: '\u003c',
nbsp: '\u00a0',
quot: '\u201c',
} as const
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 = /^(\s*>[\s\S]*?)(?=\n\n|$)/
const BLOCKQUOTE_TRIM_LEFT_MULTILINE_R = /^ *> ?/gm
const BLOCKQUOTE_ALERT_R = /^(?:\[!([^\]]*)\]\n)?([\s\S]*)/
const BREAK_LINE_R = /^ {2,}\n/
const BREAK_THEMATIC_R = /^(?:( *[-*_])){3,} *(?:\n *)+\n/
const CODE_BLOCK_FENCED_R =
/^(?: {1,3})?(`{3,}|~{3,}) *(\S+)? *([^\n]*?)?\n([\s\S]*?)(?:\1\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
/**
* Matches footnotes on the format:
*
* [^key]: value
*
* Matches multiline footnotes
*
* [^key]: row
* row
* row
*
* And empty lines in indented multiline footnotes
*
* [^key]: indented with
* row
*
* row
*
* Explanation:
*
* 1. Look for the starting tag, eg: [^key]
* ^\[\^([^\]]+)]
*
* 2. The first line starts with a colon, and continues for the rest of the line
* :(.*)
*
* 3. Parse as many additional lines as possible. Matches new non-empty lines that doesn't begin with a new footnote definition.
* (\n(?!\[\^).+)
*
* 4. ...or allows for repeated newlines if the next line begins with at least four whitespaces.
* (\n+ {4,}.*)
*/
const FOOTNOTE_R = /^\[\^([^\]]+)](:(.*)((\n+ {4,}.*)|(\n(?!\[\^).+))*)/
const FOOTNOTE_REFERENCE_R = /^\[\^([^\]]+)]/
const FORMFEED_R = /\f/g
const FRONT_MATTER_R = /^---[ \t]*\n(.|\n)*\n---[ \t]*\n/
const GFM_TASK_R = /^\s*?\[(x|\s)\]/
const HEADING_R = /^ *(#{1,6}) *([^\n]+?)(?: +#*)?(?:\n *)*(?:\n|$)/
const HEADING_ATX_COMPLIANT_R =
/^ *(#{1,6}) +([^\n]+?)(?: +#*)?(?:\n *)*(?:\n|$)/
const HEADING_SETEXT_R = /^([^\n]+)\n *(=|-){3,} *(?:\n *)+\n/
/**
* Explanation:
*
* 1. Look for a starting tag, preceded 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)
* ?([^>]*)>
*
* 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][^ >/]*) ?((?:[^>]*[^/])?)>\n?(\s*(?:<\1[^>]*?>[\s\S]*?<\/\1>|(?!<\1\b)[\s\S])*?)<\/\1>(?!<\/\1>)\n*/i
const HTML_CHAR_CODE_R = /&([a-z0-9]+|#[0-9]{1,6}|#x[0-9a-fA-F]{1,6});/gi
const HTML_COMMENT_R = /^<!--[\s\S]*?(?:-->)/
/**
* 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 CAPTURE_LETTER_AFTER_HYPHEN = /-([a-z])?/gi
const NP_TABLE_R = /^(\|.*)\n(?: *(\|? *[-:]+ *\|[-| :]*)\n((?:.*\|.*\n)*))?\n?/
const PARAGRAPH_R = /^[^\n]+(?: \n|\n{2,})/
const REFERENCE_IMAGE_OR_LINK = /^\[([^\]]*)\]:\s+<?([^\s>]+)>?\s*("([^"]*)")?/
const REFERENCE_IMAGE_R = /^!\[([^\]]*)\] ?\[([^\]]*)\]/
const REFERENCE_LINK_R = /^\[([^\]]*)\] ?\[([^\]]*)\]/
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 = /^ *-+: *$/
/**
* For inline formatting, this partial attempts to ignore characters that
* may appear in nested formatting that could prematurely trigger detection
* and therefore miss content that should have been included.
*/
const INLINE_SKIP_R =
'((?:\\[.*?\\][([].*?[)\\]]|<.*?>(?:.*?<.*?>)?|`.*?`|~~.*?~~|==.*?==|.|\\n)*?)'
/**
* Detect a sequence like **foo** or __foo__. Note that bold has a higher priority
* than emphasized to support nesting of both since they share a delimiter.
*/
const TEXT_BOLD_R = new RegExp(`^([*_])\\1${INLINE_SKIP_R}\\1\\1(?!\\1)`)
/**
* Detect a sequence like *foo* or _foo_.
*/
const TEXT_EMPHASIZED_R = new RegExp(`^([*_])${INLINE_SKIP_R}\\1(?!\\1|\\w)`)
/**
* Detect a sequence like ==foo==.
*/
const TEXT_MARKED_R = new RegExp(`^==${INLINE_SKIP_R}==`)
/**
* Detect a sequence like ~~foo~~.
*/
const TEXT_STRIKETHROUGHED_R = new RegExp(`^~~${INLINE_SKIP_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_STARTING_NEWLINES = /^\n+/
const HTML_LEFT_TRIM_AMOUNT_R = /^([ \t]*)/
const UNESCAPE_URL_R = /\\([^\\])/g
type LIST_TYPE = 1 | 2
const ORDERED: LIST_TYPE = 1
const UNORDERED: LIST_TYPE = 2
const LIST_ITEM_END_R = / *\n+$/
const LIST_LOOKBEHIND_R = /(?:^|\n)( *)$/
// recognize a `*` `-`, `+`, `1.`, `2.`... list bullet
const ORDERED_LIST_BULLET = '(?:\\d+\\.)'
const UNORDERED_LIST_BULLET = '(?:[*+-])'
function generateListItemPrefix(type: LIST_TYPE) {
return (
'( *)(' +
(type === ORDERED ? ORDERED_LIST_BULLET : UNORDERED_LIST_BULLET) +
') +'
)
}
// recognize the start of a list item:
// leading space plus a bullet plus a space (` * `)
const ORDERED_LIST_ITEM_PREFIX = generateListItemPrefix(ORDERED)
const UNORDERED_LIST_ITEM_PREFIX = generateListItemPrefix(UNORDERED)
function generateListItemPrefixRegex(type: LIST_TYPE) {
return new RegExp(
'^' +
(type === ORDERED ? ORDERED_LIST_ITEM_PREFIX : UNORDERED_LIST_ITEM_PREFIX)
)
}
const ORDERED_LIST_ITEM_PREFIX_R = generateListItemPrefixRegex(ORDERED)
const UNORDERED_LIST_ITEM_PREFIX_R = generateListItemPrefixRegex(UNORDERED)
function generateListItemRegex(type: LIST_TYPE) {
// 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
return new RegExp(
'^' +
(type === ORDERED
? ORDERED_LIST_ITEM_PREFIX
: UNORDERED_LIST_ITEM_PREFIX) +
'[^\\n]*(?:\\n' +
'(?!\\1' +
(type === ORDERED ? ORDERED_LIST_BULLET : UNORDERED_LIST_BULLET) +
' )[^\\n]*)*(\\n|$)',
'gm'
)
}
const ORDERED_LIST_ITEM_R = generateListItemRegex(ORDERED)
const UNORDERED_LIST_ITEM_R = generateListItemRegex(UNORDERED)
// check whether a list item has paragraphs: if it does,
// we leave the newlines at the end
function generateListRegex(type: LIST_TYPE) {
const bullet = type === ORDERED ? ORDERED_LIST_BULLET : UNORDERED_LIST_BULLET
return new RegExp(
'^( *)(' +
bullet +
') ' +
'[\\s\\S]+?(?:\\n{2,}(?! )' +
'(?!\\1' +
bullet +
' (?!' +
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 ORDERED_LIST_R = generateListRegex(ORDERED)
const UNORDERED_LIST_R = generateListRegex(UNORDERED)
function generateListRule(
h: any,
type: LIST_TYPE
): MarkdownToJSX.Rule<
MarkdownToJSX.OrderedListNode | MarkdownToJSX.UnorderedListNode
> {
const ordered = type === ORDERED
const LIST_R = ordered ? ORDERED_LIST_R : UNORDERED_LIST_R
const LIST_ITEM_R = ordered ? ORDERED_LIST_ITEM_R : UNORDERED_LIST_ITEM_R
const LIST_ITEM_PREFIX_R = ordered
? ORDERED_LIST_ITEM_PREFIX_R
: UNORDERED_LIST_ITEM_PREFIX_R
return {
match(source, state) {
// We only want to break into a list if we are at the start of a
// line. This is to avoid parsing "hi * there" with "* there"
// becoming a part of a list.
// You might wonder, "but that's inline, so of course it wouldn't
// start a list?". You would be correct! Except that some of our
// lists can be inline, because they might be inside another list,
// in which case we can parse with inline scope, but need to allow
// nested lists inside this inline scope.
const isStartOfLine = LIST_LOOKBEHIND_R.exec(state.prevCapture)
const isListBlock = state.list || (!state.inline && !state.simple)
if (isStartOfLine && isListBlock) {
source = isStartOfLine[1] + source
return LIST_R.exec(source)
} else {
return null
}
},
order: Priority.HIGH,
parse(capture, parse, state) {
const bullet = capture[2]
const start = ordered ? +bullet : undefined
const items = capture[0]
// recognize the end of a paragraph block inside a list item:
// two or more newlines at end end of the item
.replace(BLOCK_END_R, '\n')
.match(LIST_ITEM_R)
let lastItemWasAParagraph = false
const itemContent = items.map(function (item, i) {
// We need to see how far indented the item is:
const space = LIST_ITEM_PREFIX_R.exec(item)[0].length
// And then we construct a regex to "unindent" the subsequent
// lines of the items by that amount:
const spaceRegex = new RegExp('^ {1,' + space + '}', 'gm')
// Before processing the item, we need a couple things
const content = item
// remove indents on trailing lines:
.replace(spaceRegex, '')
// remove the bullet:
.replace(LIST_ITEM_PREFIX_R, '')
// Handling "loose" lists, like:
//
// * this is wrapped in a paragraph
//
// * as is this
//
// * as is this
const isLastItem = i === items.length - 1
const containsBlocks = content.indexOf('\n\n') !== -1
// Any element in a list is a block if it contains multiple
// newlines. The last element in the list can also be a block
// if the previous item in the list was a block (this is
// because non-last items in the list can end with \n\n, but
// the last item can't, so we just "inherit" this property
// from our previous element).
const thisItemIsAParagraph =
containsBlocks || (isLastItem && lastItemWasAParagraph)
lastItemWasAParagraph = thisItemIsAParagraph
// backup our state for restoration afterwards. We're going to
// want to set state.list to true, and state.inline depending
// on our list's looseness.
const oldStateInline = state.inline
const oldStateList = state.list
state.list = true
// Parse inline if we're in a tight list, or block if we're in
// a loose list.
let adjustedContent
if (thisItemIsAParagraph) {
state.inline = false
adjustedContent = content.replace(LIST_ITEM_END_R, '\n\n')
} else {
state.inline = true
adjustedContent = content.replace(LIST_ITEM_END_R, '')
}
const result = parse(adjustedContent, state)
// Restore our state before returning
state.inline = oldStateInline
state.list = oldStateList
return result
})
return {
items: itemContent,
ordered: ordered,
start: start,
}
},
render(node, output, state) {
const Tag = node.ordered ? 'ol' : 'ul'
return (
<Tag
key={state.key}
start={node.type === RuleType.orderedList ? node.start : undefined}
>
{node.items.map(function generateListItem(item, i) {
return <li key={i}>{output(item, state)}</li>
})}
</Tag>
)
},
}
}
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 = /^!\[(.*?)\]\( *((?:\([^)]*\)|[^() ])*) *"?([^)"]*)?"?\)/
const NON_PARAGRAPH_BLOCK_SYNTAXES = [
BLOCKQUOTE_R,
CODE_BLOCK_FENCED_R,
CODE_BLOCK_R,
HEADING_R,
HEADING_SETEXT_R,
HEADING_ATX_COMPLIANT_R,
HTML_COMMENT_R,
NP_TABLE_R,
ORDERED_LIST_ITEM_R,
ORDERED_LIST_R,
UNORDERED_LIST_ITEM_R,
UNORDERED_LIST_R,
]
const BLOCK_SYNTAXES = [
...NON_PARAGRAPH_BLOCK_SYNTAXES,
PARAGRAPH_R,
HTML_BLOCK_ELEMENT_R,
HTML_SELF_CLOSING_ELEMENT_R,
]
function containsBlockSyntax(input: string) {
return BLOCK_SYNTAXES.some(r => r.test(input))
}
/** Remove symmetrical leading and trailing quotes */
function unquote(str: string) {
const first = str[0]
if (
(first === '"' || first === "'") &&
str.length >= 2 &&
str[str.length - 1] === first
) {
return str.slice(1, -1)
}
return str
}
// based on https://stackoverflow.com/a/18123682/1141611
// not complete, but probably good enough
export function slugify(str: string) {
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: string) {
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 parseTableRow(
source: string,
parse: MarkdownToJSX.NestedParser,
state: MarkdownToJSX.State,
tableOutput: boolean
): MarkdownToJSX.ParserResult[][] {
const prevInTable = state.inTable
state.inTable = true
let tableRow = source
.trim()
// isolate situations where a pipe should be ignored (inline code, escaped, etc)
.split(/( *(?:`[^`]*`|\\\||\|) *)/)
.reduce((nodes, fragment) => {
if (fragment.trim() === '|')
nodes.push(
tableOutput
? { type: RuleType.tableSeparator }
: { type: RuleType.text, text: fragment }
)
else if (fragment !== '') nodes.push.apply(nodes, parse(fragment, state))
return nodes
}, [] as MarkdownToJSX.ParserResult[])
state.inTable = prevInTable
let cells = [[]]
tableRow.forEach(function (node, i) {
if (node.type === RuleType.tableSeparator) {
// Filter out empty table separators at the start/end:
if (i !== 0 && i !== tableRow.length - 1) {
// Split the current row:
cells.push([])
}
} else {
if (
node.type === RuleType.text &&
(tableRow[i + 1] == null ||
tableRow[i + 1].type === RuleType.tableSeparator)
) {
node.text = node.text.trimEnd()
}
cells[cells.length - 1].push(node)
}
})
return cells
}
function parseTableAlign(source: string /*, parse, state*/) {
const alignText = source.replace(TABLE_TRIM_PIPES, '').split('|')
return alignText.map(parseTableAlignCapture)
}
function parseTableCells(
source: string,
parse: MarkdownToJSX.NestedParser,
state: MarkdownToJSX.State
) {
const rowsText = source.trim().split('\n')
return rowsText.map(function (rowText) {
return parseTableRow(rowText, parse, state, true)
})
}
function parseTable(
capture: RegExpMatchArray,
parse: MarkdownToJSX.NestedParser,
state: MarkdownToJSX.State
) {
/**
* The table syntax makes some other parsing angry so as a bit of a hack even if alignment and/or cell rows are missing,
* we'll still run a detected first row through the parser and then just emit a paragraph.
*/
state.inline = true
const align = capture[2] ? parseTableAlign(capture[2]) : []
const cells = capture[3] ? parseTableCells(capture[3], parse, state) : []
const header = parseTableRow(capture[1], parse, state, !!cells.length)
state.inline = false
return cells.length
? {
align: align,
cells: cells,
header: header,
type: RuleType.table,
}
: {
children: header,
type: RuleType.paragraph,
}
}
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(
tag: MarkdownToJSX.HTMLTags,
key: keyof React.AllHTMLAttributes<Element>,
value: string,
sanitizeUrlFn: MarkdownToJSX.Options['sanitizer']
): any {
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
.trim()
.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 (key === 'href' || key === 'src') {
return sanitizeUrlFn(value, tag, key)
} 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: string): string {
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: MarkdownToJSX.Rules
): (
source: string,
state: MarkdownToJSX.State
) => ReturnType<MarkdownToJSX.NestedParser> {
// Sorts rules in order of increasing order, then
// ascending rule name in case of ties.
let ruleList = Object.keys(rules)
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
// Sort based on increasing order
if (orderA !== orderB) {
return orderA - orderB
} else if (typeA < typeB) {
return -1
}
return 1
})
function nestedParse(
source: string,
state: MarkdownToJSX.State
): MarkdownToJSX.ParserResult[] {
let result = []
state.prevCapture = state.prevCapture || ''
// 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).
while (source) {
let i = 0
while (i < ruleList.length) {
const ruleType = ruleList[i]
const rule = rules[ruleType]
const capture = rule.match(source, state)
if (capture) {
const currCaptureString = capture[0]
// retain what's been processed so far for lookbacks
state.prevCapture += currCaptureString
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 as unknown as RuleType
}
result.push(parsed)
break
}
i++
}
}
// reset on exit
state.prevCapture = ''
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: RegExp) {
return function match(source, state: MarkdownToJSX.State) {
if (state.inline) {
return regex.exec(source)
} else {
return null
}
}
}
// basically any inline element except links
function simpleInlineRegex(regex: RegExp) {
return function match(source: string, state: MarkdownToJSX.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: RegExp) {
return function match(source: string, state: MarkdownToJSX.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: RegExp) {
return function match(source: string /*, state*/) {
return regex.exec(source)
}
}
function matchParagraph(source: string, state: MarkdownToJSX.State) {
if (state.inline || state.simple) {
return null
}
let match = ''
source.split('\n').every(line => {
// bail out on first sign of non-paragraph block
if (NON_PARAGRAPH_BLOCK_SYNTAXES.some(regex => regex.test(line))) {
return false
}
match += line + '\n'
return line.trim()
})
const captured = match.trimEnd()
if (captured == '') {
return null
}
return [match, captured]
}
export function sanitizer(url: string): string {
try {
const decoded = decodeURIComponent(url).replace(/[^A-Za-z0-9/:]/g, '')
if (decoded.match(/^\s*(javascript|vbscript|data(?!:image)):/i)) {
if (process.env.NODE_ENV !== 'production') {
console.warn(
'Anchor URL contains an unsafe JavaScript/VBScript/data 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: string): string {
return rawUrlString.replace(UNESCAPE_URL_R, '$1')
}
/**
* Everything inline, including links.
*/
function parseInline(
parse: MarkdownToJSX.NestedParser,
children: string,
state: MarkdownToJSX.State
): MarkdownToJSX.ParserResult[] {
const isCurrentlyInline = state.inline || false
const isCurrentlySimple = state.simple || false
state.inline = true
state.simple = true
const result = parse(children, state)