srcset.js 2.3 KB

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