-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathindex.js
88 lines (67 loc) · 1.99 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
'use strict'
function markdownitLinkifyImages (md, config) {
md.renderer.rules.image = function (tokens, idx, options, env, self) {
config = config || {}
const token = tokens[idx]
const srcIndex = token.attrIndex('src')
const url = token.attrs[srcIndex][1]
const caption = md.utils.escapeHtml(token.content)
const target = generateTargetAttribute(config.target)
const linkClass = generateClass(config.linkClass)
const imgClass = generateClass(config.imgClass)
const otherAttributes = generateAttributes(md, token)
const imgAttributes = concatenateAttributes(
`src="${url}"`,
`alt="${caption}"`,
imgClass,
...otherAttributes
)
const imgElement = `<img ${imgAttributes}>`
if (alreadyWrappedInLink(tokens, idx)) {
return imgElement
}
const linkAttributes = concatenateAttributes(
`href="${url}"`,
linkClass,
target
)
return `<a ${linkAttributes}>${imgElement}</a>`
}
}
function concatenateAttributes (...attributes) {
return attributes.filter((val) => val).join(' ')
}
function generateAttributes (md, token) {
const ignore = ['src', 'alt']
const escape = ['title']
return token.attrs.map((entry) => {
const name = entry[0]
if (ignore.includes(name)) return ''
let value = ''
if (escape.includes(name)) {
value = md.utils.escapeHtml(entry[1])
} else {
value = entry[1]
}
return `${name}="${value}"`
})
}
function generateTargetAttribute (target) {
target = target || '_self'
return `target="${target}"`
}
function generateClass (className) {
if (!className) return ''
return `class="${className}"`
}
function alreadyWrappedInLink (tokens, currentTokenIndex) {
const previousToken = tokens[currentTokenIndex - 1]
const nextToken = tokens[currentTokenIndex + 1]
return (
previousToken &&
previousToken.type === 'link_open' &&
nextToken &&
nextToken.type === 'link_close'
)
}
module.exports = markdownitLinkifyImages