You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

66 lines
1.9 KiB

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