node.js - 我如何在node.js中使用mxGraph实例

标签 node.js mxgraph

我正在尝试使用 node.js 中的 mxGraph 实例来准备带有我的自定义逻辑的 XML 导出(适用于前端,我只是将逻辑移至后端)。是否可以在nodej.js中使用mxGraph实例的完整API,我想知道像graph.getDefaultParent()等方法。

我正在尝试使用由插件 XML 生成的正确加载新实例,但下面的代码不会影响模型(没有其他错误)

 const dom = new JSDOM();

        global.window = dom.window;
        global.document = dom.window.document;
        global.navigator = {
            userAgent: '',
            appName: '',
            appVersion: '',
        };

        new JSDOM(
            `<!DOCTYPE html>
                <html>
                    <body>
                    <div id="container"></div>
                    <script type="text/javascript">
                        const graphInstance = new mxGraph(document.getElementById('container'));

                        const xmlDocument = new DOMParser().parseFromString(window.content, 'text/xml');
                        const node = xmlDocument.documentElement;
                        let decoder = new mxCodec(xmlDocument);
                        decoder.decode(node, graphInstance.getModel());

                        console.log(graphInstance.getModel()); //  looks exactly like before decode
                    </script>
                    </body>
                </html>`,
            {
                runScripts: 'dangerously',
                beforeParse(window) {
                    const { mxGraph, mxUtils, mxCodec } = require('../../static/flow-chart/js/mxClient/js/mxClient');

                    window.DOMParser = require('xmldom').DOMParser;
                    window.content = content //  mxGraph's XML, using in front-end too
                        .replace('</mxGraphModel>', '')
                        .replace('<mxGraphModel>', '');
                    window.mxGraph = mxGraph;
                    window.mxUtils = mxUtils;
                    window.mxCodec = mxCodec;
                }
            }
        );

控制台日志抛出什么:

mxCell {
  value: undefined,
  geometry: undefined,
  style: undefined,
  children: 
   [ mxCell {
       value: undefined,
       geometry: undefined,
       style: undefined,
       parent: [Circular],
       id: '1',
       mxObjectId: 'mxCell#5' } ],
  id: '0',
  mxObjectId: 'mxCell#4' }
mxGraphModel {
  currentEdit: 
   mxUndoableEdit {
     source: [Circular],
     changes: [],
     significant: true,
     notify: [Function] },
  root: 
   mxCell {
     value: undefined,
     geometry: undefined,
     style: undefined,
     children: [ [Object] ],
     id: '0',
     mxObjectId: 'mxCell#4' },
  nextId: 2,
  cells: 
   { '0': 
      mxCell {
        value: undefined,
        geometry: undefined,
        style: undefined,
        children: [Array],
        id: '0',
        mxObjectId: 'mxCell#4' },
     '1': 
      mxCell {
        value: undefined,
        geometry: undefined,
        style: undefined,
        parent: [Object],
        id: '1',
        mxObjectId: 'mxCell#5' } },
  updateLevel: 0,
  endingUpdate: false,
  eventListeners: 
   [ 'change',
     [Function],
     'change',
     [Function],
     'change',
     [Function],
     'change',
     [Function],
     'change',
     [Function],
     'change',
     [Function] ] }

最佳答案

您好,非常感谢您推荐 jsdom。 以下代码片段生成 xml 并将其嵌入到 html 中:

'use strict';
const jsdom = require("jsdom");
const { JSDOM } = jsdom;
const dom = new JSDOM();

global.window = dom.window;
global.document = window.document;
global.XMLSerializer = window.XMLSerializer
global.navigator = window.navigator;

var viewerModulePath = "mxgraph";
const mxgraph = require(viewerModulePath)({
  // These are wrong but harmless at the moment.
  mxImageBasePath: "./src/images",
  mxBasePath: "./src"
});

const {mxGraph, mxCodec, mxUtils} = mxgraph;

const helloWorldGraph = makeHelloWorld();
console.log(graphToHTML(helloWorldGraph));

