/
link.js
61 lines (48 loc) · 1.18 KB
/
link.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
'use strict';
const util = require('hexo-util');
const htmlTag = util.htmlTag;
const rUrl = /((([A-Za-z]{3,9}:(?:\/\/)?)(?:[-;:&=+$,\w]+@)?[A-Za-z0-9.-]+|(?:www.|[-;:&=+$,\w]+@)[A-Za-z0-9.-]+)((?:\/[+~%/.\w-_]*)?\??(?:[-+=&;%@.\w_]*)#?(?:[.!/\\w]*))?)/;
/**
* Link tag
*
* Syntax:
* {% link text url [external] [title] %}
*/
function linkTag(args, content) {
let url = '';
const text = [];
let external = false;
let title = '';
let item = '';
let i = 0;
const len = args.length;
// Find link URL and text
for (; i < len; i++) {
item = args[i];
if (rUrl.test(item)) {
url = item;
break;
} else {
text.push(item);
}
}
// Delete link URL and text from arguments
args = args.slice(i + 1);
// Check if the link should be open in a new window
// and collect the last text as the link title
if (args.length) {
const shift = args[0];
if (shift === 'true' || shift === 'false') {
external = shift === 'true';
args.shift();
}
title = args.join(' ');
}
const attrs = {
href: url,
title,
target: external ? '_blank' : ''
};
return htmlTag('a', attrs, text.join(' '));
}
module.exports = linkTag;