-
Notifications
You must be signed in to change notification settings - Fork 78
/
Copy pathsrcset.ts
73 lines (64 loc) · 2.14 KB
/
srcset.ts
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
// vue compiler module for transforming `img:srcset` to a number of `require`s
import { urlToRequire, ASTNode } from './utils'
import { TransformAssetUrlsOptions } from './assetUrl'
interface ImageCandidate {
require: string
descriptor: string
}
export default (transformAssetUrlsOptions?: TransformAssetUrlsOptions) => ({
postTransformNode: (node: ASTNode) => {
transform(node, transformAssetUrlsOptions)
}
})
// http://w3c.github.io/html/semantics-embedded-content.html#ref-for-image-candidate-string-5
const escapedSpaceCharacters = /( |\\t|\\n|\\f|\\r)+/g
function transform(
node: ASTNode,
transformAssetUrlsOptions?: TransformAssetUrlsOptions
) {
const tags = ['img', 'source']
if (tags.indexOf(node.tag) !== -1 && node.attrs) {
node.attrs.forEach(attr => {
if (attr.name === 'srcset') {
// same logic as in transform-require.js
const { value } = attr
const isStatic =
value.charAt(0) === '"' && value.charAt(value.length - 1) === '"'
if (!isStatic) {
return
}
const imageCandidates: ImageCandidate[] = value
.substr(1, value.length - 2)
.split(',')
.map(s => {
// The attribute value arrives here with all whitespace, except
// normal spaces, represented by escape sequences
const [url, descriptor] = s
.replace(escapedSpaceCharacters, ' ')
.trim()
.split(' ', 2)
return {
require: urlToRequire(url, transformAssetUrlsOptions),
descriptor
}
})
// "require(url1)"
// "require(url1) 1x"
// "require(url1), require(url2)"
// "require(url1), require(url2) 2x"
// "require(url1) 1x, require(url2)"
// "require(url1) 1x, require(url2) 2x"
const code = imageCandidates
.map(
({ require, descriptor }) =>
`${require} + "${descriptor ? ' ' + descriptor : ''}, " + `
)
.join('')
.slice(0, -6)
.concat('"')
.replace(/ \+ ""$/, '')
attr.value = code
}
})
}
}