plantuml.js 1.4 KB

123456789101112131415161718192021222324252627282930313233343536
  1. const encoder = require('plantuml-encoder');
  2. const svgToDataUri = require('mini-svg-data-uri');
  3. const fetch = require('node-fetch');
  4. const visit = require('unist-util-visit');
  5. async function umlToSvgDataUri(uml) {
  6. const encoded = encoder.encode(uml);
  7. const response = await fetch(`https://www.plantuml.com/plantuml/svg/${encoded}`);
  8. let svg = await response.text();
  9. return svgToDataUri(svg);
  10. }
  11. module.exports = () => {
  12. return async syntaxTree => {
  13. const matches = [];
  14. visit(syntaxTree, 'code', node => {
  15. if (node.lang === 'uml' && !!node.value) {
  16. matches.push(node);
  17. }
  18. });
  19. if (!matches.length) {
  20. return;
  21. }
  22. const id = Math.random().toString().substring(2);
  23. syntaxTree.children.unshift({ type: 'import', value: `import ThemedImage${id} from '@theme/ThemedImage'` });
  24. await Promise.all(matches.map(async node => {
  25. const lightSvg = await umlToSvgDataUri(node.value.replace('@startuml', '@startuml\n!theme bluegray'));
  26. // Workaround https://github.com/bschwarz/puml-themes/issues/15
  27. const darkSvg = await umlToSvgDataUri(node.value.replace('@startuml', '@startuml\n!theme cyborg\nskinparam SequenceDelayFontColor $FGCOLOR'));
  28. node.type = 'jsx';
  29. node.value = `<ThemedImage${id} sources={{ light: "${lightSvg}", dark: "${darkSvg}" }} />`;
  30. }));
  31. }
  32. }