2
2
// 1. adding target="_blank" to external links
3
3
// 2. converting internal links to <router-link>
4
4
5
+ const url = require ( 'url' )
6
+
5
7
const indexRE = / ( ^ | .* \/ ) ( i n d e x | r e a d m e ) .m d ( # ? .* ) $ / i
6
8
7
9
module . exports = ( md , externalAttrs ) => {
8
10
let hasOpenRouterLink = false
9
11
let hasOpenExternalLink = false
10
12
11
13
md . renderer . rules . link_open = ( tokens , idx , options , env , self ) => {
14
+ const { relPath } = env
12
15
const token = tokens [ idx ]
13
16
const hrefIndex = token . attrIndex ( 'href' )
14
17
if ( hrefIndex >= 0 ) {
@@ -25,20 +28,27 @@ module.exports = (md, externalAttrs) => {
25
28
}
26
29
} else if ( isSourceLink ) {
27
30
hasOpenRouterLink = true
28
- tokens [ idx ] = toRouterLink ( token , link )
31
+ tokens [ idx ] = toRouterLink ( token , link , relPath )
29
32
}
30
33
}
31
34
return self . renderToken ( tokens , idx , options )
32
35
}
33
36
34
- function toRouterLink ( token , link ) {
37
+ function toRouterLink ( token , link , relPath ) {
35
38
link [ 0 ] = 'to'
36
39
let to = link [ 1 ]
37
40
38
41
// convert link to filename and export it for existence check
39
42
const links = md . $data . links || ( md . $data . links = [ ] )
40
43
links . push ( to )
41
44
45
+ // relative path usage.
46
+ if ( ! to . startsWith ( '/' ) ) {
47
+ to = relPath
48
+ ? url . resolve ( '/' + relPath , to )
49
+ : ensureBeginningDotSlash ( to )
50
+ }
51
+
42
52
const indexMatch = to . match ( indexRE )
43
53
if ( indexMatch ) {
44
54
const [ , path , , hash ] = indexMatch
@@ -49,11 +59,6 @@ module.exports = (md, externalAttrs) => {
49
59
. replace ( / \. m d ( # .* ) $ / , '.html$1' )
50
60
}
51
61
52
- // relative path usage.
53
- if ( ! to . startsWith ( '/' ) ) {
54
- to = ensureBeginningDotSlash ( to )
55
- }
56
-
57
62
// markdown-it encodes the uri
58
63
link [ 1 ] = decodeURI ( to )
59
64
0 commit comments