-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
68 lines (51 loc) · 2.03 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
/**
* External Links MarkdownIt plugin
* Mark external, absolute links as necessary
*
* @param {import("markdown-it")} md
* @param {object} options
* @param {string?} options.domain domain to consider an internal link.
* @param {string?} options.class add a class (preserves existing)
*/
module.exports = (md, options={}) => {
// Finds external links
let regex = /^https?:\/\//;
if(!!options.domain) {
// Sanitize domain - remove the protocol, if existing
const domain = options.domain.replace(/^https?:\/\//, "");
regex = RegExp(`^https?:\/\/(?!${domain}|localhost)`);
}
/**
* @type {import("markdown-it/lib/parser_core").RuleCore}
*/
function link_external({ tokens }) {
// Iterate through tokens, looking for links
for(let t of tokens) {
// There are no tokens, or we got an empty one (skip)
if(!t) continue;
// It's a block, but any links will be inline (skip)
if(t.type !== 'inline') continue;
// It's inline, but there are no child tokens (skip)
if(!t.children) continue;
// There's children, but no links
if(t.children.filter(c => c.type === "link_open").length === 0) {
continue;
}
for(let c of t.children) {
// It's not a link (skip)
if(c.type !== "link_open") continue;
let href = c.attrGet("href");
// It's a link tag, but the url is missing (skip)
if(!href) continue;
// It's a link, but it's internal (skip)
if(!regex.test(href)) continue;
// We can start messing around now!
// Note: `attrJoin` preserves existing values
c.attrJoin("rel", "noopener noreferrer")
c.attrSet("target", "_blank")
if(!!options.class) c.attrJoin("class", options.class)
}
}
}
md.core.ruler.push("link_external", link_external);
};