-
-
Notifications
You must be signed in to change notification settings - Fork 6k
/
mermaid.ts
547 lines (507 loc) · 16.4 KB
/
mermaid.ts
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
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
/**
* Web page integration module for the mermaid framework. It uses the mermaidAPI for mermaid
* functionality and to render the diagrams to svg code!
*/
import type { MermaidConfig } from './config.type';
import { log } from './logger';
import utils from './utils';
import { mermaidAPI } from './mermaidAPI';
import { addDetector } from './diagram-api/detectType';
import { isDetailedError, type DetailedError } from './utils';
import { registerDiagram } from './diagram-api/diagramAPI';
export type { MermaidConfig, DetailedError };
/**
* ## init
*
* Function that goes through the document to find the chart definitions in there and render them.
*
* The function tags the processed attributes with the attribute data-processed and ignores found
* elements with the attribute already set. This way the init function can be triggered several
* times.
*
* Optionally, `init` can accept in the second argument one of the following:
*
* - A DOM Node
* - An array of DOM nodes (as would come from a jQuery selector)
* - A W3C selector, a la `.mermaid`
*
* ```mermaid
* graph LR;
* a(Find elements)-->b{Processed}
* b-->|Yes|c(Leave element)
* b-->|No |d(Transform)
* ```
*
* Renders the mermaid diagrams
*
* @param config
* @param nodes
* @param callback
*/
const init = async function (
config?: MermaidConfig,
// eslint-disable-next-line no-undef
nodes?: string | HTMLElement | NodeListOf<HTMLElement>,
// eslint-disable-next-line @typescript-eslint/ban-types
callback?: Function
) {
try {
await initThrowsErrors(config, nodes, callback);
} catch (e) {
log.warn('Syntax Error rendering');
if (isDetailedError(e)) {
log.warn(e.str);
}
if (mermaid.parseError) {
mermaid.parseError(e);
}
}
};
// eslint-disable-next-line @typescript-eslint/ban-types
const handleError = (error: unknown, errors: DetailedError[], parseError?: Function) => {
log.warn(error);
if (isDetailedError(error)) {
// handle case where error string and hash were
// wrapped in object like`const error = { str, hash };`
if (parseError) {
parseError(error.str, error.hash);
}
errors.push({ ...error, message: error.str, error });
} else {
// assume it is just error string and pass it on
if (parseError) {
parseError(error);
}
if (error instanceof Error) {
errors.push({
str: error.message,
message: error.message,
hash: error.name,
error,
});
}
}
};
/**
* Equivalent to {@link init()}, except an error will be thrown on error.
*
* @param config - **Deprecated** Mermaid sequenceConfig.
* @param nodes - One of:
* - A DOM Node
* - An array of DOM nodes (as would come from a jQuery selector)
* - A W3C selector, a la `.mermaid` (default)
* @param callback - Function that is called with the id of each generated mermaid diagram.
*
* @returns Resolves on success, otherwise the {@link Promise} will be rejected with an Error.
*/
const initThrowsErrors = async function (
config?: MermaidConfig,
// eslint-disable-next-line no-undef
nodes?: string | HTMLElement | NodeListOf<HTMLElement>,
// eslint-disable-next-line @typescript-eslint/ban-types
callback?: Function
) {
const conf = mermaidAPI.getConfig();
if (config) {
// This is a legacy way of setting config. It is not documented and should be removed in the future.
// @ts-ignore: TODO Fix ts errors
mermaid.sequenceConfig = config;
}
const errors = [];
if (conf?.lazyLoadedDiagrams && conf.lazyLoadedDiagrams.length > 0) {
// Load all lazy loaded diagrams in parallel
const results = await Promise.allSettled(
conf.lazyLoadedDiagrams.map(async (diagram: string) => {
const { id, detector, loadDiagram } = await import(diagram);
addDetector(id, detector, loadDiagram);
})
);
for (const result of results) {
if (result.status == 'rejected') {
log.warn(`Failed to lazyLoadedDiagram due to `, result.reason);
errors.push(result.reason);
}
}
}
// if last argument is a function this is the callback function
log.debug(`${!callback ? 'No ' : ''}Callback function found`);
let nodesToProcess: ArrayLike<HTMLElement>;
if (typeof nodes === 'undefined') {
nodesToProcess = document.querySelectorAll('.mermaid');
} else if (typeof nodes === 'string') {
nodesToProcess = document.querySelectorAll(nodes);
} else if (nodes instanceof HTMLElement) {
nodesToProcess = [nodes];
} else if (nodes instanceof NodeList) {
nodesToProcess = nodes;
} else {
throw new Error('Invalid argument nodes for mermaid.init');
}
log.debug(`Found ${nodesToProcess.length} diagrams`);
if (typeof config?.startOnLoad !== 'undefined') {
log.debug('Start On Load: ' + config?.startOnLoad);
mermaidAPI.updateSiteConfig({ startOnLoad: config?.startOnLoad });
}
// generate the id of the diagram
const idGenerator = new utils.initIdGenerator(conf.deterministicIds, conf.deterministicIDSeed);
let txt: string;
// element is the current div with mermaid class
for (const element of Array.from(nodesToProcess)) {
log.info('Rendering diagram: ' + element.id);
/*! Check if previously processed */
if (element.getAttribute('data-processed')) {
continue;
}
element.setAttribute('data-processed', 'true');
const id = `mermaid-${idGenerator.next()}`;
// Fetch the graph definition including tags
txt = element.innerHTML;
// transforms the html to pure text
txt = utils
.entityDecode(txt)
.trim()
.replace(/<br\s*\/?>/gi, '<br/>');
const init = utils.detectInit(txt);
if (init) {
log.debug('Detected early reinit: ', init);
}
try {
mermaidAPI.render(
id,
txt,
(svgCode: string, bindFunctions?: (el: Element) => void) => {
element.innerHTML = svgCode;
if (typeof callback !== 'undefined') {
callback(id);
}
if (bindFunctions) bindFunctions(element);
},
element
);
} catch (error) {
handleError(error, errors, mermaid.parseError);
}
}
if (errors.length > 0) {
// TODO: We should be throwing an error object.
throw errors[0];
}
};
let lazyLoadingPromise: Promise<unknown> | undefined = undefined;
/**
* @param conf
* @deprecated This is an internal function and should not be used. Will be removed in v10.
*/
const registerLazyLoadedDiagrams = async (conf: MermaidConfig) => {
// Only lazy load once
// TODO: This is a hack. We should either throw error when new diagrams are added, or load them anyway.
if (lazyLoadingPromise === undefined) {
// Load all lazy loaded diagrams in parallel
lazyLoadingPromise = Promise.allSettled(
(conf?.lazyLoadedDiagrams ?? []).map(async (diagram: string) => {
const { id, detector, loadDiagram } = await import(diagram);
addDetector(id, detector, loadDiagram);
})
);
}
await lazyLoadingPromise;
};
let loadingPromise: Promise<unknown> | undefined = undefined;
const loadExternalDiagrams = async (conf: MermaidConfig) => {
// Only lazy load once
// TODO: This is a hack. We should either throw error when new diagrams are added, or load them anyway.
if (loadingPromise === undefined) {
log.debug(`Loading ${conf?.lazyLoadedDiagrams?.length} external diagrams`);
// Load all lazy loaded diagrams in parallel
loadingPromise = Promise.allSettled(
(conf?.lazyLoadedDiagrams ?? []).map(async (url: string) => {
const { id, detector, loadDiagram } = await import(url);
const { diagram } = await loadDiagram();
registerDiagram(id, diagram, detector, diagram.injectUtils);
})
);
}
await loadingPromise;
};
/**
* @deprecated This is an internal function and should not be used. Will be removed in v10.
*/
const initThrowsErrorsAsync = async function (
config?: MermaidConfig,
// eslint-disable-next-line no-undef
nodes?: string | HTMLElement | NodeListOf<HTMLElement>,
// eslint-disable-next-line @typescript-eslint/ban-types
callback?: Function
) {
const conf = mermaidAPI.getConfig();
if (config) {
// This is a legacy way of setting config. It is not documented and should be removed in the future.
// @ts-ignore: TODO Fix ts errors
mermaid.sequenceConfig = config;
}
// if last argument is a function this is the callback function
log.debug(`${!callback ? 'No ' : ''}Callback function found`);
let nodesToProcess: ArrayLike<HTMLElement>;
if (typeof nodes === 'undefined') {
nodesToProcess = document.querySelectorAll('.mermaid');
} else if (typeof nodes === 'string') {
nodesToProcess = document.querySelectorAll(nodes);
} else if (nodes instanceof HTMLElement) {
nodesToProcess = [nodes];
} else if (nodes instanceof NodeList) {
nodesToProcess = nodes;
} else {
throw new Error('Invalid argument nodes for mermaid.init');
}
log.debug(`Found ${nodesToProcess.length} diagrams`);
if (typeof config?.startOnLoad !== 'undefined') {
log.debug('Start On Load: ' + config?.startOnLoad);
mermaidAPI.updateSiteConfig({ startOnLoad: config?.startOnLoad });
}
// generate the id of the diagram
const idGenerator = new utils.initIdGenerator(conf.deterministicIds, conf.deterministicIDSeed);
let txt: string;
const errors: DetailedError[] = [];
// element is the current div with mermaid class
for (const element of Array.from(nodesToProcess)) {
log.info('Rendering diagram: ' + element.id);
/*! Check if previously processed */
if (element.getAttribute('data-processed')) {
continue;
}
element.setAttribute('data-processed', 'true');
const id = `mermaid-${idGenerator.next()}`;
// Fetch the graph definition including tags
txt = element.innerHTML;
// transforms the html to pure text
txt = utils
.entityDecode(txt)
.trim()
.replace(/<br\s*\/?>/gi, '<br/>');
const init = utils.detectInit(txt);
if (init) {
log.debug('Detected early reinit: ', init);
}
try {
await mermaidAPI.renderAsync(
id,
txt,
(svgCode: string, bindFunctions?: (el: Element) => void) => {
element.innerHTML = svgCode;
if (typeof callback !== 'undefined') {
callback(id);
}
if (bindFunctions) bindFunctions(element);
},
element
);
} catch (error) {
handleError(error, errors, mermaid.parseError);
}
}
if (errors.length > 0) {
// TODO: We should be throwing an error object.
throw errors[0];
}
};
const initialize = function (config: MermaidConfig) {
mermaidAPI.initialize(config);
};
/**
* @param config
* @deprecated This is an internal function and should not be used. Will be removed in v10.
*/
const initializeAsync = async function (config: MermaidConfig) {
if (config.loadExternalDiagramsAtStartup) {
await loadExternalDiagrams(config);
} else {
await registerLazyLoadedDiagrams(config);
}
mermaidAPI.initialize(config);
};
/**
* ##contentLoaded Callback function that is called when page is loaded. This functions fetches
* configuration for mermaid rendering and calls init for rendering the mermaid diagrams on the
* page.
*/
const contentLoaded = function () {
if (mermaid.startOnLoad) {
const { startOnLoad } = mermaidAPI.getConfig();
if (startOnLoad) {
mermaid.init();
}
}
};
if (typeof document !== 'undefined') {
/*!
* Wait for document loaded before starting the execution
*/
window.addEventListener('load', contentLoaded, false);
}
/**
* ## setParseErrorHandler Alternative to directly setting parseError using:
*
* ```js
* mermaid.parseError = function(err,hash){=
* forExampleDisplayErrorInGui(err); // do something with the error
* };
* ```
*
* This is provided for environments where the mermaid object can't directly have a new member added
* to it (eg. dart interop wrapper). (Initially there is no parseError member of mermaid).
*
* @param newParseErrorHandler New parseError() callback.
*/
const setParseErrorHandler = function (newParseErrorHandler: (err: any, hash: any) => void) {
mermaid.parseError = newParseErrorHandler;
};
const parse = (txt: string) => {
return mermaidAPI.parse(txt, mermaid.parseError);
};
const executionQueue: (() => Promise<unknown>)[] = [];
let executionQueueRunning = false;
const executeQueue = async () => {
if (executionQueueRunning) {
return;
}
executionQueueRunning = true;
while (executionQueue.length > 0) {
const f = executionQueue.shift();
if (f) {
try {
await f();
} catch (e) {
log.error('Error executing queue', e);
}
}
}
executionQueueRunning = false;
};
/**
* @param txt
* @deprecated This is an internal function and should not be used. Will be removed in v10.
*/
const parseAsync = (txt: string) => {
return new Promise((resolve, reject) => {
// This promise will resolve when the mermaidAPI.render call is done.
// It will be queued first and will be executed when it is first in line
const performCall = () =>
new Promise((res, rej) => {
mermaidAPI.parseAsync(txt, mermaid.parseError).then(
(r) => {
// This resolves for the promise for the queue handling
res(r);
// This fullfills the promise sent to the value back to the original caller
resolve(r);
},
(e) => {
log.error('Error parsing', e);
rej(e);
reject(e);
}
);
});
executionQueue.push(performCall);
executeQueue();
});
};
// const asynco = (id: string, delay: number) =>
// new Promise((res) => {
// setTimeout(() => {
// // This resolves for the promise for the queue handling
// res(id);
// }, delay);
// });
/**
* @param txt
* @param id
* @param delay
* @deprecated This is an internal function and should not be used. Will be removed in v10.
*/
// const test1 = (id: string, delay: number) => {
// const p = new Promise((resolve, reject) => {
// // This promise will resolve when the mermaidAPI.render call is done.
// // It will be queued first and will be executed when it is first in line
// const performCall = () =>
// new Promise((res) => {
// asynco(id, delay).then((r) => {
// // This resolves for the promise for the queue handling
// res(r);
// // This fullfills the promise sent to the value back to the original caller
// resolve(r + ' result to caller');
// });
// });
// executionQueue.push(performCall);
// });
// return p;
// };
/**
* @param txt
* @param id
* @param text
* @param cb
* @param container
* @deprecated This is an internal function and should not be used. Will be removed in v10.
*/
const renderAsync = (
id: string,
text: string,
cb: (svgCode: string, bindFunctions?: (element: Element) => void) => void,
container?: Element
): Promise<void> => {
return new Promise((resolve, reject) => {
// This promise will resolve when the mermaidAPI.render call is done.
// It will be queued first and will be executed when it is first in line
const performCall = () =>
new Promise((res, rej) => {
mermaidAPI.renderAsync(id, text, cb, container).then(
(r) => {
// This resolves for the promise for the queue handling
res(r);
// This fullfills the promise sent to the value back to the original caller
resolve(r);
},
(e) => {
log.error('Error parsing', e);
rej(e);
reject(e);
}
);
});
executionQueue.push(performCall);
executeQueue();
});
};
const mermaid: {
startOnLoad: boolean;
diagrams: any;
// eslint-disable-next-line @typescript-eslint/ban-types
parseError?: Function;
mermaidAPI: typeof mermaidAPI;
parse: typeof parse;
parseAsync: typeof parseAsync;
render: typeof mermaidAPI.render;
renderAsync: typeof renderAsync;
init: typeof init;
initThrowsErrors: typeof initThrowsErrors;
initialize: typeof initialize;
initializeAsync: typeof initializeAsync;
contentLoaded: typeof contentLoaded;
setParseErrorHandler: typeof setParseErrorHandler;
} = {
startOnLoad: true,
diagrams: {},
mermaidAPI,
parse,
parseAsync,
render: mermaidAPI.render,
renderAsync,
init,
initThrowsErrors,
initialize,
initializeAsync,
parseError: undefined,
contentLoaded,
setParseErrorHandler,
};
export default mermaid;