forked from crookedneighbor/markdown-it-link-attributes
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
81 lines (64 loc) · 2.33 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
'use strict'
// Adapted from https://github.com/markdown-it/markdown-it/blob/fbc6b0fed563ba7c00557ab638fd19752f8e759d/docs/architecture.md
function findFirstMatchingConfig (link, configs) {
var i, config
var href = link.attrs[link.attrIndex('href')][1]
for (i = 0; i < configs.length; ++i) {
config = configs[i]
// If there is a matcher function defined then call it
// Matcher Function should return a bool indicating it matched (true) or not (false)
if (config.function && typeof config.function === 'function') {
if (config.function(href, config)) {
return config
} else {
return
}
}
// if no function defined, will revert to RegExp
// if there is no pattern, config matches for all links
// otherwise, only return config if href matches the pattern set
if (!config.pattern || new RegExp(config.pattern).test(href)) {
return config
}
}
}
function applyAttributes (idx, tokens, attributes) {
Object.keys(attributes).forEach(function (attr) {
var attrIndex
var value = attributes[attr]
if (attr === 'className') {
// when dealing with applying classes
// programatically, some programmers
// may prefer to use the className syntax
attr = 'class'
}
attrIndex = tokens[idx].attrIndex(attr)
if (attrIndex < 0) { // attr doesn't exist, add new attribute
tokens[idx].attrPush([attr, value])
} else { // attr already exists, overwrite it
tokens[idx].attrs[attrIndex][1] = value // replace value of existing attr
}
})
}
function markdownitLinkAttributes (md, configs) {
if (!configs) {
configs = []
} else {
configs = Array.isArray(configs) ? configs : [configs]
}
Object.freeze(configs)
var defaultRender = md.renderer.rules.link_open || this.defaultRender
md.renderer.rules.link_open = function (tokens, idx, options, env, self) {
var config = findFirstMatchingConfig(tokens[idx], configs)
var attributes = config && config.attrs
if (attributes) {
applyAttributes(idx, tokens, attributes)
}
// pass token to default renderer.
return defaultRender(tokens, idx, options, env, self)
}
}
markdownitLinkAttributes.defaultRender = function (tokens, idx, options, env, self) {
return self.renderToken(tokens, idx, options)
}
module.exports = markdownitLinkAttributes