srcset.js 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  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 = () => ({
  6. postTransformNode: (node) => {
  7. transform(node);
  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) {
  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 { require: utils_1.urlToRequire(url), descriptor };
  34. });
  35. // "require(url1)"
  36. // "require(url1) 1x"
  37. // "require(url1), require(url2)"
  38. // "require(url1), require(url2) 2x"
  39. // "require(url1) 1x, require(url2)"
  40. // "require(url1) 1x, require(url2) 2x"
  41. const code = imageCandidates
  42. .map(({ require, descriptor }) => `${require} + "${descriptor ? ' ' + descriptor : ''}, " + `)
  43. .join('')
  44. .slice(0, -6)
  45. .concat('"')
  46. .replace(/ \+ ""$/, '');
  47. attr.value = code;
  48. }
  49. });
  50. }
  51. }