parse.cjs 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. 'use strict';
  2. const svg_defs = require('./defs.cjs');
  3. const svg_viewbox = require('./viewbox.cjs');
  4. function parseSVGContent(content) {
  5. const match = content.trim().match(
  6. /(?:<(?:\?xml|!DOCTYPE)[^>]+>\s*)*<svg([^>]+)>([\s\S]+)<\/svg[^>]*>/
  7. );
  8. if (!match) {
  9. return;
  10. }
  11. const body = match[2].trim();
  12. const attribsList = match[1].match(/[\w:-]+="[^"]*"/g);
  13. const attribs = /* @__PURE__ */ Object.create(null);
  14. attribsList?.forEach((row) => {
  15. const match2 = row.match(/([\w:-]+)="([^"]*)"/);
  16. if (match2) {
  17. attribs[match2[1]] = match2[2];
  18. }
  19. });
  20. return {
  21. attribs,
  22. body
  23. };
  24. }
  25. function build(data) {
  26. const attribs = data.attribs;
  27. const viewBox = svg_viewbox.getSVGViewBox(attribs["viewBox"] ?? "");
  28. if (!viewBox) {
  29. return;
  30. }
  31. const groupAttributes = [];
  32. for (const key in attribs) {
  33. if (key === "style" || key.startsWith("fill") || key.startsWith("stroke")) {
  34. groupAttributes.push(`${key}="${attribs[key]}"`);
  35. }
  36. }
  37. let body = data.body;
  38. if (groupAttributes.length) {
  39. body = svg_defs.wrapSVGContent(
  40. body,
  41. "<g " + groupAttributes.join(" ") + ">",
  42. "</g>"
  43. );
  44. }
  45. return {
  46. // Copy dimensions if exist
  47. width: attribs.width,
  48. height: attribs.height,
  49. viewBox,
  50. body
  51. };
  52. }
  53. function buildParsedSVG(data) {
  54. const result = build(data);
  55. if (result) {
  56. return {
  57. attributes: {
  58. // Copy dimensions if exist
  59. width: result.width,
  60. height: result.height,
  61. // Merge viewBox
  62. viewBox: result.viewBox.join(" ")
  63. },
  64. viewBox: result.viewBox,
  65. body: result.body
  66. };
  67. }
  68. }
  69. function convertParsedSVG(data) {
  70. const result = build(data);
  71. if (result) {
  72. const viewBox = result.viewBox;
  73. return {
  74. left: viewBox[0],
  75. top: viewBox[1],
  76. width: viewBox[2],
  77. height: viewBox[3],
  78. body: result.body
  79. };
  80. }
  81. }
  82. exports.buildParsedSVG = buildParsedSVG;
  83. exports.convertParsedSVG = convertParsedSVG;
  84. exports.parseSVGContent = parseSVGContent;