-
-
Notifications
You must be signed in to change notification settings - Fork 47
/
Copy pathmarkdown-it-replace-link.mts
56 lines (52 loc) · 1.62 KB
/
markdown-it-replace-link.mts
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
import path from 'path';
import type Md from 'markdown-it';
import type Token from 'markdown-it/lib/token';
export default (md: Md, options: { baseUrl: string; root: string }): void => {
const base = options.baseUrl;
const root = path.resolve(options.root);
/** Normalize href */
function normalizeHref(curr: string, href: string) {
let absolutePath;
let hash = '';
if (/\.md(?:#.*)?$/.test(href)) {
hash = /\.md(#.*)?$/.exec(href)![1] || '';
absolutePath = path.join(path.dirname(curr), hash ? href.slice(0, -hash.length) : href);
} else {
// hash only
absolutePath = curr;
hash = href;
}
return `${base}/${path
.relative(root, absolutePath)
.replace(/README\.md$/, '')
.replace(/\.md$/, '')}/${hash}`
.replace(/\\/gu, '/')
.replace(/\/+/gu, '/');
}
md.renderer.rules.link_open = (tokens, idx, options, env, self) => {
const token = tokens[idx];
const hrefIndex = token.attrIndex('href');
if (hrefIndex >= 0) {
const link = token.attrs![hrefIndex];
const href = link[1];
if (/^https?:/.test(href)) {
const proxyToken = {
...token,
attrs: [...token.attrs!, ['target', '_blank'], ['rel', 'noopener noreferrer']]
} as Token;
return self.renderToken([proxyToken], 0, options);
} else if (/\.md(?:#.*)?$/.test(href) || /^#.*$/.test(href)) {
const proxyToken = {
...token,
attrs: [
...token.attrs!.slice(0, hrefIndex - 1),
[link[0], normalizeHref(env.id, href)],
...token.attrs!.slice(hrefIndex + 1)
]
} as Token;
return self.renderToken([proxyToken], 0, options);
}
}
return self.renderToken(tokens, idx, options);
};
};