-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathindex.js
45 lines (39 loc) · 1001 Bytes
/
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
import path from 'path'
import {visit} from 'unist-util-visit'
import sizeOf from 'image-size'
export default setImageSize
/**
* Handles:
* "//"
* "http://"
* "https://"
* "ftp://"
*/
const absolutePathRegex = /^(?:[a-z]+:)?\/\//;
function getImageSize(src, dir) {
if (absolutePathRegex.exec(src)) {
return
}
// Treat `/` as a relative path, according to the server
const shouldJoin = !path.isAbsolute(src) || src.startsWith('/');
if (dir && shouldJoin) {
src = path.join(dir, src);
}
return sizeOf(src)
}
function setImageSize(options) {
const opts = options || {}
const dir = opts.dir
return transformer
function transformer(tree, file) {
visit(tree, 'element', visitor)
function visitor(node) {
if (node.tagName === 'img') {
const src = node.properties.src
const dimensions = getImageSize(src, dir) || {};
node.properties.width = dimensions.width
node.properties.height = dimensions.height
}
}
}
}