mermaid/src/Diagram.js

73 lines
2.1 KiB
JavaScript
Raw Normal View History

2022-02-10 20:32:21 +01:00
import utils from './utils';
import * as configApi from './config';
import { log } from './logger';
2022-07-18 16:00:03 +02:00
import { getDiagrams } from './diagram-api/diagramAPI';
import detectType from './diagram-api/detectType';
2022-02-10 20:32:21 +01:00
class Diagram {
type = 'graph';
parser;
renderer;
db;
constructor(txt) {
2022-07-18 16:00:03 +02:00
const diagrams = getDiagrams();
2022-02-10 20:32:21 +01:00
const cnf = configApi.getConfig();
this.txt = txt;
2022-07-18 16:00:03 +02:00
this.type = detectType(txt, cnf);
2022-02-10 20:32:21 +01:00
log.debug('Type ' + this.type);
2022-07-18 16:00:03 +02:00
// console.log('this.type', this.type, diagrams[this.type]);
// Setup diagram
this.db = diagrams[this.type].db;
this.renderer = diagrams[this.type].renderer;
this.parser = diagrams[this.type].parser;
this.parser.parser.yy = this.db;
if (typeof diagrams[this.type].init === 'function') {
diagrams[this.type].init(cnf);
log.debug('Initialized diagram ' + this.type, cnf);
2022-02-10 20:32:21 +01:00
}
2022-07-18 16:00:03 +02:00
this.txt = this.txt + '\n';
2022-02-10 20:32:21 +01:00
this.parser.parser.yy.graphType = this.type;
this.parser.parser.yy.parseError = (str, hash) => {
const error = { str, hash };
throw error;
};
2022-07-04 12:37:50 +02:00
this.parser.parse(this.txt);
2022-02-10 20:32:21 +01:00
}
2022-07-18 16:00:03 +02:00
parse(text) {
var parseEncounteredException = false;
try {
text = text + '\n';
this.db.clear();
this.parser.parse(text);
} catch (error) {
parseEncounteredException = true;
// Is this the correct way to access mermiad's parseError()
// method ? (or global.mermaid.parseError()) ?
if (global.mermaid.parseError) {
if (error.str != undefined) {
// handle case where error string and hash were
// wrapped in object like`const error = { str, hash };`
global.mermaid.parseError(error.str, error.hash);
} else {
// assume it is just error string and pass it on
global.mermaid.parseError(error);
}
} else {
// No mermaid.parseError() handler defined, so re-throw it
throw error;
}
}
return !parseEncounteredException;
}
2022-02-10 20:32:21 +01:00
getParser() {
return this.parser;
}
getType() {
return this.type;
}
}
export default Diagram;