function makeHelloWorld() {
  // Extracted from https://github.com/jgraph/mxgraph/blob/master/javascript/examples/helloworld.html
  const graph = new mxGraph();

  // Gets the default parent for inserting new cells. This
  // is normally the first child of the root (ie. layer 0).
  var parent = graph.getDefaultParent();

  // Adds cells to the model in a single step
  graph.getModel().beginUpdate();
  try {
    var v1 = graph.insertVertex(parent, null, 'Hello,', 20, 20, 80, 30);
    var v2 = graph.insertVertex(parent, null, 'World!', 200, 150, 80, 30);
    var e1 = graph.insertEdge(parent, null, '', v1, v2);
  } finally {
    // Updates the display
    graph.getModel().endUpdate();
  }
  return graph;
}

function graphToXML(graph) {
  var encoder = new mxCodec();
  var result = encoder.encode(graph.getModel());
  return mxUtils.getXml(result);
}

function graphToHTML(graph) {
  const xml = graphToXML(graph);
  return getHtml2(xml, "Hello World!");
}

// Extracted from https://github.com/jgraph/drawio/blob/master/src/main/webapp/js/diagramly/EditorUi.js#L1452
function getHtml2(xml, title, redirect) {

  const EditorUi = {
    drawHost: 'https://www.draw.io'
  }

  var js = EditorUi.drawHost + '/js/viewer.min.js';
  var foldingEnabled = false;

  // Makes XHTML compatible
  if (redirect != null) {
    redirect = redirect.replace(/&/g, '&amp;');
  }

  var data = {highlight: '#0000ff', nav: foldingEnabled, resize: false, xml: xml, toolbar: ''};

  var style = 'max-width:100%;border:1px solid transparent;';

  return ((redirect == null) ? '<!--[if IE]><meta http-equiv="X-UA-Compatible" content="IE=5,IE=9" ><![endif]-->\n' : '') +
    '<!DOCTYPE html>\n<html' + ((redirect != null) ? ' xmlns="http://www.w3.org/1999/xhtml">' : '>') +
    '\n<head>\n' + ((redirect == null) ? ((title != null) ? '<title>' + mxUtils.htmlEntities(title) +
      '</title>\n' : '') : '<title>Draw.io Diagram</title>\n') +
    ((redirect != null) ? '<meta http-equiv="refresh" content="0;URL=\'' + redirect + '\'"/>\n' : '') +
    '<meta charset="utf-8"/>\n</head>\n<body>' +
    '\n<div class="mxgraph" style="' + style + '" data-mxgraph="' + mxUtils.htmlEntities(JSON.stringify(data)) + '"></div>\n' +
    ((redirect == null) ? '<script type="text/javascript" src="' + js + '"></script>' :
    '<a style="position:absolute;top:50%;left:50%;margin-top:-128px;margin-left:-64px;" ' +
    'href="' + redirect + '" target="_blank"><img border="0" ' +
    'src="' + EditorUi.drawHost + '/images/drawlogo128.png"/></a>') +
    '\n</body>\n</html>\n';
}

将其保存在 html 文件中,例如:

npm install mxgraph jdom
node helloworld.js > helloworld.html

布局算法也运行良好。

我曾尝试从图表中提取更多代码来支持 SVG Canvas ,但感觉很复杂且难以维护。 Jsdom 确实支持canvas,因此从技术上讲,应该可以单独从nodejs 生成SVG。

希望这会有所帮助!

关于node.js - 我如何在node.js中使用mxGraph实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55711473/

相关文章:

c# - FileReader 不是用 Angular 服务器端渲染定义的

javascript - NodeJS爬虫未定义不是函数

node.js - 使用 NodeJS 和 Angular6 在 MongoDB 的背景 URL 中显示图像

user-interface - 我可以使用 HP 的 Quick Test Professional 测试 mxGraph ui 吗?

javascript - mxgraph:我想添加一个按钮来禁用/启用图表和工具栏

javascript - 如何从 javascript 为 DynamoDB 中的预配置读取容量启用自动缩放

node.js - Sequelize 查询给出 TypeError : undefined is not a function

java - 如何设置在 mxGraph 的 pdf/图像导出功能中使用的自定义字体以支持 UTF-8 编码的亚洲语言文本?

javascript - 如何在 mxGraph 中渲染折线元素?

javascript - 无法从提供的 XML 创建 MxGraph