-
-
Notifications
You must be signed in to change notification settings - Fork 4.9k
/
Copy pathimg.js
79 lines (63 loc) · 1.66 KB
/
img.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
'use strict';
const url = require('url');
const { htmlTag } = require('hexo-util');
const rUrl = /((([A-Za-z]{3,9}:(?:\/\/)?)(?:[-;:&=+$,\w]+@)?[A-Za-z0-9.-]+|(?:www.|[-;:&=+$,\w]+@)[A-Za-z0-9.-]+)((?:\/[+~%/.\w-_]*)?\??(?:[-+=&;%@.\w_]*)#?(?:[.!/\\w]*))?)/;
const rMeta = /["']?([^"']+)?["']?\s*["']?([^"']+)?["']?/;
/**
* Image tag
*
* Syntax:
* {% img [class names] /path/to/image [width] [height] [title text [alt text]] %}
*/
module.exports = ctx => {
const { config } = ctx;
function makeUrl(path) {
if (path[0] === '#' || path.startsWith('//')) {
return path;
}
const data = url.parse(path);
if (data && data.protocol) {
return path;
}
path = config.root + path;
return path.replace(/\/{2,}/g, '/');
}
return function imgTag(args, content) {
const classes = [];
let src, width, height, title, alt;
// Find image URL and class name
while (args.length > 0) {
const item = args.shift();
if (rUrl.test(item) || item[0] === '/') {
src = makeUrl(item);
break;
} else {
classes.push(item);
}
}
// Find image width and height
if (args && args.length) {
if (!/\D+/.test(args[0])) {
width = args.shift();
if (args.length && !/\D+/.test(args[0])) {
height = args.shift();
}
}
const match = rMeta.exec(args.join(' '));
// Find image title and alt
if (match != null) {
title = match[1];
alt = match[2];
}
}
const attrs = {
src,
class: classes.join(' '),
width,
height,
title,
alt
};
return htmlTag('img', attrs);
};
};