-
Notifications
You must be signed in to change notification settings - Fork 15
/
index.js
78 lines (72 loc) · 2.39 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
function replaceAttr (token, attrName, replace, env) {
token.attrs.forEach(function (attr) {
if (attr[0] === attrName) {
attr[1] = replace(attr[1], env, token)
}
})
}
function replaceNodes (nodes, replace, env, token) {
if (!nodes) return
for (let i = 0; i < nodes.length; i++) {
const node = nodes[i]
if (node.attribs) {
if (node.name === 'img' && node.attribs.src) {
node.attribs.src = replace(node.attribs.src, env, token, node)
}
if (node.name === 'a' && node.attribs.href) {
node.attribs.href = replace(node.attribs.href, env, token, node)
}
}
replaceNodes(node.children, replace, env, token)
}
}
function replaceHTML (token, replace, env) {
const htmlparser = require('htmlparser2')
const serializer = require('dom-serializer')
const dom = new htmlparser.parseDocument(token.content, {
recognizeCDATA: true,
recognizeSelfClosing: true
})
replaceNodes(dom.children, replace, env, token)
token.content = serializer.render(dom)
}
module.exports = function (md, opts) {
md.core.ruler.after(
'inline',
'replace-link',
function (state) {
let replace
if (md.options.replaceLink && typeof md.options.replaceLink === 'function') {
// Use markdown options (default so far)
replace = md.options.replaceLink
} else if (opts && opts.replaceLink && typeof opts.replaceLink === 'function') {
// Alternatively use plugin options provided upon .use(..)
replace = opts.replaceLink
} else {
return false
}
const html = opts && opts.processHTML || false
if (typeof replace === 'function') {
state.tokens.forEach(function (blockToken) {
if (html && blockToken.type === 'html_block') {
replaceHTML(blockToken, replace, state.env)
}
if (blockToken.type === 'inline' && blockToken.children) {
blockToken.children.forEach(function (token) {
const type = token.type
if (html && type === 'html_inline') {
replaceHTML(token, replace, state.env)
}
if (type === 'link_open') {
replaceAttr(token, 'href', replace, state.env)
} else if (type === 'image') {
replaceAttr(token, 'src', replace, state.env)
}
})
}
})
}
return false
}
)
}