parse.mjs 1.9 KB

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