3
3
module . exports = toMdast
4
4
5
5
var minify = require ( 'rehype-minify-whitespace' )
6
+ var convert = require ( 'unist-util-is/convert' )
6
7
var visit = require ( 'unist-util-visit' )
7
8
var xtend = require ( 'xtend' )
8
9
var one = require ( './lib/one' )
9
10
var handlers = require ( './lib/handlers' )
10
11
12
+ var block = convert ( [ 'heading' , 'paragraph' , 'root' ] )
13
+
11
14
function toMdast ( tree , options ) {
12
15
var settings = options || { }
13
16
var byId = { }
17
+ var mdast
14
18
15
19
h . nodeById = byId
16
20
h . baseFound = false
@@ -26,11 +30,15 @@ function toMdast(tree, options) {
26
30
h . unchecked = settings . unchecked || '[ ]'
27
31
h . quotes = settings . quotes || [ '"' ]
28
32
29
- visit ( tree , onvisit )
33
+ visit ( tree , 'element' , onelement )
30
34
31
35
minify ( { newlines : settings . newlines === true } ) ( tree )
32
36
33
- return one ( h , tree , null )
37
+ mdast = one ( h , tree , null )
38
+
39
+ visit ( mdast , 'text' , ontext )
40
+
41
+ return mdast
34
42
35
43
function h ( node , type , props , children ) {
36
44
var result
@@ -65,12 +73,47 @@ function toMdast(tree, options) {
65
73
return right
66
74
}
67
75
68
- function onvisit ( node ) {
69
- var props = node . properties || { }
70
- var id = props . id
76
+ function onelement ( node ) {
77
+ var id = node . properties . id
71
78
72
- if ( id && ! ( id in node ) ) {
79
+ if ( id && ! ( id in byId ) ) {
73
80
byId [ id ] = node
74
81
}
75
82
}
83
+
84
+ // Collapse text nodes, and fix whitespace.
85
+ // Most of this is taken care of by `rehype-minify-whitespace`, but
86
+ // we’re generating some whitespace too, and some nodes are in the end
87
+ // ignored.
88
+ // So clean up:
89
+ function ontext ( node , index , parent ) {
90
+ var previous = parent . children [ index - 1 ]
91
+
92
+ if ( previous && node . type === previous . type ) {
93
+ previous . value += node . value
94
+
95
+ parent . children . splice ( index , 1 )
96
+
97
+ if ( previous . position && node . position ) {
98
+ previous . position . end = node . position . end
99
+ }
100
+
101
+ // Iterate over the previous node again, to handle its total value.
102
+ return index - 1
103
+ }
104
+
105
+ node . value = node . value . replace ( / [ \t ] * ( \r ? \n | \r ) [ \t ] * / , '$1' )
106
+
107
+ // We don’t care about other phrasing nodes in between (e.g., `[ asd ]()`),
108
+ // as there the whitespace matters.
109
+ if ( block ( parent ) ) {
110
+ if ( ! index ) {
111
+ node . value = node . value . replace ( / ^ [ \t ] + / , '' )
112
+ }
113
+
114
+ if ( index === parent . children . length - 1 ) {
115
+ node . value = node . value . replace ( / [ \t ] + $ / , '' )
116
+ }
117
+ }
118
+ }
76
119
}
0 commit comments