e561175dfbe56623489a76efc458d560e0f6f84d9fcd469156f47c6985167a4a37ea7031c33b3741371f38d199d6bde346c88e018fd78638b5302aaf14e327 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. 'use strict';
  2. var svgReg = /<svg[^>]+[^>]*>/;
  3. function isSVG (buffer) {
  4. return svgReg.test(buffer);
  5. }
  6. var extractorRegExps = {
  7. 'root': /<svg\s[^>]+>/,
  8. 'width': /\bwidth=(['"])([^%]+?)\1/,
  9. 'height': /\bheight=(['"])([^%]+?)\1/,
  10. 'viewbox': /\bviewBox=(['"])(.+?)\1/
  11. };
  12. function parseViewbox (viewbox) {
  13. var bounds = viewbox.split(' ');
  14. return {
  15. 'width': parseInt(bounds[2], 10),
  16. 'height': parseInt(bounds[3], 10)
  17. };
  18. }
  19. function parseAttributes (root) {
  20. var width = root.match(extractorRegExps.width);
  21. var height = root.match(extractorRegExps.height);
  22. var viewbox = root.match(extractorRegExps.viewbox);
  23. return {
  24. 'width': width && parseInt(width[2], 10),
  25. 'height': height && parseInt(height[2], 10),
  26. 'viewbox': viewbox && parseViewbox(viewbox[2])
  27. };
  28. }
  29. function calculateByDimensions (attrs) {
  30. return {
  31. 'width': attrs.width,
  32. 'height': attrs.height
  33. };
  34. }
  35. function calculateByViewbox (attrs) {
  36. var ratio = attrs.viewbox.width / attrs.viewbox.height;
  37. if (attrs.width) {
  38. return {
  39. 'width': attrs.width,
  40. 'height': Math.floor(attrs.width / ratio)
  41. };
  42. }
  43. if (attrs.height) {
  44. return {
  45. 'width': Math.floor(attrs.height * ratio),
  46. 'height': attrs.height
  47. };
  48. }
  49. return {
  50. 'width': attrs.viewbox.width,
  51. 'height': attrs.viewbox.height
  52. };
  53. }
  54. function calculate (buffer) {
  55. var root = buffer.toString('utf8').match(extractorRegExps.root);
  56. if (root) {
  57. var attrs = parseAttributes(root[0]);
  58. if (attrs.width && attrs.height) {
  59. return calculateByDimensions(attrs);
  60. }
  61. if (attrs.viewbox) {
  62. return calculateByViewbox(attrs);
  63. }
  64. }
  65. throw new TypeError('invalid svg');
  66. }
  67. module.exports = {
  68. 'detect': isSVG,
  69. 'calculate': calculate
  70. };