No display when loading diagram.xml in mxgraph and react

I am carrying out a project with mxgraph and react in which I want to implement a function that allows loading a diagram saved in an xml file, but when loading the diagram the diagram is not displayed and when I inspect the page it does not show me errors. This is the complete code:

import React, { useRef, useEffect } from 'react';
import { mxGraph, mxRubberband, mxClient, mxUtils, mxCodec } from 'mxgraph-js';
import './DiagramEditor.css'; // Asegúrate de tener este archivo CSS en tu proyecto

const DiagramModifier = () => {
    const graphContainer = useRef(null);
    const graph = useRef(null);

    useEffect(() => {
        if (!mxClient.isBrowserSupported()) {
            mxUtils.alert('Browser is not supported!');
            return;
        }

        // Initialize the graph within the container
        graph.current = new mxGraph(graphContainer.current);
        graph.current.setHtmlLabels(true);
        graph.current.setCellsEditable(true);
        graph.current.setCellsDeletable(true);
        graph.current.setCellsMovable(true);
        graph.current.setConnectable(true);
        graph.current.setCellsResizable(true);
        new mxRubberband(graph.current); // Enables rubber-band selection

    }, []);

    const updateGraph = (action) => {
        const model = graph.current.getModel();
        model.beginUpdate();
        try {
            action();
        } finally {
            model.endUpdate();
        }
    };

    const addVertex = () => {
        updateGraph(() => {
            const parent = graph.current.getDefaultParent();
            graph.current.insertVertex(parent, null, 'Node', 100, 100, 80, 30);
        });
    };

    const connectVertices = () => {
        const selectedCells = graph.current.getSelectionCells();
        if (selectedCells.length === 2) {
            updateGraph(() => {
                const parent = graph.current.getDefaultParent();
                graph.current.insertEdge(parent, null, 'Edge', selectedCells[0], selectedCells[1]);
            });
        } else {
            alert('Select exactly two nodes to connect.');
        }
    };

    const deleteVertex = () => {
        const selected = graph.current.getSelectionCell();
        if (selected) {
            updateGraph(() => {
                graph.current.removeCells([selected]);
            });
        } else {
            alert('Please select a node to delete.');
        }
    };

    const saveDiagram = () => {
        const encoder = new mxCodec();
        const result = encoder.encode(graph.current.getModel());
        const xml = mxUtils.getXml(result);
        const blob = new Blob([xml], { type: 'application/xml' });
        const url = URL.createObjectURL(blob);
        const link = document.createElement('a');
        link.setAttribute('href', url);
        link.setAttribute('download', 'diagram.xml');
        link.click();
    };

    const loadDiagram = () => {
        const input = document.createElement('input');
        input.type = 'file';
        input.accept = '.xml';
        input.onchange = e => {
            const file = e.target.files[0];
            if (file) {
                const reader = new FileReader();
                reader.onload = e => {
                    try {
                        const xml = e.target.result;
                        const doc = mxUtils.parseXml(xml);
                        const codec = new mxCodec(doc);
                        const model = graph.current.getModel();
                        model.beginUpdate();
                        try {
                            codec.decode(doc.documentElement, model);
                        } finally {
                            model.endUpdate();
                            graph.current.refresh(); 
                        }
                    } catch (err) {
                        console.error('Error loading the diagram:', err);
                        alert('Failed to load the diagram.');
                    }
                };
                reader.readAsText(file);
            } else {
                alert('No file selected.');
            }
        };
        input.click();
    };

    return (
        <div className="diagram-editor">
            <div ref={graphContainer} className="graph-container" />
            <div className="toolbar">
                <button onClick={addVertex}>Add Node</button>
                <button onClick={connectVertices}>Connect Nodes</button>
                <button onClick={deleteVertex}>Delete Node</button>
                <button onClick={saveDiagram}>Save Diagram</button>
                <button onClick={loadDiagram}>Load Diagram</button>
            </div>
        </div>
    );
};

export default DiagramModifier;

At first I used mxgraph 1.0.1 but I already updated it to the latest version which is 4.2.2

Upvotes: 0

Views: 60

Answers (1)

Nikolay
Nikolay

Reputation: 12245

mxgraph is not available as a module. You must import it into global namespace. Also, it is not supported anymore by the mxgraph team (they switched completely to draw.io as an application and do not provide embeddable component)

There is a fork of it you could try though: https://github.com/maxGraph/maxGraph

Upvotes: 0

Related Questions