Serialization in EJ2 TypeScript Diagram control
16 Dec 202417 minutes to read
Serialization is the process of converting the state of the diagram into a format that can be saved and later restored. This ensures that the diagram’s current state, including its nodes, connectors, and configurations, can be persisted across sessions.
Serialization involves saving the diagram’s state as a JSON string, which can then be stored in a database, file, or other storage medium. When needed, the serialized string can be deserialized to recreate the diagram in its previous state.
Save
The diagram method saveDiagram
, helps to serialize the diagram as a string. This method captures the entire diagram’s configuration and content, converting it into a string representation.
The following code illustrates how to save the diagram:
//returns serialized string of the Diagram
var savedData = diagram.saveDiagram();
This JSON string can be stored in local storage for future use. The following code illustrates how to save the serialized string into local storage and how to retrieve it:
// Store the serialized string in local storage
localStorage.setItem('fileName', savedData);
// Retrieve the saved string from local storage
savedData = localStorage.getItem('fileName');
The diagram can also be saved as raster or vector image files. For more information about saving the diagram as images, refer to the Print
and Export
section.
Load
The diagram can be loaded from serialized string data using the loadDiagram
method. The saved string should be passed as the parameter of the loadDiagram method. The following code illustrates how to load the diagram from serialized string data:
/*
* Loads the diagram from saved JSON data.
* parameter 1 - The string representing the diagram model JSON to be loaded.
* parameter 2 - Whether it is ej1 data or not (optional)
*/
diagram.loadDiagram(savedData);
NOTE
Before loading a new diagram, existing diagram is cleared.
Prevent Default Values
The preventDefaults
property of serializationSettings is used to simplifying the saved JSON object without adding the default properties that are presented in the diagram.
The preventDefaults
property of serializationSettings
is used to simplify the saved JSON object by excluding default properties that are inherent to the diagram. This helps reduce the size of the serialized data and improves efficiency when saving and loading diagrams.
By enabling preventDefaults, only properties that you set in diagram are included in the serialized JSON object. This optimization is useful for scenarios where minimizing data size is crucial, such as in applications with large diagrams or when optimizing network transfers.
The following code illustrates how to enable the preventDefaults property to simplify the JSON object:
let diagram = new Diagram({
serializationSettings: { preventDefaults: true },
});
Save and load diagram using uploader control
The JSON files can be uploaded using the uploader component, where they are parsed to extract the JSON data they contain. To achieve this, configure the uploader component with the saveUrl property to receive uploaded files and store them on the server. Similarly, use the removeUrl property to handle file removal operations on the server.
When a JSON file is uploaded, it undergoes parsing to extract its JSON data. This data is then loaded into the diagram using the loadDiagram
method.
import { Uploader } from '@syncfusion/ej2-inputs';
import { Diagram, NodeModel, ConnectorModel } from '@syncfusion/ej2-diagrams';
// initialize Uploader component
let uploadObject: Uploader = new Uploader({
asyncSettings: {
saveUrl:
'https://services.syncfusion.com/js/production/api/FileUploader/Save',
removeUrl:
'https://services.syncfusion.com/js/production/api/FileUploader/Remove',
},
success: onUploadSuccess,
});
// render initialized Uploader
uploadObject.appendTo('#fileupload');
function onUploadSuccess(args) {
var file1 = args.file;
var file = file1.rawFile;
var reader = new FileReader();
reader.readAsText(file);
reader.onloadend = loadDiagram;
}
let nodes: NodeModel[] = [
{
id: 'Start',
width: 140,
height: 50,
offsetX: 300,
offsetY: 50,
annotations: [
{
id: 'label1',
content: 'Start',
},
],
shape: {
type: 'Flow',
shape: 'Terminator',
},
},
];
let diagram: Diagram = new Diagram({
width: '100%',
height: '600px',
nodes: nodes,
});
diagram.appendTo('#element');
//Load the diagraming object.
function loadDiagram(event) {
diagram.loadDiagram(event.target.result);
}
(document.getElementById('btnSave') as HTMLElement).onclick = function () {
download(diagram.saveDiagram());
};
//save the diagram object in json data.
function download(data: string): void {
if ((window.navigator as any).msSaveBlob) {
let blob: any = new Blob([data], { type: 'data:text/json;charset=utf-8,' });
(window.navigator as any).msSaveBlob(blob, 'Diagram.json');
} else {
let dataStr: string =
'data:text/json;charset=utf-8,' + encodeURIComponent(data);
let a: HTMLAnchorElement = document.createElement('a');
a.href = dataStr;
a.download = 'Diagram.json';
document.body.appendChild(a);
a.click();
a.remove();
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<title>Essential JS 2 Load Diagram</title>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta name="description" content="Essential JS 2 Diagram Component" />
<meta name="author" content="Syncfusion" />
<link href="index.css" rel="stylesheet" />
<link href="https://cdn.syncfusion.com/ej2/28.1.33/ej2-base/styles/material.css" rel="stylesheet" />
<link href="https://cdn.syncfusion.com/ej2/28.1.33/ej2-inputs/styles/material.css" rel="stylesheet" />
<link href="https://cdn.syncfusion.com/ej2/28.1.33/ej2-popups/styles/material.css" rel="stylesheet" />
<link href="https://cdn.syncfusion.com/ej2/28.1.33/ej2-buttons/styles/material.css" rel="stylesheet" />
<link href="https://cdn.syncfusion.com/ej2/28.1.33/ej2-diagrams/styles/material.css" rel="stylesheet">
<script src="https://cdnjs.cloudflare.com/ajax/libs/systemjs/0.19.38/system.js"></script>
<link href="https://cdn.syncfusion.com/ej2/28.1.33/ej2-navigations/styles/fabric.css" rel="stylesheet" />
<script src="systemjs.config.js"></script>
<script src="https://cdn.syncfusion.com/ej2/syncfusion-helper.js" type ="text/javascript"></script>
</head>
<body>
<div id='loader'>Loading....</div>
<div id='container'>
<label>Browse to load</label>
<input type="file" id="fileupload" name="UploadFiles" />
<button id="btnSave">Save Diagram</button>
<div id="element"></div>
</div>
</body>
</html>
Importing and Exporting Mind Map and Flowchart Diagrams using Mermaid Syntax
The Diagram
supports saving diagrams in Mermaid syntax format. Mermaid is a Markdown-inspired syntax that automatically generates diagrams. With this functionality, you can easily create mind maps and flowcharts from Mermaid syntax data, simplifying the visualization of complex ideas and processes without manual drawing. Additionally, you can export your mind maps and flowcharts to Mermaid syntax, allowing for easy sharing, editing, and use across different platforms.
Save diagram as Mermaid syntax
The saveDiagramAsMermaid
method serializes the diagram into a Mermaid-compatible string format. This method is specifically designed for diagrams that utilize Flowchart and Mind map layouts. The following code illustrates how to save the diagram in Mermaid string format.
//returns the serialized Mermaid string of the Diagram
let data = diagram.saveDiagramAsMermaid();
Load diagram from Mermaid syntax
You can load a diagram from the serialized Mermaid syntax data using the loadDiagramFromMermaid
method. The following code illustrates how to load a diagram from a Mermaid string data.
Load flowchart layout
The following example shows how to load flowchart diagram from mermaid syntax.
import { Diagram, NodeModel, ConnectorModel,FlowchartLayout,DataBinding } from '@syncfusion/ej2-diagrams';
Diagram.Inject(FlowchartLayout,DataBinding);
let diagram: Diagram = new Diagram({
width: '100%',
height: '600px',
layout:{type:'Flowchart'},
getNodeDefaults: function (obj: NodeModel) {
obj.width = 120;
obj.height = 50;
if (obj.shape.shape === 'Decision') {
obj.height = 80;
}
obj.annotations[0].style.bold = true;
return obj;
}, getConnectorDefaults: function (connector: ConnectorModel) {
connector.type = 'Orthogonal';
connector.style.strokeColor = '#6CA0DC';
connector.targetDecorator.style = {fill: '#6CA0DC', strokeColor: '#6CA0DC'};
return connector;
}
});
diagram.appendTo('#element');
let mermaidFlowchartData: string = `flowchart TD
A[Start] --> B(Process)
B -.- C{Decision}
C --Yes--> D[Plan 1]
C ==>|No| E[Plan 2]
style A fill:#90EE90,stroke:#333,stroke-width:2px;
style B fill:#4682B4,stroke:#333,stroke-width:2px;
style C fill:#FFD700,stroke:#333,stroke-width:2px;
style D fill:#FF6347,stroke:#333,stroke-width:2px;
style E fill:#FF6347,stroke:#333,stroke-width:2px;`;
(document.getElementById('loadMermaidFlowchart') as HTMLElement).onclick = function () {
// load the mermaid flowchart data to diagram
//parameter: mermaidFlowchartData - mermaid format string data for flowchart
diagram.loadDiagramFromMermaid(mermaidFlowchartData);
};
<!DOCTYPE html>
<html lang="en">
<head>
<title>Essential JS 2 Load Diagram</title>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta name="description" content="Essential JS 2 Diagram Component" />
<meta name="author" content="Syncfusion" />
<link href="index.css" rel="stylesheet" />
<link href="https://cdn.syncfusion.com/ej2/28.1.33/ej2-base/styles/material.css" rel="stylesheet" />
<link href="https://cdn.syncfusion.com/ej2/28.1.33/ej2-inputs/styles/material.css" rel="stylesheet" />
<link href="https://cdn.syncfusion.com/ej2/28.1.33/ej2-popups/styles/material.css" rel="stylesheet" />
<link href="https://cdn.syncfusion.com/ej2/28.1.33/ej2-buttons/styles/material.css" rel="stylesheet" />
<link href="https://cdn.syncfusion.com/ej2/28.1.33/ej2-diagrams/styles/material.css" rel="stylesheet">
<script src="https://cdnjs.cloudflare.com/ajax/libs/systemjs/0.19.38/system.js"></script>
<link href="https://cdn.syncfusion.com/ej2/28.1.33/ej2-navigations/styles/fabric.css" rel="stylesheet" />
<script src="systemjs.config.js"></script>
<script src="https://cdn.syncfusion.com/ej2/syncfusion-helper.js" type ="text/javascript"></script>
</head>
<body>
<div id='loader'>Loading....</div>
<div id='container'>
<button id="loadMermaidFlowchart">Load</button>
<div id="element"></div>
</div>
</body>
</html>
Load mindmap layout
The following example shows how to load mind map diagram from mermaid syntax.
import { Diagram, NodeModel, ConnectorModel,MindMap,DataBinding } from '@syncfusion/ej2-diagrams';
Diagram.Inject(MindMap,DataBinding);
let diagram: Diagram = new Diagram({
width: '100%',
height: '600px',
layout:{
type:'MindMap',
verticalSpacing: 50,
horizontalSpacing: 50,
orientation: 'Horizontal',
},
getNodeDefaults: function (obj: NodeModel) {
obj.width = 120;
obj.height = 50;
obj.annotations[0].style.bold = true;
return obj;
}, getConnectorDefaults: function (connector: ConnectorModel) {
connector.type = 'Orthogonal';
connector.style.strokeColor = '#6CA0DC';
connector.targetDecorator.shape = 'None';
return connector;
}
});
diagram.appendTo('#element');
let mermaidMindmapData = `mindmap
root((mindmap))
Origins
Popularisation
Research
On effectivness<br/>and features
On Automatic creation
Tools
Pen and paper
Mermaid`;
(document.getElementById('loadMermaidMindmap') as HTMLElement).onclick = function () {
// load the mermaid mindmap data to diagram
//parameter: mermaidMindmapData - mermaid format string data for mindmap
diagram.loadDiagramFromMermaid(mermaidMindmapData);
};
<!DOCTYPE html>
<html lang="en">
<head>
<title>Essential JS 2 Load Diagram</title>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta name="description" content="Essential JS 2 Diagram Component" />
<meta name="author" content="Syncfusion" />
<link href="index.css" rel="stylesheet" />
<link href="https://cdn.syncfusion.com/ej2/28.1.33/ej2-base/styles/material.css" rel="stylesheet" />
<link href="https://cdn.syncfusion.com/ej2/28.1.33/ej2-inputs/styles/material.css" rel="stylesheet" />
<link href="https://cdn.syncfusion.com/ej2/28.1.33/ej2-popups/styles/material.css" rel="stylesheet" />
<link href="https://cdn.syncfusion.com/ej2/28.1.33/ej2-buttons/styles/material.css" rel="stylesheet" />
<link href="https://cdn.syncfusion.com/ej2/28.1.33/ej2-diagrams/styles/material.css" rel="stylesheet">
<script src="https://cdnjs.cloudflare.com/ajax/libs/systemjs/0.19.38/system.js"></script>
<link href="https://cdn.syncfusion.com/ej2/28.1.33/ej2-navigations/styles/fabric.css" rel="stylesheet" />
<script src="systemjs.config.js"></script>
<script src="https://cdn.syncfusion.com/ej2/syncfusion-helper.js" type ="text/javascript"></script>
</head>
<body>
<div id='loader'>Loading....</div>
<div id='container'>
<button id="loadMermaidMindmap">Load</button>
<div id="element"></div>
</div>
</body>
</html>
NOTE
Mermaid syntax data serialization and deserialization are only supported for Flowchart and Mind map layouts. Please ensure that your diagram uses one of these layouts to successfully load the data.