/
stateRenderer.js
317 lines (275 loc) · 8.64 KB
/
stateRenderer.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
import * as d3 from 'd3';
import dagre from 'dagre';
import graphlib from 'graphlib';
import { logger } from '../../logger';
import stateDb from './stateDb';
import { parser } from './parser/stateDiagram';
// import idCache from './id-cache';
import { drawState, addIdAndBox, drawEdge } from './shapes';
import { getConfig } from '../../config';
parser.yy = stateDb;
// TODO Move conf object to main conf in mermaidAPI
let conf;
// {
// // Used
// padding: 5,
// // Font size factor, this is used to guess the width of the edges labels before rendering by dagre
// // layout. This might need updating if/when switching font
// fontSizeFactor: 5.02,
// labelHeight: 16,
// edgeLengthFactor: '20',
// compositTitleSize: 35
// };
const transformationLog = {};
export const setConf = function() {};
// Todo optimize
// const getGraphId = function(label) {
// const keys = idCache.keys();
// for (let i = 0; i < keys.length; i++) {
// if (idCache.get(keys[i]).label === label) {
// return keys[i];
// }
// }
// return undefined;
// };
/**
* Setup arrow head and define the marker. The result is appended to the svg.
*/
const insertMarkers = function(elem) {
elem
.append('defs')
.append('marker')
.attr('id', 'dependencyEnd')
.attr('refX', 19)
.attr('refY', 7)
.attr('markerWidth', 20)
.attr('markerHeight', 28)
.attr('orient', 'auto')
.append('path')
.attr('d', 'M 19,7 L9,13 L14,7 L9,1 Z');
};
/**
* Draws a flowchart in the tag with id: id based on the graph definition in text.
* @param text
* @param id
*/
export const draw = function(text, id) {
conf = getConfig().state;
parser.yy.clear();
parser.parse(text);
logger.debug('Rendering diagram ' + text);
// /// / Fetch the default direction, use TD if none was found
const diagram = d3.select(`[id='${id}']`);
insertMarkers(diagram);
// // Layout graph, Create a new directed graph
const graph = new graphlib.Graph({
multigraph: false,
compound: true,
// acyclicer: 'greedy',
rankdir: 'RL'
// ranksep: '20'
});
// // Default to assigning a new object as a label for each new edge.
graph.setDefaultEdgeLabel(function() {
return {};
});
const rootDoc = stateDb.getRootDoc();
renderDoc(rootDoc, diagram);
const padding = conf.padding;
const bounds = diagram.node().getBBox();
const width = bounds.width + padding * 2;
const height = bounds.height + padding * 2;
// diagram.attr('height', '100%');
// diagram.attr('style', `width: ${bounds.width * 3 + conf.padding * 2};`);
// diagram.attr('height', height);
// Zoom in a bit
diagram.attr('width', width * 2);
// diagram.attr('height', bounds.height * 3 + conf.padding * 2);
diagram.attr(
'viewBox',
`${bounds.x - conf.padding} ${bounds.y - conf.padding} ` + width + ' ' + height
);
// diagram.attr('transform', `translate(, 0)`);
// diagram.attr(
// 'viewBox',
// `${conf.padding * -1} ${conf.padding * -1} ` +
// (bounds.width * 1.5 + conf.padding * 2) +
// ' ' +
// (bounds.height + conf.padding * 5)
// );
};
const getLabelWidth = text => {
return text ? text.length * conf.fontSizeFactor : 1;
};
/* TODO: REMOVE DUPLICATION, SEE SHAPES */
const getRows = s => {
if (!s) return 1;
let str = s.replace(/<br\/?>/gi, '#br#');
str = str.replace(/\\n/g, '#br#');
return str.split('#br#');
};
const renderDoc = (doc, diagram, parentId) => {
// // Layout graph, Create a new directed graph
const graph = new graphlib.Graph({
compound: true
});
// Set an object for the graph label
if (parentId)
graph.setGraph({
rankdir: 'LR',
// multigraph: false,
compound: true,
// acyclicer: 'greedy',
ranker: 'tight-tree',
ranksep: conf.edgeLengthFactor
// isMultiGraph: false
});
else {
graph.setGraph({
rankdir: 'TB',
compound: true,
// isCompound: true,
// acyclicer: 'greedy',
// ranker: 'longest-path'
ranksep: conf.edgeLengthFactor,
ranker: 'tight-tree'
// ranker: 'network-simplex'
// isMultiGraph: false
});
}
// Default to assigning a new object as a label for each new edge.
graph.setDefaultEdgeLabel(function() {
return {};
});
stateDb.extract(doc);
const states = stateDb.getStates();
const relations = stateDb.getRelations();
const keys = Object.keys(states);
let first = true;
for (let i = 0; i < keys.length; i++) {
const stateDef = states[keys[i]];
if (parentId) {
stateDef.parentId = parentId;
}
let node;
if (stateDef.doc) {
let sub = diagram
.append('g')
.attr('id', stateDef.id)
.attr('class', 'stateGroup');
node = renderDoc(stateDef.doc, sub, stateDef.id);
if (first) {
// first = false;
sub = addIdAndBox(sub, stateDef);
let boxBounds = sub.node().getBBox();
node.width = boxBounds.width;
node.height = boxBounds.height + 2 * conf.padding;
transformationLog[stateDef.id] = { y: conf.compositTitleSize };
} else {
// sub = addIdAndBox(sub, stateDef);
let boxBounds = sub.node().getBBox();
node.width = boxBounds.width;
node.height = boxBounds.height;
// transformationLog[stateDef.id] = { y: conf.compositTitleSize };
}
} else {
node = drawState(diagram, stateDef, graph);
}
if (stateDef.note) {
// Draw note note
const noteDef = {
descriptions: [],
id: stateDef.id + '-note',
note: stateDef.note,
type: 'note'
};
const note = drawState(diagram, noteDef, graph);
// graph.setNode(node.id, node);
if (stateDef.note.position === 'left of') {
graph.setNode(node.id + '-note', note);
graph.setNode(node.id, node);
} else {
graph.setNode(node.id, node);
graph.setNode(node.id + '-note', note);
}
// graph.setNode(node.id);
graph.setParent(node.id, node.id + '-group');
graph.setParent(node.id + '-note', node.id + '-group');
} else {
// Add nodes to the graph. The first argument is the node id. The second is
// metadata about the node. In this case we're going to add labels to each of
// our nodes.
graph.setNode(node.id, node);
}
}
logger.info('Count=', graph.nodeCount());
relations.forEach(function(relation) {
graph.setEdge(relation.id1, relation.id2, {
relation: relation,
width: getLabelWidth(relation.title),
height: conf.labelHeight * getRows(relation.title).length,
labelpos: 'c'
});
});
dagre.layout(graph);
logger.debug('Graph after layout', graph.nodes());
const svgElem = diagram.node();
graph.nodes().forEach(function(v) {
if (typeof v !== 'undefined' && typeof graph.node(v) !== 'undefined') {
logger.warn('Node ' + v + ': ' + JSON.stringify(graph.node(v)));
d3.select('#' + svgElem.id + ' #' + v).attr(
'transform',
'translate(' +
(graph.node(v).x - graph.node(v).width / 2) +
',' +
(graph.node(v).y +
(transformationLog[v] ? transformationLog[v].y : 0) -
graph.node(v).height / 2) +
' )'
);
d3.select('#' + svgElem.id + ' #' + v).attr(
'data-x-shift',
graph.node(v).x - graph.node(v).width / 2
);
const dividers = document.querySelectorAll('#' + svgElem.id + ' #' + v + ' .divider');
dividers.forEach(divider => {
const parent = divider.parentElement;
let pWidth = 0;
let pShift = 0;
if (parent) {
if (parent.parentElement) pWidth = parent.parentElement.getBBox().width;
pShift = parseInt(parent.getAttribute('data-x-shift'), 10);
if (Number.isNaN(pShift)) {
pShift = 0;
}
}
divider.setAttribute('x1', 0 - pShift);
divider.setAttribute('x2', pWidth - pShift);
});
} else {
logger.debug('No Node ' + v + ': ' + JSON.stringify(graph.node(v)));
}
});
let stateBox = svgElem.getBBox();
graph.edges().forEach(function(e) {
if (typeof e !== 'undefined' && typeof graph.edge(e) !== 'undefined') {
logger.debug('Edge ' + e.v + ' -> ' + e.w + ': ' + JSON.stringify(graph.edge(e)));
drawEdge(diagram, graph.edge(e), graph.edge(e).relation);
}
});
stateBox = svgElem.getBBox();
const stateInfo = {
id: parentId ? parentId : 'root',
label: parentId ? parentId : 'root',
width: 0,
height: 0
};
stateInfo.width = stateBox.width + 2 * conf.padding;
stateInfo.height = stateBox.height + 2 * conf.padding;
logger.info('Doc rendered', stateInfo, graph);
return stateInfo;
};
export default {
setConf,
draw
};