srcset.ts 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. // vue compiler module for transforming `img:srcset` to a number of `require`s
  2. import { urlToRequire, ASTNode } from './utils'
  3. import { TransformAssetUrlsOptions } from './assetUrl'
  4. interface ImageCandidate {
  5. require: string
  6. descriptor: string
  7. }
  8. export default (transformAssetUrlsOptions?: TransformAssetUrlsOptions) => ({
  9. postTransformNode: (node: ASTNode) => {
  10. transform(node, transformAssetUrlsOptions)
  11. }
  12. })
  13. // http://w3c.github.io/html/semantics-embedded-content.html#ref-for-image-candidate-string-5
  14. const escapedSpaceCharacters = /( |\\t|\\n|\\f|\\r)+/g
  15. function transform(
  16. node: ASTNode,
  17. transformAssetUrlsOptions?: TransformAssetUrlsOptions
  18. ) {
  19. const tags = ['img', 'source']
  20. if (tags.indexOf(node.tag) !== -1 && node.attrs) {
  21. node.attrs.forEach(attr => {
  22. if (attr.name === 'srcset') {
  23. // same logic as in transform-require.js
  24. const value = attr.value
  25. const isStatic =
  26. value.charAt(0) === '"' && value.charAt(value.length - 1) === '"'
  27. if (!isStatic) {
  28. return
  29. }
  30. const imageCandidates: ImageCandidate[] = value
  31. .substr(1, value.length - 2)
  32. .split(',')
  33. .map(s => {
  34. // The attribute value arrives here with all whitespace, except
  35. // normal spaces, represented by escape sequences
  36. const [url, descriptor] = s
  37. .replace(escapedSpaceCharacters, ' ')
  38. .trim()
  39. .split(' ', 2)
  40. return {
  41. require: urlToRequire(url, transformAssetUrlsOptions),
  42. descriptor
  43. }
  44. })
  45. // "require(url1)"
  46. // "require(url1) 1x"
  47. // "require(url1), require(url2)"
  48. // "require(url1), require(url2) 2x"
  49. // "require(url1) 1x, require(url2)"
  50. // "require(url1) 1x, require(url2) 2x"
  51. const code = imageCandidates
  52. .map(
  53. ({ require, descriptor }) =>
  54. `${require} + "${descriptor ? ' ' + descriptor : ''}, " + `
  55. )
  56. .join('')
  57. .slice(0, -6)
  58. .concat('"')
  59. .replace(/ \+ ""$/, '')
  60. attr.value = code
  61. }
  62. })
  63. }
  64. }