-
Notifications
You must be signed in to change notification settings - Fork 0
/
html-to-markdown.js
315 lines (294 loc) · 8.98 KB
/
html-to-markdown.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
'use strict'
module.exports = HTMLToMarkdown
function HTMLToMarkdown (html) {
return new Parser().parse(html)
}
function nothing () {}
class Parser {
constructor () {
this.output = []
this.lineBuffer = ''
this.tagBuffer = {}
this.accumulatingContent = true
this.tags = {
a: {
start: (tag, attrs) => {
const href = attrs.filter(attr => attr.name === 'href')
if (href.length === 0) {
this.linkDest = null
return
}
this.linkDest = href[0].value
this.addText(`[`)
},
end: () => {
if (this.linkDest) this.addText(`](${this.linkDest})`)
}
},
abbr: this.inline(),
acronym: this.inline(),
address: this.block('*', '*'),
article: this.block(),
aside: this.block(),
b: this.inline('**', '**'),
big: this.inline(),
blockquote: this.block('> ', ''),
// body: ignore
br: {
start: () => this.endLine(),
end: nothing
},
caption: this.inline(), // table related
center: this.inline(),
cite: this.inline('*', '*'),
code: this.block('`', '`'),
col: this.inline(),
colgroup: this.inline(),
dd: this.block('', ''),
del: this.inline('~~', '~~'),
dfn: this.inline(),
div: this.block(),
dl: this.block(),
dt: this.block('**', '**'),
em: this.inline('*', '*'),
figcaption: this.block(),
figure: this.block(),
footer: this.block(),
h1: this.paragraph('# ', ''), // 2em
h2: this.paragraph('## ', ''), // 1.5em
h3: this.paragraph('### ', ''), // 1.17em
h4: this.paragraph('#### ', ''),
h5: this.paragraph('##### ', ''), // 0.83em
h6: this.paragraph('######', ''), // 0.67em
// head: ignore
header: this.block(),
hgroup: this.block(),
hr: this.block('---', null, false),
i: this.inline('*', '*'),
img: {
start: (tag, attrs) => {
const src = attrs.filter(attr => attr.name === 'src')
this.addText(`[!${src[0].alt||''}](${src[0].value})`)
},
end: () => { }
},
ins: this.inline('*', '*'),
kbd: this.inline('`', '`'),
li: this.block('* ', null, false),
// link: supress
menu: this.block(),
ol: this.block(),
output: this.inline(),
p: this.paragraph(),
pre: this.block('```', '```'),
q: this.inline('“', '”'),
// ruby: ignore
// rp: ignore
// rt: ignore
s: this.inline('~~', '~~'),
samp: this.inline('`', '`'),
section: this.block(),
// small: this.inline(),
// source: supress (used w/ video)
span: this.inline(),
strike: this.inline('~~', '~~'),
strong: this.inline('**', '**'),
// style: suppress (BUT DON'T DO THIS FOREVER)
// sub: this.inline(),
// sup: this.inline(),
table: this.inline(),
// tbody: ignored
td: this.inline(),
// tfoot: ignored
th: this.inline(),
// thead: ignored
time: this.inline(),
// title: suppress
tr: this.inline(),
// u: this.inline('[u]', '[/u]'),
ul: this.block(),
var: this.inline('*', '*'),
$ignore: {
start: nothing,
end: nothing
},
$suppress: {
start: () => this.pauseText(),
end: () => this.resumeText()
}
}
this.tags.body = this.tags.$ignore
this.tags.head = this.tags.$ignore
this.tags.hgroup = this.tags.$ignore
this.tags.html = this.tags.$ignore
this.tags.link = this.tags.$suppress
this.tags.ruby = this.tags.$ignore
this.tags.rp = this.tags.$ignore
this.tags.rt = this.tags.$ignore
this.tags.script = this.tags.$suppress
this.tags.source = this.tags.$suppress
this.tags.style = this.tags.$suppress
this.tags.tbody = this.tags.$ignore
this.tags.tfoot = this.tags.$ignore
this.tags.thead = this.tags.$ignore
this.tags.time = this.tags.$ignore
this.tags.title = this.tags.$suppress
this.tags.wbr = this.tags.$ignore
this.tags.u = this.tags.$ignore
this.tags.big = this.tags.$ignore
this.tags.small = this.tags.$ignore
this.styles = {
'border': () => '',
'width': () => '',
'display': () => '',
'padding': () => '',
'padding-left': () => '',
'margin-left': () => '',
'font-size': () => '',
'font-weight': (tag, name, value) => {
if (value === 'bold' || value === 'bolder' || value >= 700) {
this.addText(`**`)
return '**'
} else {
return ''
}
},
'font-family': () => '',
'vertical-align': () => '',
'text-align': () => '',
}
}
pauseText () {
this.accumulatingContent = false
}
resumeText () {
this.accumulatingContent = true
}
addText (text) {
if (!this.accumulatingContent) return
this.lineBuffer += text
}
currentLine () {
return this.lineBuffer.replace(/\s+/g, ' ').trim()
}
endLine () {
this.output.push(this.currentLine())
this.lineBuffer = ''
}
textDecorations (which) {
return value => which == null ? this.textDecorationsMap[value] : this.textDecorationsMap[value][which]
}
handleStyle (tag, attrs) {
let foundUnknown = false
let closeWith = ''
for (let attr of attrs) {
if (attr.name === 'style') {
try {
const parseCSS = require('css-parse')
let css = parseCSS(`this { ${attr.value} }`)
for (let decl of css.stylesheet.rules[0].declarations) {
let style = this.styles[decl.property]
if (style) {
try {
closeWith = style(tag, decl.property, decl.value) + closeWith
} catch (ex) {
process.emit('error', 'style crashed', ex)
}
if (/^xenforo-/.test(decl.property)) break
} else {
const util = require('util')
process.emit('debug', `UNKNOWN CSS: ${util.inspect(decl)} ${tag} ${util.inspect(attrs)}`)
}
}
} catch (ex) {
process.emit('debug', 'INVALID CSS value=' + attr.value + ', ' + ex.stack)
}
}
}
if (!this.tagBuffer[tag]) this.tagBuffer[tag] = []
this.tagBuffer[tag].push(closeWith)
}
inline (start, end, noStyle) {
return {
start: (tag, attrs) => {
if (!noStyle) this.handleStyle(tag, attrs)
if (start) this.addText(start)
},
end: (tag) => {
if (end) this.addText(end)
if (!noStyle) {
const closeWith = this.tagBuffer[tag].pop()
if (closeWith) this.addText(closeWith)
}
}
}
}
block (start, end, noStyle) {
return {
start: (tag, attrs) => {
if (this.currentLine().length) this.endLine()
if (!noStyle) this.handleStyle(tag, attrs)
if (start) this.addText(start)
},
end: (tag, attrs) => {
if (end) this.addText(end)
if (!noStyle) {
const closeWith = this.tagBuffer[tag].pop()
if (closeWith) this.addText(closeWith)
}
if (this.currentLine().length) this.endLine()
}
}
}
paragraph (start, end, noStyle) {
return {
start: (tag, attrs) => {
// paragraphs end the current line, if any
if (this.currentLine().length) this.endLine()
// they also inject a blank line between themselves and any previous lines
if (this.output.length && this.output[this.output.length - 1].length) this.endLine()
if (!noStyle) this.handleStyle(tag, attrs)
if (start) this.addText(start)
},
end: (tag, attrs) => {
if (end) this.addText(end)
if (!noStyle) {
const closeWith = this.tagBuffer[tag].pop()
if (closeWith) this.addText(closeWith)
}
if (this.currentLine().length) {
this.endLine()
this.endLine()
} else {
this.endLine()
}
}
}
}
async parse (html$) {
const parse5 = require('parse5')
const parser = new parse5.SAXParser()
parser.on('startTag', (tag, attrs, selfClosing, location) => {
if (this.tags[tag]) {
this.tags[tag].start(tag, attrs, selfClosing, location)
} else {
const util = require('util')
process.emit('debug', 'UNKNOWN', 'tag:', tag + ', attrs:', util.inspect(attrs) + ', selfClosing:', !!selfClosing + ', location:', location, '\n')
}
})
parser.on('endTag', (tag, attrs, selfClosing, location) => {
if (this.tags[tag]) {
this.tags[tag].end(tag, attrs, selfClosing, location)
} else {
const util = require('util')
process.emit('debug', 'UNKNOWN', 'endtag:', tag + ', attrs:', util.inspect(attrs) + ', selfClosing:', !!selfClosing + ', location:', location, '\n')
}
})
parser.on('text', text => this.addText(text))
parser.end(await html$)
const fun = require('funstream')
await fun(parser)
this.endLine()
return this.output.join('\n').replace(/\n+$/, '') + '\n'
}
}