Merge from upstream mermaid OS develop

This commit is contained in:
Ashish Jain
2025-01-24 12:47:42 +01:00
18 changed files with 1465 additions and 1249 deletions

View File

@@ -0,0 +1,5 @@
---
'mermaid': patch
---
fix: `mermaidAPI.getDiagramFromText()` now returns a new different db for each class diagram

View File

@@ -0,0 +1,5 @@
---
'mermaid': patch
---
`mermaidAPI.getDiagramFromText()` now returns a new different db for each state diagram

View File

@@ -24,23 +24,53 @@ import type {
Interface, Interface,
} from './classTypes.js'; } from './classTypes.js';
import type { Node, Edge } from '../../rendering-util/types.js'; import type { Node, Edge } from '../../rendering-util/types.js';
import type { DiagramDB } from '../../diagram-api/types.js';
const MERMAID_DOM_ID_PREFIX = 'classId-'; const MERMAID_DOM_ID_PREFIX = 'classId-';
let relations: ClassRelation[] = [];
let classes = new Map<string, ClassNode>();
const styleClasses = new Map<string, StyleClass>();
let notes: ClassNote[] = [];
let interfaces: Interface[] = [];
let classCounter = 0; let classCounter = 0;
let namespaces = new Map<string, NamespaceNode>();
let namespaceCounter = 0;
let functions: any[] = [];
const sanitizeText = (txt: string) => common.sanitizeText(txt, getConfig()); const sanitizeText = (txt: string) => common.sanitizeText(txt, getConfig());
const splitClassNameAndType = function (_id: string) { export class ClassDB implements DiagramDB {
private relations: ClassRelation[] = [];
private classes = new Map<string, ClassNode>();
private readonly styleClasses = new Map<string, StyleClass>();
private notes: ClassNote[] = [];
private interfaces: Interface[] = [];
// private static classCounter = 0;
private namespaces = new Map<string, NamespaceNode>();
private namespaceCounter = 0;
private functions: any[] = [];
constructor() {
this.functions.push(this.setupToolTips.bind(this));
this.clear();
// Needed for JISON since it only supports direct properties
this.addRelation = this.addRelation.bind(this);
this.addClassesToNamespace = this.addClassesToNamespace.bind(this);
this.addNamespace = this.addNamespace.bind(this);
this.setCssClass = this.setCssClass.bind(this);
this.addMembers = this.addMembers.bind(this);
this.addClass = this.addClass.bind(this);
this.setClassLabel = this.setClassLabel.bind(this);
this.addAnnotation = this.addAnnotation.bind(this);
this.addMember = this.addMember.bind(this);
this.cleanupLabel = this.cleanupLabel.bind(this);
this.addNote = this.addNote.bind(this);
this.defineClass = this.defineClass.bind(this);
this.setDirection = this.setDirection.bind(this);
this.setLink = this.setLink.bind(this);
this.bindFunctions = this.bindFunctions.bind(this);
this.clear = this.clear.bind(this);
this.setTooltip = this.setTooltip.bind(this);
this.setClickEvent = this.setClickEvent.bind(this);
this.setCssStyle = this.setCssStyle.bind(this);
}
private splitClassNameAndType(_id: string) {
const id = common.sanitizeText(_id, getConfig()); const id = common.sanitizeText(_id, getConfig());
let genericType = ''; let genericType = '';
let className = id; let className = id;
@@ -52,19 +82,19 @@ const splitClassNameAndType = function (_id: string) {
} }
return { className: className, type: genericType }; return { className: className, type: genericType };
}; }
export const setClassLabel = function (_id: string, label: string) { public setClassLabel(_id: string, label: string) {
const id = common.sanitizeText(_id, getConfig()); const id = common.sanitizeText(_id, getConfig());
if (label) { if (label) {
label = sanitizeText(label); label = sanitizeText(label);
} }
const { className } = splitClassNameAndType(id); const { className } = this.splitClassNameAndType(id);
classes.get(className)!.label = label; this.classes.get(className)!.label = label;
classes.get(className)!.text = this.classes.get(className)!.text =
`${label}${classes.get(className)!.type ? `<${classes.get(className)!.type}>` : ''}`; `${label}${this.classes.get(className)!.type ? `<${this.classes.get(className)!.type}>` : ''}`;
}; }
/** /**
* Function called by parser when a node definition has been found. * Function called by parser when a node definition has been found.
@@ -72,17 +102,17 @@ export const setClassLabel = function (_id: string, label: string) {
* @param id - Id of the class to add * @param id - Id of the class to add
* @public * @public
*/ */
export const addClass = function (_id: string) { public addClass(_id: string) {
const id = common.sanitizeText(_id, getConfig()); const id = common.sanitizeText(_id, getConfig());
const { className, type } = splitClassNameAndType(id); const { className, type } = this.splitClassNameAndType(id);
// Only add class if not exists // Only add class if not exists
if (classes.has(className)) { if (this.classes.has(className)) {
return; return;
} }
// alert('Adding class: ' + className); // alert('Adding class: ' + className);
const name = common.sanitizeText(className, getConfig()); const name = common.sanitizeText(className, getConfig());
// alert('Adding class after: ' + name); // alert('Adding class after: ' + name);
classes.set(name, { this.classes.set(name, {
id: name, id: name,
type: type, type: type,
label: name, label: name,
@@ -97,17 +127,17 @@ export const addClass = function (_id: string) {
} as ClassNode); } as ClassNode);
classCounter++; classCounter++;
}; }
const addInterface = function (label: string, classId: string) { private addInterface(label: string, classId: string) {
const classInterface: Interface = { const classInterface: Interface = {
id: `interface${interfaces.length}`, id: `interface${this.interfaces.length}`,
label, label,
classId, classId,
}; };
interfaces.push(classInterface); this.interfaces.push(classInterface);
}; }
/** /**
* Function to lookup domId from id in the graph definition. * Function to lookup domId from id in the graph definition.
@@ -115,75 +145,75 @@ const addInterface = function (label: string, classId: string) {
* @param id - class ID to lookup * @param id - class ID to lookup
* @public * @public
*/ */
export const lookUpDomId = function (_id: string): string { public lookUpDomId(_id: string): string {
const id = common.sanitizeText(_id, getConfig()); const id = common.sanitizeText(_id, getConfig());
if (classes.has(id)) { if (this.classes.has(id)) {
return classes.get(id)!.domId; return this.classes.get(id)!.domId;
} }
throw new Error('Class not found: ' + id); throw new Error('Class not found: ' + id);
}; }
export const clear = function () { public clear() {
relations = []; this.relations = [];
classes = new Map(); this.classes = new Map();
notes = []; this.notes = [];
interfaces = []; this.interfaces = [];
functions = []; this.functions = [];
functions.push(setupToolTips); this.functions.push(this.setupToolTips.bind(this));
namespaces = new Map(); this.namespaces = new Map();
namespaceCounter = 0; this.namespaceCounter = 0;
direction = 'TB'; this.direction = 'TB';
commonClear(); commonClear();
}; }
export const getClass = function (id: string): ClassNode { public getClass(id: string): ClassNode {
return classes.get(id)!; return this.classes.get(id)!;
}; }
export const getClasses = function (): ClassMap { public getClasses(): ClassMap {
return classes; return this.classes;
}; }
export const getRelations = function (): ClassRelation[] { public getRelations(): ClassRelation[] {
return relations; return this.relations;
}; }
export const getNotes = function () { public getNotes() {
return notes; return this.notes;
}; }
export const addRelation = function (classRelation: ClassRelation) { public addRelation(classRelation: ClassRelation) {
log.debug('Adding relation: ' + JSON.stringify(classRelation)); log.debug('Adding relation: ' + JSON.stringify(classRelation));
// Due to relationType cannot just check if it is equal to 'none' or it complains, can fix this later // Due to relationType cannot just check if it is equal to 'none' or it complains, can fix this later
const invalidTypes = [ const invalidTypes = [
relationType.LOLLIPOP, this.relationType.LOLLIPOP,
relationType.AGGREGATION, this.relationType.AGGREGATION,
relationType.COMPOSITION, this.relationType.COMPOSITION,
relationType.DEPENDENCY, this.relationType.DEPENDENCY,
relationType.EXTENSION, this.relationType.EXTENSION,
]; ];
if ( if (
classRelation.relation.type1 === relationType.LOLLIPOP && classRelation.relation.type1 === this.relationType.LOLLIPOP &&
!invalidTypes.includes(classRelation.relation.type2) !invalidTypes.includes(classRelation.relation.type2)
) { ) {
addClass(classRelation.id2); this.addClass(classRelation.id2);
addInterface(classRelation.id1, classRelation.id2); this.addInterface(classRelation.id1, classRelation.id2);
classRelation.id1 = `interface${interfaces.length - 1}`; classRelation.id1 = `interface${this.interfaces.length - 1}`;
} else if ( } else if (
classRelation.relation.type2 === relationType.LOLLIPOP && classRelation.relation.type2 === this.relationType.LOLLIPOP &&
!invalidTypes.includes(classRelation.relation.type1) !invalidTypes.includes(classRelation.relation.type1)
) { ) {
addClass(classRelation.id1); this.addClass(classRelation.id1);
addInterface(classRelation.id2, classRelation.id1); this.addInterface(classRelation.id2, classRelation.id1);
classRelation.id2 = `interface${interfaces.length - 1}`; classRelation.id2 = `interface${this.interfaces.length - 1}`;
} else { } else {
addClass(classRelation.id1); this.addClass(classRelation.id1);
addClass(classRelation.id2); this.addClass(classRelation.id2);
} }
classRelation.id1 = splitClassNameAndType(classRelation.id1).className; classRelation.id1 = this.splitClassNameAndType(classRelation.id1).className;
classRelation.id2 = splitClassNameAndType(classRelation.id2).className; classRelation.id2 = this.splitClassNameAndType(classRelation.id2).className;
classRelation.relationTitle1 = common.sanitizeText( classRelation.relationTitle1 = common.sanitizeText(
classRelation.relationTitle1.trim(), classRelation.relationTitle1.trim(),
@@ -195,8 +225,8 @@ export const addRelation = function (classRelation: ClassRelation) {
getConfig() getConfig()
); );
relations.push(classRelation); this.relations.push(classRelation);
}; }
/** /**
* Adds an annotation to the specified class Annotations mark special properties of the given type * Adds an annotation to the specified class Annotations mark special properties of the given type
@@ -206,10 +236,10 @@ export const addRelation = function (classRelation: ClassRelation) {
* @param annotation - The name of the annotation without any brackets * @param annotation - The name of the annotation without any brackets
* @public * @public
*/ */
export const addAnnotation = function (className: string, annotation: string) { public addAnnotation(className: string, annotation: string) {
const validatedClassName = splitClassNameAndType(className).className; const validatedClassName = this.splitClassNameAndType(className).className;
classes.get(validatedClassName)!.annotations.push(annotation); this.classes.get(validatedClassName)!.annotations.push(annotation);
}; }
/** /**
* Adds a member to the specified class * Adds a member to the specified class
@@ -220,11 +250,11 @@ export const addAnnotation = function (className: string, annotation: string) {
* method Otherwise the member will be treated as a normal property * method Otherwise the member will be treated as a normal property
* @public * @public
*/ */
export const addMember = function (className: string, member: string) { public addMember(className: string, member: string) {
addClass(className); this.addClass(className);
const validatedClassName = splitClassNameAndType(className).className; const validatedClassName = this.splitClassNameAndType(className).className;
const theClass = classes.get(validatedClassName)!; const theClass = this.classes.get(validatedClassName)!;
if (typeof member === 'string') { if (typeof member === 'string') {
// Member can contain white spaces, we trim them out // Member can contain white spaces, we trim them out
@@ -240,30 +270,30 @@ export const addMember = function (className: string, member: string) {
theClass.members.push(new ClassMember(memberString, 'attribute')); theClass.members.push(new ClassMember(memberString, 'attribute'));
} }
} }
}; }
export const addMembers = function (className: string, members: string[]) { public addMembers(className: string, members: string[]) {
if (Array.isArray(members)) { if (Array.isArray(members)) {
members.reverse(); members.reverse();
members.forEach((member) => addMember(className, member)); members.forEach((member) => this.addMember(className, member));
}
} }
};
export const addNote = function (text: string, className: string) { public addNote(text: string, className: string) {
const note = { const note = {
id: `note${notes.length}`, id: `note${this.notes.length}`,
class: className, class: className,
text: text, text: text,
}; };
notes.push(note); this.notes.push(note);
}; }
export const cleanupLabel = function (label: string) { public cleanupLabel(label: string) {
if (label.startsWith(':')) { if (label.startsWith(':')) {
label = label.substring(1); label = label.substring(1);
} }
return sanitizeText(label.trim()); return sanitizeText(label.trim());
}; }
/** /**
* Called by parser when assigning cssClass to a class * Called by parser when assigning cssClass to a class
@@ -271,29 +301,29 @@ export const cleanupLabel = function (label: string) {
* @param ids - Comma separated list of ids * @param ids - Comma separated list of ids
* @param className - Class to add * @param className - Class to add
*/ */
export const setCssClass = function (ids: string, className: string) { public setCssClass(ids: string, className: string) {
ids.split(',').forEach(function (_id) { ids.split(',').forEach((_id) => {
let id = _id; let id = _id;
if (/\d/.exec(_id[0])) { if (/\d/.exec(_id[0])) {
id = MERMAID_DOM_ID_PREFIX + id; id = MERMAID_DOM_ID_PREFIX + id;
} }
const classNode = classes.get(id); const classNode = this.classes.get(id);
if (classNode) { if (classNode) {
classNode.cssClasses += ' ' + className; classNode.cssClasses += ' ' + className;
} }
}); });
}; }
export const defineClass = function (ids: string[], style: string[]) { public defineClass(ids: string[], style: string[]) {
for (const id of ids) { for (const id of ids) {
let styleClass = styleClasses.get(id); let styleClass = this.styleClasses.get(id);
if (styleClass === undefined) { if (styleClass === undefined) {
styleClass = { id, styles: [], textStyles: [] }; styleClass = { id, styles: [], textStyles: [] };
styleClasses.set(id, styleClass); this.styleClasses.set(id, styleClass);
} }
if (style) { if (style) {
style.forEach(function (s) { style.forEach((s) => {
if (/color/.exec(s)) { if (/color/.exec(s)) {
const newStyle = s.replace('fill', 'bgFill'); // .replace('color', 'fill'); const newStyle = s.replace('fill', 'bgFill'); // .replace('color', 'fill');
styleClass.textStyles.push(newStyle); styleClass.textStyles.push(newStyle);
@@ -302,13 +332,13 @@ export const defineClass = function (ids: string[], style: string[]) {
}); });
} }
classes.forEach((value) => { this.classes.forEach((value) => {
if (value.cssClasses.includes(id)) { if (value.cssClasses.includes(id)) {
value.styles.push(...style.flatMap((s) => s.split(','))); value.styles.push(...style.flatMap((s) => s.split(',')));
} }
}); });
} }
}; }
/** /**
* Called by parser when a tooltip is found, e.g. a clickable element. * Called by parser when a tooltip is found, e.g. a clickable element.
@@ -316,21 +346,21 @@ export const defineClass = function (ids: string[], style: string[]) {
* @param ids - Comma separated list of ids * @param ids - Comma separated list of ids
* @param tooltip - Tooltip to add * @param tooltip - Tooltip to add
*/ */
const setTooltip = function (ids: string, tooltip?: string) { public setTooltip(ids: string, tooltip?: string) {
ids.split(',').forEach(function (id) { ids.split(',').forEach((id) => {
if (tooltip !== undefined) { if (tooltip !== undefined) {
classes.get(id)!.tooltip = sanitizeText(tooltip); this.classes.get(id)!.tooltip = sanitizeText(tooltip);
} }
}); });
};
export const getTooltip = function (id: string, namespace?: string) {
if (namespace && namespaces.has(namespace)) {
return namespaces.get(namespace)!.classes.get(id)!.tooltip;
} }
return classes.get(id)!.tooltip; public getTooltip(id: string, namespace?: string) {
}; if (namespace && this.namespaces.has(namespace)) {
return this.namespaces.get(namespace)!.classes.get(id)!.tooltip;
}
return this.classes.get(id)!.tooltip;
}
/** /**
* Called by parser when a link is found. Adds the URL to the vertex data. * Called by parser when a link is found. Adds the URL to the vertex data.
@@ -339,14 +369,14 @@ export const getTooltip = function (id: string, namespace?: string) {
* @param linkStr - URL to create a link for * @param linkStr - URL to create a link for
* @param target - Target of the link, _blank by default as originally defined in the svgDraw.js file * @param target - Target of the link, _blank by default as originally defined in the svgDraw.js file
*/ */
export const setLink = function (ids: string, linkStr: string, target: string) { public setLink(ids: string, linkStr: string, target: string) {
const config = getConfig(); const config = getConfig();
ids.split(',').forEach(function (_id) { ids.split(',').forEach((_id) => {
let id = _id; let id = _id;
if (/\d/.exec(_id[0])) { if (/\d/.exec(_id[0])) {
id = MERMAID_DOM_ID_PREFIX + id; id = MERMAID_DOM_ID_PREFIX + id;
} }
const theClass = classes.get(id); const theClass = this.classes.get(id);
if (theClass) { if (theClass) {
theClass.link = utils.formatUrl(linkStr, config); theClass.link = utils.formatUrl(linkStr, config);
if (config.securityLevel === 'sandbox') { if (config.securityLevel === 'sandbox') {
@@ -358,8 +388,8 @@ export const setLink = function (ids: string, linkStr: string, target: string) {
} }
} }
}); });
setCssClass(ids, 'clickable'); this.setCssClass(ids, 'clickable');
}; }
/** /**
* Called by parser when a click definition is found. Registers an event handler. * Called by parser when a click definition is found. Registers an event handler.
@@ -368,15 +398,15 @@ export const setLink = function (ids: string, linkStr: string, target: string) {
* @param functionName - Function to be called on click * @param functionName - Function to be called on click
* @param functionArgs - Function args the function should be called with * @param functionArgs - Function args the function should be called with
*/ */
export const setClickEvent = function (ids: string, functionName: string, functionArgs: string) { public setClickEvent(ids: string, functionName: string, functionArgs: string) {
ids.split(',').forEach(function (id) { ids.split(',').forEach((id) => {
setClickFunc(id, functionName, functionArgs); this.setClickFunc(id, functionName, functionArgs);
classes.get(id)!.haveCallback = true; this.classes.get(id)!.haveCallback = true;
}); });
setCssClass(ids, 'clickable'); this.setCssClass(ids, 'clickable');
}; }
const setClickFunc = function (_domId: string, functionName: string, functionArgs: string) { private setClickFunc(_domId: string, functionName: string, functionArgs: string) {
const domId = common.sanitizeText(_domId, getConfig()); const domId = common.sanitizeText(_domId, getConfig());
const config = getConfig(); const config = getConfig();
if (config.securityLevel !== 'loose') { if (config.securityLevel !== 'loose') {
@@ -387,8 +417,8 @@ const setClickFunc = function (_domId: string, functionName: string, functionArg
} }
const id = domId; const id = domId;
if (classes.has(id)) { if (this.classes.has(id)) {
const elemId = lookUpDomId(id); const elemId = this.lookUpDomId(id);
let argList: string[] = []; let argList: string[] = [];
if (typeof functionArgs === 'string') { if (typeof functionArgs === 'string') {
/* Splits functionArgs by ',', ignoring all ',' in double quoted strings */ /* Splits functionArgs by ',', ignoring all ',' in double quoted strings */
@@ -409,12 +439,12 @@ const setClickFunc = function (_domId: string, functionName: string, functionArg
argList.push(elemId); argList.push(elemId);
} }
functions.push(function () { this.functions.push(() => {
const elem = document.querySelector(`[id="${elemId}"]`); const elem = document.querySelector(`[id="${elemId}"]`);
if (elem !== null) { if (elem !== null) {
elem.addEventListener( elem.addEventListener(
'click', 'click',
function () { () => {
utils.runFunc(functionName, ...argList); utils.runFunc(functionName, ...argList);
}, },
false false
@@ -422,20 +452,20 @@ const setClickFunc = function (_domId: string, functionName: string, functionArg
} }
}); });
} }
}; }
export const bindFunctions = function (element: Element) { public bindFunctions(element: Element) {
functions.forEach(function (fun) { this.functions.forEach((fun) => {
fun(element); fun(element);
}); });
}; }
export const lineType = { public readonly lineType = {
LINE: 0, LINE: 0,
DOTTED_LINE: 1, DOTTED_LINE: 1,
}; };
export const relationType = { public readonly relationType = {
AGGREGATION: 0, AGGREGATION: 0,
EXTENSION: 1, EXTENSION: 1,
COMPOSITION: 2, COMPOSITION: 2,
@@ -443,20 +473,23 @@ export const relationType = {
LOLLIPOP: 4, LOLLIPOP: 4,
}; };
const setupToolTips = function (element: Element) { private readonly setupToolTips = (element: Element) => {
let tooltipElem: Selection<HTMLDivElement, unknown, HTMLElement, unknown> = let tooltipElem: Selection<HTMLDivElement, unknown, HTMLElement, unknown> =
select('.mermaidTooltip'); select('.mermaidTooltip');
// @ts-expect-error - Incorrect types // @ts-expect-error - Incorrect types
if ((tooltipElem._groups || tooltipElem)[0][0] === null) { if ((tooltipElem._groups || tooltipElem)[0][0] === null) {
tooltipElem = select('body').append('div').attr('class', 'mermaidTooltip').style('opacity', 0); tooltipElem = select('body')
.append('div')
.attr('class', 'mermaidTooltip')
.style('opacity', 0);
} }
const svg = select(element).select('svg'); const svg = select(element).select('svg');
const nodes = svg.selectAll('g.node'); const nodes = svg.selectAll('g.node');
nodes nodes
.on('mouseover', function () { .on('mouseover', (event: MouseEvent) => {
const el = select(this); const el = select(event.currentTarget as HTMLElement);
const title = el.attr('title'); const title = el.attr('title');
// Don't try to draw a tooltip if no data is provided // Don't try to draw a tooltip if no data is provided
if (title === null) { if (title === null) {
@@ -473,19 +506,20 @@ const setupToolTips = function (element: Element) {
tooltipElem.html(tooltipElem.html().replace(/&lt;br\/&gt;/g, '<br/>')); tooltipElem.html(tooltipElem.html().replace(/&lt;br\/&gt;/g, '<br/>'));
el.classed('hover', true); el.classed('hover', true);
}) })
.on('mouseout', function () { .on('mouseout', (event: MouseEvent) => {
tooltipElem.transition().duration(500).style('opacity', 0); tooltipElem.transition().duration(500).style('opacity', 0);
const el = select(this); const el = select(event.currentTarget as HTMLElement);
el.classed('hover', false); el.classed('hover', false);
}); });
}; };
functions.push(setupToolTips);
let direction = 'TB'; private direction = 'TB';
const getDirection = () => direction; public getDirection() {
const setDirection = (dir: string) => { return this.direction;
direction = dir; }
}; public setDirection(dir: string) {
this.direction = dir;
}
/** /**
* Function called by parser when a namespace definition has been found. * Function called by parser when a namespace definition has been found.
@@ -493,28 +527,28 @@ const setDirection = (dir: string) => {
* @param id - Id of the namespace to add * @param id - Id of the namespace to add
* @public * @public
*/ */
export const addNamespace = function (id: string) { public addNamespace(id: string) {
if (namespaces.has(id)) { if (this.namespaces.has(id)) {
return; return;
} }
namespaces.set(id, { this.namespaces.set(id, {
id: id, id: id,
classes: new Map(), classes: new Map(),
children: {}, children: {},
domId: MERMAID_DOM_ID_PREFIX + id + '-' + namespaceCounter, domId: MERMAID_DOM_ID_PREFIX + id + '-' + this.namespaceCounter,
} as NamespaceNode); } as NamespaceNode);
namespaceCounter++; this.namespaceCounter++;
}; }
const getNamespace = function (name: string): NamespaceNode { public getNamespace(name: string): NamespaceNode {
return namespaces.get(name)!; return this.namespaces.get(name)!;
}; }
const getNamespaces = function (): NamespaceMap { public getNamespaces(): NamespaceMap {
return namespaces; return this.namespaces;
}; }
/** /**
* Function called by parser when a namespace definition has been found. * Function called by parser when a namespace definition has been found.
@@ -523,19 +557,19 @@ const getNamespaces = function (): NamespaceMap {
* @param classNames - Ids of the class to add * @param classNames - Ids of the class to add
* @public * @public
*/ */
export const addClassesToNamespace = function (id: string, classNames: string[]) { public addClassesToNamespace(id: string, classNames: string[]) {
if (!namespaces.has(id)) { if (!this.namespaces.has(id)) {
return; return;
} }
for (const name of classNames) { for (const name of classNames) {
const { className } = splitClassNameAndType(name); const { className } = this.splitClassNameAndType(name);
classes.get(className)!.parent = id; this.classes.get(className)!.parent = id;
namespaces.get(id)!.classes.set(className, classes.get(className)!); this.namespaces.get(id)!.classes.set(className, this.classes.get(className)!);
}
} }
};
export const setCssStyle = function (id: string, styles: string[]) { public setCssStyle(id: string, styles: string[]) {
const thisClass = classes.get(id); const thisClass = this.classes.get(id);
if (!styles || !thisClass) { if (!styles || !thisClass) {
return; return;
} }
@@ -546,7 +580,7 @@ export const setCssStyle = function (id: string, styles: string[]) {
thisClass.styles.push(s); thisClass.styles.push(s);
} }
} }
}; }
/** /**
* Gets the arrow marker for a type index * Gets the arrow marker for a type index
@@ -554,7 +588,7 @@ export const setCssStyle = function (id: string, styles: string[]) {
* @param type - The type to look for * @param type - The type to look for
* @returns The arrow marker * @returns The arrow marker
*/ */
function getArrowMarker(type: number) { private getArrowMarker(type: number) {
let marker; let marker;
switch (type) { switch (type) {
case 0: case 0:
@@ -578,13 +612,13 @@ function getArrowMarker(type: number) {
return marker; return marker;
} }
export const getData = () => { public getData() {
const nodes: Node[] = []; const nodes: Node[] = [];
const edges: Edge[] = []; const edges: Edge[] = [];
const config = getConfig(); const config = getConfig();
for (const namespaceKey of namespaces.keys()) { for (const namespaceKey of this.namespaces.keys()) {
const namespace = namespaces.get(namespaceKey); const namespace = this.namespaces.get(namespaceKey);
if (namespace) { if (namespace) {
const node: Node = { const node: Node = {
id: namespace.id, id: namespace.id,
@@ -600,8 +634,8 @@ export const getData = () => {
} }
} }
for (const classKey of classes.keys()) { for (const classKey of this.classes.keys()) {
const classNode = classes.get(classKey); const classNode = this.classes.get(classKey);
if (classNode) { if (classNode) {
const node = classNode as unknown as Node; const node = classNode as unknown as Node;
node.parentId = classNode.parent; node.parentId = classNode.parent;
@@ -611,7 +645,7 @@ export const getData = () => {
} }
let cnt = 0; let cnt = 0;
for (const note of notes) { for (const note of this.notes) {
cnt++; cnt++;
const noteNode: Node = { const noteNode: Node = {
id: note.id, id: note.id,
@@ -629,7 +663,7 @@ export const getData = () => {
}; };
nodes.push(noteNode); nodes.push(noteNode);
const noteClassId = classes.get(note.class)?.id ?? ''; const noteClassId = this.classes.get(note.class)?.id ?? '';
if (noteClassId) { if (noteClassId) {
const edge: Edge = { const edge: Edge = {
@@ -651,7 +685,7 @@ export const getData = () => {
} }
} }
for (const _interface of interfaces) { for (const _interface of this.interfaces) {
const interfaceNode: Node = { const interfaceNode: Node = {
id: _interface.id, id: _interface.id,
label: _interface.label, label: _interface.label,
@@ -664,7 +698,7 @@ export const getData = () => {
} }
cnt = 0; cnt = 0;
for (const classRelation of relations) { for (const classRelation of this.relations) {
cnt++; cnt++;
const edge: Edge = { const edge: Edge = {
id: getEdgeId(classRelation.id1, classRelation.id2, { id: getEdgeId(classRelation.id1, classRelation.id2, {
@@ -678,9 +712,10 @@ export const getData = () => {
labelpos: 'c', labelpos: 'c',
thickness: 'normal', thickness: 'normal',
classes: 'relation', classes: 'relation',
arrowTypeStart: getArrowMarker(classRelation.relation.type1), arrowTypeStart: this.getArrowMarker(classRelation.relation.type1),
arrowTypeEnd: getArrowMarker(classRelation.relation.type2), arrowTypeEnd: this.getArrowMarker(classRelation.relation.type2),
startLabelRight: classRelation.relationTitle1 === 'none' ? '' : classRelation.relationTitle1, startLabelRight:
classRelation.relationTitle1 === 'none' ? '' : classRelation.relationTitle1,
endLabelLeft: classRelation.relationTitle2 === 'none' ? '' : classRelation.relationTitle2, endLabelLeft: classRelation.relationTitle2 === 'none' ? '' : classRelation.relationTitle2,
arrowheadStyle: '', arrowheadStyle: '',
labelStyle: ['display: inline-block'], labelStyle: ['display: inline-block'],
@@ -691,46 +726,14 @@ export const getData = () => {
edges.push(edge); edges.push(edge);
} }
return { nodes, edges, other: {}, config, direction: getDirection() }; return { nodes, edges, other: {}, config, direction: this.getDirection() };
}; }
export default { public setAccTitle = setAccTitle;
setAccTitle, public getAccTitle = getAccTitle;
getAccTitle, public setAccDescription = setAccDescription;
getAccDescription, public getAccDescription = getAccDescription;
setAccDescription, public setDiagramTitle = setDiagramTitle;
getConfig: () => getConfig().class, public getDiagramTitle = getDiagramTitle;
addClass, public getConfig = () => getConfig().class;
bindFunctions, }
clear,
getClass,
getClasses,
getNotes,
addAnnotation,
addNote,
getRelations,
addRelation,
getDirection,
setDirection,
addMember,
addMembers,
cleanupLabel,
lineType,
relationType,
setClickEvent,
setCssClass,
defineClass,
setLink,
getTooltip,
setTooltip,
lookUpDomId,
setDiagramTitle,
getDiagramTitle,
setClassLabel,
addNamespace,
addClassesToNamespace,
getNamespace,
getNamespaces,
setCssStyle,
getData,
};

View File

@@ -1,9 +1,11 @@
import { parser } from './parser/classDiagram.jison'; import { parser } from './parser/classDiagram.jison';
import classDb from './classDb.js'; import { ClassDB } from './classDb.js';
describe('class diagram, ', function () { describe('class diagram, ', function () {
describe('when parsing data from a classDiagram it', function () { describe('when parsing data from a classDiagram it', function () {
let classDb;
beforeEach(function () { beforeEach(function () {
classDb = new ClassDB();
parser.yy = classDb; parser.yy = classDb;
parser.yy.clear(); parser.yy.clear();
}); });

View File

@@ -1,13 +1,15 @@
import type { DiagramDefinition } from '../../diagram-api/types.js'; import type { DiagramDefinition } from '../../diagram-api/types.js';
// @ts-ignore: JISON doesn't support types // @ts-ignore: JISON doesn't support types
import parser from './parser/classDiagram.jison'; import parser from './parser/classDiagram.jison';
import db from './classDb.js'; import { ClassDB } from './classDb.js';
import styles from './styles.js'; import styles from './styles.js';
import renderer from './classRenderer-v3-unified.js'; import renderer from './classRenderer-v3-unified.js';
export const diagram: DiagramDefinition = { export const diagram: DiagramDefinition = {
parser, parser,
db, get db() {
return new ClassDB();
},
renderer, renderer,
styles, styles,
init: (cnf) => { init: (cnf) => {
@@ -15,6 +17,5 @@ export const diagram: DiagramDefinition = {
cnf.class = {}; cnf.class = {};
} }
cnf.class.arrowMarkerAbsolute = cnf.arrowMarkerAbsolute; cnf.class.arrowMarkerAbsolute = cnf.arrowMarkerAbsolute;
db.clear();
}, },
}; };

View File

@@ -1,6 +1,7 @@
/* eslint-disable @typescript-eslint/unbound-method -- Broken for Vitest mocks, see https://github.com/vitest-dev/eslint-plugin-vitest/pull/286 */
// @ts-expect-error Jison doesn't export types // @ts-expect-error Jison doesn't export types
import { parser } from './parser/classDiagram.jison'; import { parser } from './parser/classDiagram.jison';
import classDb from './classDb.js'; import { ClassDB } from './classDb.js';
import { vi, describe, it, expect } from 'vitest'; import { vi, describe, it, expect } from 'vitest';
import type { ClassMap, NamespaceNode } from './classTypes.js'; import type { ClassMap, NamespaceNode } from './classTypes.js';
const spyOn = vi.spyOn; const spyOn = vi.spyOn;
@@ -10,8 +11,9 @@ const abstractCssStyle = 'font-style:italic;';
describe('given a basic class diagram, ', function () { describe('given a basic class diagram, ', function () {
describe('when parsing class definition', function () { describe('when parsing class definition', function () {
let classDb: ClassDB;
beforeEach(function () { beforeEach(function () {
classDb.clear(); classDb = new ClassDB();
parser.yy = classDb; parser.yy = classDb;
}); });
it('should handle classes within namespaces', () => { it('should handle classes within namespaces', () => {
@@ -564,8 +566,9 @@ class C13["With Città foreign language"]
}); });
describe('when parsing class defined in brackets', function () { describe('when parsing class defined in brackets', function () {
let classDb: ClassDB;
beforeEach(function () { beforeEach(function () {
classDb.clear(); classDb = new ClassDB();
parser.yy = classDb; parser.yy = classDb;
}); });
@@ -656,8 +659,9 @@ class C13["With Città foreign language"]
}); });
describe('when parsing comments', function () { describe('when parsing comments', function () {
let classDb: ClassDB;
beforeEach(function () { beforeEach(function () {
classDb.clear(); classDb = new ClassDB();
parser.yy = classDb; parser.yy = classDb;
}); });
@@ -746,8 +750,9 @@ foo()
}); });
describe('when parsing click statements', function () { describe('when parsing click statements', function () {
let classDb: ClassDB;
beforeEach(function () { beforeEach(function () {
classDb.clear(); classDb = new ClassDB();
parser.yy = classDb; parser.yy = classDb;
}); });
it('should handle href link', function () { it('should handle href link', function () {
@@ -857,8 +862,9 @@ foo()
}); });
describe('when parsing annotations', function () { describe('when parsing annotations', function () {
let classDb: ClassDB;
beforeEach(function () { beforeEach(function () {
classDb.clear(); classDb = new ClassDB();
parser.yy = classDb; parser.yy = classDb;
}); });
@@ -921,8 +927,9 @@ foo()
describe('given a class diagram with members and methods ', function () { describe('given a class diagram with members and methods ', function () {
describe('when parsing members', function () { describe('when parsing members', function () {
let classDb: ClassDB;
beforeEach(function () { beforeEach(function () {
classDb.clear(); classDb = new ClassDB();
parser.yy = classDb; parser.yy = classDb;
}); });
@@ -980,8 +987,9 @@ describe('given a class diagram with members and methods ', function () {
}); });
describe('when parsing method definition', function () { describe('when parsing method definition', function () {
let classDb: ClassDB;
beforeEach(function () { beforeEach(function () {
classDb.clear(); classDb = new ClassDB();
parser.yy = classDb; parser.yy = classDb;
}); });
@@ -1067,8 +1075,9 @@ describe('given a class diagram with members and methods ', function () {
describe('given a class diagram with generics, ', function () { describe('given a class diagram with generics, ', function () {
describe('when parsing valid generic classes', function () { describe('when parsing valid generic classes', function () {
let classDb: ClassDB;
beforeEach(function () { beforeEach(function () {
classDb.clear(); classDb = new ClassDB();
parser.yy = classDb; parser.yy = classDb;
}); });
@@ -1180,8 +1189,9 @@ namespace space {
describe('given a class diagram with relationships, ', function () { describe('given a class diagram with relationships, ', function () {
describe('when parsing basic relationships', function () { describe('when parsing basic relationships', function () {
let classDb: ClassDB;
beforeEach(function () { beforeEach(function () {
classDb.clear(); classDb = new ClassDB();
parser.yy = classDb; parser.yy = classDb;
}); });
@@ -1714,7 +1724,9 @@ class Class2
}); });
describe('when parsing classDiagram with text labels', () => { describe('when parsing classDiagram with text labels', () => {
let classDb: ClassDB;
beforeEach(function () { beforeEach(function () {
classDb = new ClassDB();
parser.yy = classDb; parser.yy = classDb;
parser.yy.clear(); parser.yy.clear();
}); });
@@ -1897,3 +1909,40 @@ class C13["With Città foreign language"]
}); });
}); });
}); });
describe('class db class', () => {
let classDb: ClassDB;
beforeEach(() => {
classDb = new ClassDB();
});
// This is to ensure that functions used in class JISON are exposed as function from ClassDB
it('should have functions used in class JISON as own property', () => {
const functionsUsedInParser = [
'addRelation',
'cleanupLabel',
'setAccTitle',
'setAccDescription',
'addClassesToNamespace',
'addNamespace',
'setCssClass',
'addMembers',
'addClass',
'setClassLabel',
'addAnnotation',
'addMember',
'addNote',
'defineClass',
'setDirection',
'relationType',
'lineType',
'setClickEvent',
'setTooltip',
'setLink',
'setCssStyle',
] as const satisfies (keyof ClassDB)[];
for (const fun of functionsUsedInParser) {
expect(Object.hasOwn(classDb, fun)).toBe(true);
}
});
});

View File

@@ -1,13 +1,15 @@
import type { DiagramDefinition } from '../../diagram-api/types.js'; import type { DiagramDefinition } from '../../diagram-api/types.js';
// @ts-ignore: JISON doesn't support types // @ts-ignore: JISON doesn't support types
import parser from './parser/classDiagram.jison'; import parser from './parser/classDiagram.jison';
import db from './classDb.js'; import { ClassDB } from './classDb.js';
import styles from './styles.js'; import styles from './styles.js';
import renderer from './classRenderer-v3-unified.js'; import renderer from './classRenderer-v3-unified.js';
export const diagram: DiagramDefinition = { export const diagram: DiagramDefinition = {
parser, parser,
db, get db() {
return new ClassDB();
},
renderer, renderer,
styles, styles,
init: (cnf) => { init: (cnf) => {
@@ -15,6 +17,5 @@ export const diagram: DiagramDefinition = {
cnf.class = {}; cnf.class = {};
} }
cnf.class.arrowMarkerAbsolute = cnf.arrowMarkerAbsolute; cnf.class.arrowMarkerAbsolute = cnf.arrowMarkerAbsolute;
db.clear();
}, },
}; };

View File

@@ -1,8 +1,10 @@
import { parser } from './classDiagram.jison'; import { parser } from './classDiagram.jison';
import classDb from '../classDb.js'; import { ClassDB } from '../classDb.js';
describe('class diagram', function () { describe('class diagram', function () {
let classDb;
beforeEach(function () { beforeEach(function () {
classDb = new ClassDB();
parser.yy = classDb; parser.yy = classDb;
parser.yy.clear(); parser.yy.clear();
}); });

View File

@@ -1,4 +1,4 @@
import stateDb from '../stateDb.js'; import { StateDB } from '../stateDb.js';
import stateDiagram from './stateDiagram.jison'; import stateDiagram from './stateDiagram.jison';
import { setConfig } from '../../../config.js'; import { setConfig } from '../../../config.js';
@@ -7,7 +7,9 @@ setConfig({
}); });
describe('state parser can parse...', () => { describe('state parser can parse...', () => {
let stateDb;
beforeEach(function () { beforeEach(function () {
stateDb = new StateDB();
stateDiagram.parser.yy = stateDb; stateDiagram.parser.yy = stateDb;
stateDiagram.parser.yy.clear(); stateDiagram.parser.yy.clear();
}); });

View File

@@ -1,4 +1,4 @@
import stateDb from '../stateDb.js'; import { StateDB } from '../stateDb.js';
import stateDiagram from './stateDiagram.jison'; import stateDiagram from './stateDiagram.jison';
import { setConfig } from '../../../config.js'; import { setConfig } from '../../../config.js';
@@ -7,7 +7,9 @@ setConfig({
}); });
describe('ClassDefs and classes when parsing a State diagram', () => { describe('ClassDefs and classes when parsing a State diagram', () => {
let stateDb;
beforeEach(function () { beforeEach(function () {
stateDb = new StateDB();
stateDiagram.parser.yy = stateDb; stateDiagram.parser.yy = stateDb;
stateDiagram.parser.yy.clear(); stateDiagram.parser.yy.clear();
}); });

View File

@@ -1,6 +1,6 @@
import { line, curveBasis } from 'd3'; import { line, curveBasis } from 'd3';
import idCache from './id-cache.js'; import idCache from './id-cache.js';
import stateDb from './stateDb.js'; import { StateDB } from './stateDb.js';
import utils from '../../utils.js'; import utils from '../../utils.js';
import common from '../common/common.js'; import common from '../common/common.js';
import { getConfig } from '../../diagram-api/diagramAPI.js'; import { getConfig } from '../../diagram-api/diagramAPI.js';
@@ -414,13 +414,13 @@ let edgeCount = 0;
export const drawEdge = function (elem, path, relation) { export const drawEdge = function (elem, path, relation) {
const getRelationType = function (type) { const getRelationType = function (type) {
switch (type) { switch (type) {
case stateDb.relationType.AGGREGATION: case StateDB.relationType.AGGREGATION:
return 'aggregation'; return 'aggregation';
case stateDb.relationType.EXTENSION: case StateDB.relationType.EXTENSION:
return 'extension'; return 'extension';
case stateDb.relationType.COMPOSITION: case StateDB.relationType.COMPOSITION:
return 'composition'; return 'composition';
case stateDb.relationType.DEPENDENCY: case StateDB.relationType.DEPENDENCY:
return 'dependency'; return 'dependency';
} }
}; };
@@ -459,7 +459,7 @@ export const drawEdge = function (elem, path, relation) {
svgPath.attr( svgPath.attr(
'marker-end', 'marker-end',
'url(' + url + '#' + getRelationType(stateDb.relationType.DEPENDENCY) + 'End' + ')' 'url(' + url + '#' + getRelationType(StateDB.relationType.DEPENDENCY) + 'End' + ')'
); );
if (relation.title !== undefined) { if (relation.title !== undefined) {

View File

@@ -1,28 +1,28 @@
import { getConfig } from '../../diagram-api/diagramAPI.js';
import { log } from '../../logger.js'; import { log } from '../../logger.js';
import { generateId } from '../../utils.js'; import { generateId } from '../../utils.js';
import common from '../common/common.js'; import common from '../common/common.js';
import { getConfig } from '../../diagram-api/diagramAPI.js';
import { import {
setAccTitle,
getAccTitle,
getAccDescription,
setAccDescription,
clear as commonClear, clear as commonClear,
setDiagramTitle, getAccDescription,
getAccTitle,
getDiagramTitle, getDiagramTitle,
setAccDescription,
setAccTitle,
setDiagramTitle,
} from '../common/commonDb.js'; } from '../common/commonDb.js';
import { dataFetcher, reset as resetDataFetching } from './dataFetcher.js'; import { dataFetcher, reset as resetDataFetching } from './dataFetcher.js';
import { getDir } from './stateRenderer-v3-unified.js'; import { getDir } from './stateRenderer-v3-unified.js';
import { import {
DEFAULT_DIAGRAM_DIRECTION, DEFAULT_DIAGRAM_DIRECTION,
STMT_STATE,
STMT_RELATION,
STMT_CLASSDEF,
STMT_STYLEDEF,
STMT_APPLYCLASS,
DEFAULT_STATE_TYPE, DEFAULT_STATE_TYPE,
DIVIDER_TYPE, DIVIDER_TYPE,
STMT_APPLYCLASS,
STMT_CLASSDEF,
STMT_RELATION,
STMT_STATE,
STMT_STYLEDEF,
} from './stateCommon.js'; } from './stateCommon.js';
const START_NODE = '[*]'; const START_NODE = '[*]';
@@ -46,15 +46,6 @@ function newClassesList() {
return new Map(); return new Map();
} }
let nodes = [];
let edges = [];
let direction = DEFAULT_DIAGRAM_DIRECTION;
let rootDoc = [];
let classes = newClassesList(); // style classes defined by a classDef
// --------------------------------------
const newDoc = () => { const newDoc = () => {
return { return {
/** @type {{ id1: string, id2: string, relationTitle: string }[]} */ /** @type {{ id1: string, id2: string, relationTitle: string }[]} */
@@ -63,40 +54,98 @@ const newDoc = () => {
documents: {}, documents: {},
}; };
}; };
let documents = {
const clone = (o) => JSON.parse(JSON.stringify(o));
export class StateDB {
constructor() {
this.clear();
// Needed for JISON since it only supports direct properties
this.setRootDoc = this.setRootDoc.bind(this);
this.getDividerId = this.getDividerId.bind(this);
this.setDirection = this.setDirection.bind(this);
this.trimColon = this.trimColon.bind(this);
}
/**
* @private
* @type {Array}
*/
nodes = [];
/**
* @private
* @type {Array}
*/
edges = [];
/**
* @private
* @type {string}
*/
direction = DEFAULT_DIAGRAM_DIRECTION;
/**
* @private
* @type {Array}
*/
rootDoc = [];
/**
* @private
* @type {Map<string, any>}
*/
classes = newClassesList(); // style classes defined by a classDef
/**
* @private
* @type {Object}
*/
documents = {
root: newDoc(), root: newDoc(),
}; };
let currentDocument = documents.root; /**
let startEndCount = 0; * @private
let dividerCnt = 0; * @type {Object}
*/
currentDocument = this.documents.root;
/**
* @private
* @type {number}
*/
startEndCount = 0;
/**
* @private
* @type {number}
*/
dividerCnt = 0;
export const lineType = { static relationType = {
LINE: 0,
DOTTED_LINE: 1,
};
export const relationType = {
AGGREGATION: 0, AGGREGATION: 0,
EXTENSION: 1, EXTENSION: 1,
COMPOSITION: 2, COMPOSITION: 2,
DEPENDENCY: 3, DEPENDENCY: 3,
}; };
const clone = (o) => JSON.parse(JSON.stringify(o)); setRootDoc(o) {
const setRootDoc = (o) => {
log.info('Setting root doc', o); log.info('Setting root doc', o);
// rootDoc = { id: 'root', doc: o }; // rootDoc = { id: 'root', doc: o };
rootDoc = o; this.rootDoc = o;
}; }
const getRootDoc = () => rootDoc; getRootDoc() {
return this.rootDoc;
}
const docTranslator = (parent, node, first) => { /**
* @private
* @param {Object} parent
* @param {Object} node
* @param {boolean} first
*/
docTranslator(parent, node, first) {
if (node.stmt === STMT_RELATION) { if (node.stmt === STMT_RELATION) {
docTranslator(parent, node.state1, true); this.docTranslator(parent, node.state1, true);
docTranslator(parent, node.state2, false); this.docTranslator(parent, node.state2, false);
} else { } else {
if (node.stmt === STMT_STATE) { if (node.stmt === STMT_STATE) {
if (node.id === '[*]') { if (node.id === '[*]') {
@@ -115,7 +164,6 @@ const docTranslator = (parent, node, first) => {
let i; let i;
for (i = 0; i < node.doc.length; i++) { for (i = 0; i < node.doc.length; i++) {
if (node.doc[i].type === DIVIDER_TYPE) { if (node.doc[i].type === DIVIDER_TYPE) {
// debugger;
const newNode = clone(node.doc[i]); const newNode = clone(node.doc[i]);
newNode.doc = clone(currentDoc); newNode.doc = clone(currentDoc);
doc.push(newNode); doc.push(newNode);
@@ -137,15 +185,15 @@ const docTranslator = (parent, node, first) => {
node.doc = doc; node.doc = doc;
} }
node.doc.forEach((docNode) => docTranslator(node, docNode, true)); node.doc.forEach((docNode) => this.docTranslator(node, docNode, true));
} }
} }
}; }
const getRootDocV2 = () => { getRootDocV2() {
docTranslator({ id: 'root' }, { id: 'root', doc: rootDoc }, true); this.docTranslator({ id: 'root' }, { id: 'root', doc: this.rootDoc }, true);
return { id: 'root', doc: rootDoc }; return { id: 'root', doc: this.rootDoc };
// Here // Here
}; }
/** /**
* Convert all of the statements (stmts) that were parsed into states and relationships. * Convert all of the statements (stmts) that were parsed into states and relationships.
@@ -158,7 +206,7 @@ const getRootDocV2 = () => {
* *
* @param _doc * @param _doc
*/ */
const extract = (_doc) => { extract(_doc) {
// const res = { states: [], relations: [] }; // const res = { states: [], relations: [] };
let doc; let doc;
if (_doc.doc) { if (_doc.doc) {
@@ -171,7 +219,7 @@ const extract = (_doc) => {
// doc = root; // doc = root;
// } // }
log.info(doc); log.info(doc);
clear(true); this.clear(true);
log.info('Extract initial document:', doc); log.info('Extract initial document:', doc);
@@ -179,7 +227,7 @@ const extract = (_doc) => {
log.warn('Statement', item.stmt); log.warn('Statement', item.stmt);
switch (item.stmt) { switch (item.stmt) {
case STMT_STATE: case STMT_STATE:
addState( this.addState(
item.id.trim(), item.id.trim(),
item.type, item.type,
item.doc, item.doc,
@@ -191,38 +239,49 @@ const extract = (_doc) => {
); );
break; break;
case STMT_RELATION: case STMT_RELATION:
addRelation(item.state1, item.state2, item.description); this.addRelation(item.state1, item.state2, item.description);
break; break;
case STMT_CLASSDEF: case STMT_CLASSDEF:
addStyleClass(item.id.trim(), item.classes); this.addStyleClass(item.id.trim(), item.classes);
break; break;
case STMT_STYLEDEF: case STMT_STYLEDEF:
{ {
const ids = item.id.trim().split(','); const ids = item.id.trim().split(',');
const styles = item.styleClass.split(','); const styles = item.styleClass.split(',');
ids.forEach((id) => { ids.forEach((id) => {
let foundState = getState(id); let foundState = this.getState(id);
if (foundState === undefined) { if (foundState === undefined) {
const trimmedId = id.trim(); const trimmedId = id.trim();
addState(trimmedId); this.addState(trimmedId);
foundState = getState(trimmedId); foundState = this.getState(trimmedId);
} }
foundState.styles = styles.map((s) => s.replace(/;/g, '')?.trim()); foundState.styles = styles.map((s) => s.replace(/;/g, '')?.trim());
}); });
} }
break; break;
case STMT_APPLYCLASS: case STMT_APPLYCLASS:
setCssClass(item.id.trim(), item.styleClass); this.setCssClass(item.id.trim(), item.styleClass);
break; break;
} }
}); });
const diagramStates = getStates(); const diagramStates = this.getStates();
const config = getConfig(); const config = getConfig();
const look = config.look; const look = config.look;
resetDataFetching(); resetDataFetching();
dataFetcher(undefined, getRootDocV2(), diagramStates, nodes, edges, true, look, classes, config); dataFetcher(
nodes.forEach((node) => { undefined,
this.getRootDocV2(),
diagramStates,
this.nodes,
this.edges,
true,
look,
this.classes,
config
);
this.nodes.forEach((node) => {
if (Array.isArray(node.label)) { if (Array.isArray(node.label)) {
// add the rest as description // add the rest as description
node.description = node.label.slice(1); node.description = node.label.slice(1);
@@ -237,7 +296,7 @@ const extract = (_doc) => {
node.label = node.label[0]; node.label = node.label[0];
} }
}); });
}; }
/** /**
* Function called by parser when a node definition has been found. * Function called by parser when a node definition has been found.
@@ -251,7 +310,7 @@ const extract = (_doc) => {
* @param {null | string | string[]} styles - styles to apply to this state. Can be a string (1 style) or an array of styles. If it's just 1 style, convert it to an array of that 1 style. * @param {null | string | string[]} styles - styles to apply to this state. Can be a string (1 style) or an array of styles. If it's just 1 style, convert it to an array of that 1 style.
* @param {null | string | string[]} textStyles - text styles to apply to this state. Can be a string (1 text test) or an array of text styles. If it's just 1 text style, convert it to an array of that 1 text style. * @param {null | string | string[]} textStyles - text styles to apply to this state. Can be a string (1 text test) or an array of text styles. If it's just 1 text style, convert it to an array of that 1 text style.
*/ */
export const addState = function ( addState(
id, id,
type = DEFAULT_STATE_TYPE, type = DEFAULT_STATE_TYPE,
doc = null, doc = null,
@@ -263,9 +322,9 @@ export const addState = function (
) { ) {
const trimmedId = id?.trim(); const trimmedId = id?.trim();
// add the state if needed // add the state if needed
if (!currentDocument.states.has(trimmedId)) { if (!this.currentDocument.states.has(trimmedId)) {
log.info('Adding state ', trimmedId, descr); log.info('Adding state ', trimmedId, descr);
currentDocument.states.set(trimmedId, { this.currentDocument.states.set(trimmedId, {
id: trimmedId, id: trimmedId,
descriptions: [], descriptions: [],
type, type,
@@ -276,27 +335,27 @@ export const addState = function (
textStyles: [], textStyles: [],
}); });
} else { } else {
if (!currentDocument.states.get(trimmedId).doc) { if (!this.currentDocument.states.get(trimmedId).doc) {
currentDocument.states.get(trimmedId).doc = doc; this.currentDocument.states.get(trimmedId).doc = doc;
} }
if (!currentDocument.states.get(trimmedId).type) { if (!this.currentDocument.states.get(trimmedId).type) {
currentDocument.states.get(trimmedId).type = type; this.currentDocument.states.get(trimmedId).type = type;
} }
} }
if (descr) { if (descr) {
log.info('Setting state description', trimmedId, descr); log.info('Setting state description', trimmedId, descr);
if (typeof descr === 'string') { if (typeof descr === 'string') {
addDescription(trimmedId, descr.trim()); this.addDescription(trimmedId, descr.trim());
} }
if (typeof descr === 'object') { if (typeof descr === 'object') {
descr.forEach((des) => addDescription(trimmedId, des.trim())); descr.forEach((des) => this.addDescription(trimmedId, des.trim()));
} }
} }
if (note) { if (note) {
const doc2 = currentDocument.states.get(trimmedId); const doc2 = this.currentDocument.states.get(trimmedId);
doc2.note = note; doc2.note = note;
doc2.note.text = common.sanitizeText(doc2.note.text, getConfig()); doc2.note.text = common.sanitizeText(doc2.note.text, getConfig());
} }
@@ -304,51 +363,50 @@ export const addState = function (
if (classes) { if (classes) {
log.info('Setting state classes', trimmedId, classes); log.info('Setting state classes', trimmedId, classes);
const classesList = typeof classes === 'string' ? [classes] : classes; const classesList = typeof classes === 'string' ? [classes] : classes;
classesList.forEach((cssClass) => setCssClass(trimmedId, cssClass.trim())); classesList.forEach((cssClass) => this.setCssClass(trimmedId, cssClass.trim()));
} }
if (styles) { if (styles) {
log.info('Setting state styles', trimmedId, styles); log.info('Setting state styles', trimmedId, styles);
const stylesList = typeof styles === 'string' ? [styles] : styles; const stylesList = typeof styles === 'string' ? [styles] : styles;
stylesList.forEach((style) => setStyle(trimmedId, style.trim())); stylesList.forEach((style) => this.setStyle(trimmedId, style.trim()));
} }
if (textStyles) { if (textStyles) {
log.info('Setting state styles', trimmedId, styles); log.info('Setting state styles', trimmedId, styles);
const textStylesList = typeof textStyles === 'string' ? [textStyles] : textStyles; const textStylesList = typeof textStyles === 'string' ? [textStyles] : textStyles;
textStylesList.forEach((textStyle) => setTextStyle(trimmedId, textStyle.trim())); textStylesList.forEach((textStyle) => this.setTextStyle(trimmedId, textStyle.trim()));
}
} }
};
export const clear = function (saveCommon) { clear(saveCommon) {
nodes = []; this.nodes = [];
edges = []; this.edges = [];
documents = { this.documents = {
root: newDoc(), root: newDoc(),
}; };
currentDocument = documents.root; this.currentDocument = this.documents.root;
// number of start and end nodes; used to construct ids // number of start and end nodes; used to construct ids
startEndCount = 0; this.startEndCount = 0;
classes = newClassesList(); this.classes = newClassesList();
if (!saveCommon) { if (!saveCommon) {
commonClear(); commonClear();
} }
}; }
export const getState = function (id) { getState(id) {
return currentDocument.states.get(id); return this.currentDocument.states.get(id);
}; }
getStates() {
export const getStates = function () { return this.currentDocument.states;
return currentDocument.states; }
}; logDocuments() {
export const logDocuments = function () { log.info('Documents = ', this.documents);
log.info('Documents = ', documents); }
}; getRelations() {
export const getRelations = function () { return this.currentDocument.relations;
return currentDocument.relations; }
};
/** /**
* If the id is a start node ( [*] ), then return a new id constructed from * If the id is a start node ( [*] ), then return a new id constructed from
@@ -357,12 +415,13 @@ export const getRelations = function () {
* *
* @param {string} id * @param {string} id
* @returns {string} - the id (original or constructed) * @returns {string} - the id (original or constructed)
* @private
*/ */
function startIdIfNeeded(id = '') { startIdIfNeeded(id = '') {
let fixedId = id; let fixedId = id;
if (id === START_NODE) { if (id === START_NODE) {
startEndCount++; this.startEndCount++;
fixedId = `${START_TYPE}${startEndCount}`; fixedId = `${START_TYPE}${this.startEndCount}`;
} }
return fixedId; return fixedId;
} }
@@ -374,8 +433,9 @@ function startIdIfNeeded(id = '') {
* @param {string} id * @param {string} id
* @param {string} type * @param {string} type
* @returns {string} - the type that should be used * @returns {string} - the type that should be used
* @private
*/ */
function startTypeIfNeeded(id = '', type = DEFAULT_STATE_TYPE) { startTypeIfNeeded(id = '', type = DEFAULT_STATE_TYPE) {
return id === START_NODE ? START_TYPE : type; return id === START_NODE ? START_TYPE : type;
} }
@@ -386,12 +446,13 @@ function startTypeIfNeeded(id = '', type = DEFAULT_STATE_TYPE) {
* *
* @param {string} id * @param {string} id
* @returns {string} - the id (original or constructed) * @returns {string} - the id (original or constructed)
* @private
*/ */
function endIdIfNeeded(id = '') { endIdIfNeeded(id = '') {
let fixedId = id; let fixedId = id;
if (id === END_NODE) { if (id === END_NODE) {
startEndCount++; this.startEndCount++;
fixedId = `${END_TYPE}${startEndCount}`; fixedId = `${END_TYPE}${this.startEndCount}`;
} }
return fixedId; return fixedId;
} }
@@ -403,8 +464,9 @@ function endIdIfNeeded(id = '') {
* @param {string} id * @param {string} id
* @param {string} type * @param {string} type
* @returns {string} - the type that should be used * @returns {string} - the type that should be used
* @private
*/ */
function endTypeIfNeeded(id = '', type = DEFAULT_STATE_TYPE) { endTypeIfNeeded(id = '', type = DEFAULT_STATE_TYPE) {
return id === END_NODE ? END_TYPE : type; return id === END_NODE ? END_TYPE : type;
} }
@@ -414,13 +476,13 @@ function endTypeIfNeeded(id = '', type = DEFAULT_STATE_TYPE) {
* @param item2 * @param item2
* @param relationTitle * @param relationTitle
*/ */
export function addRelationObjs(item1, item2, relationTitle) { addRelationObjs(item1, item2, relationTitle) {
let id1 = startIdIfNeeded(item1.id.trim()); let id1 = this.startIdIfNeeded(item1.id.trim());
let type1 = startTypeIfNeeded(item1.id.trim(), item1.type); let type1 = this.startTypeIfNeeded(item1.id.trim(), item1.type);
let id2 = startIdIfNeeded(item2.id.trim()); let id2 = this.startIdIfNeeded(item2.id.trim());
let type2 = startTypeIfNeeded(item2.id.trim(), item2.type); let type2 = this.startTypeIfNeeded(item2.id.trim(), item2.type);
addState( this.addState(
id1, id1,
type1, type1,
item1.doc, item1.doc,
@@ -430,7 +492,7 @@ export function addRelationObjs(item1, item2, relationTitle) {
item1.styles, item1.styles,
item1.textStyles item1.textStyles
); );
addState( this.addState(
id2, id2,
type2, type2,
item2.doc, item2.doc,
@@ -441,7 +503,7 @@ export function addRelationObjs(item1, item2, relationTitle) {
item2.textStyles item2.textStyles
); );
currentDocument.relations.push({ this.currentDocument.relations.push({
id1, id1,
id2, id2,
relationTitle: common.sanitizeText(relationTitle, getConfig()), relationTitle: common.sanitizeText(relationTitle, getConfig()),
@@ -455,43 +517,43 @@ export function addRelationObjs(item1, item2, relationTitle) {
* @param {string | object} item2 * @param {string | object} item2
* @param {string} title * @param {string} title
*/ */
export const addRelation = function (item1, item2, title) { addRelation(item1, item2, title) {
if (typeof item1 === 'object') { if (typeof item1 === 'object') {
addRelationObjs(item1, item2, title); this.addRelationObjs(item1, item2, title);
} else { } else {
const id1 = startIdIfNeeded(item1.trim()); const id1 = this.startIdIfNeeded(item1.trim());
const type1 = startTypeIfNeeded(item1); const type1 = this.startTypeIfNeeded(item1);
const id2 = endIdIfNeeded(item2.trim()); const id2 = this.endIdIfNeeded(item2.trim());
const type2 = endTypeIfNeeded(item2); const type2 = this.endTypeIfNeeded(item2);
addState(id1, type1); this.addState(id1, type1);
addState(id2, type2); this.addState(id2, type2);
currentDocument.relations.push({ this.currentDocument.relations.push({
id1, id1,
id2, id2,
title: common.sanitizeText(title, getConfig()), title: common.sanitizeText(title, getConfig()),
}); });
} }
}; }
export const addDescription = function (id, descr) { addDescription(id, descr) {
const theState = currentDocument.states.get(id); const theState = this.currentDocument.states.get(id);
const _descr = descr.startsWith(':') ? descr.replace(':', '').trim() : descr; const _descr = descr.startsWith(':') ? descr.replace(':', '').trim() : descr;
theState.descriptions.push(common.sanitizeText(_descr, getConfig())); theState.descriptions.push(common.sanitizeText(_descr, getConfig()));
}; }
export const cleanupLabel = function (label) { cleanupLabel(label) {
if (label.substring(0, 1) === ':') { if (label.substring(0, 1) === ':') {
return label.substr(2).trim(); return label.substr(2).trim();
} else { } else {
return label.trim(); return label.trim();
} }
}; }
const getDividerId = () => { getDividerId() {
dividerCnt++; this.dividerCnt++;
return 'divider-id-' + dividerCnt; return 'divider-id-' + this.dividerCnt;
}; }
/** /**
* Called when the parser comes across a (style) class definition * Called when the parser comes across a (style) class definition
@@ -500,12 +562,12 @@ const getDividerId = () => {
* @param {string} id - the id of this (style) class * @param {string} id - the id of this (style) class
* @param {string | null} styleAttributes - the string with 1 or more style attributes (each separated by a comma) * @param {string | null} styleAttributes - the string with 1 or more style attributes (each separated by a comma)
*/ */
export const addStyleClass = function (id, styleAttributes = '') { addStyleClass(id, styleAttributes = '') {
// create a new style class object with this id // create a new style class object with this id
if (!classes.has(id)) { if (!this.classes.has(id)) {
classes.set(id, { id: id, styles: [], textStyles: [] }); // This is a classDef this.classes.set(id, { id: id, styles: [], textStyles: [] }); // This is a classDef
} }
const foundClass = classes.get(id); const foundClass = this.classes.get(id);
if (styleAttributes !== undefined && styleAttributes !== null) { if (styleAttributes !== undefined && styleAttributes !== null) {
styleAttributes.split(STYLECLASS_SEP).forEach((attrib) => { styleAttributes.split(STYLECLASS_SEP).forEach((attrib) => {
// remove any trailing ; // remove any trailing ;
@@ -520,15 +582,15 @@ export const addStyleClass = function (id, styleAttributes = '') {
foundClass.styles.push(fixedAttrib); foundClass.styles.push(fixedAttrib);
}); });
} }
}; }
/** /**
* Return all of the style classes * Return all of the style classes
* @returns {{} | any | classes} * @returns {{} | any | classes}
*/ */
export const getClasses = function () { getClasses() {
return classes; return this.classes;
}; }
/** /**
* Add a (style) class or css class to a state with the given id. * Add a (style) class or css class to a state with the given id.
@@ -538,17 +600,17 @@ export const getClasses = function () {
* @param {string | string[]} itemIds The id or a list of ids of the item(s) to apply the css class to * @param {string | string[]} itemIds The id or a list of ids of the item(s) to apply the css class to
* @param {string} cssClassName CSS class name * @param {string} cssClassName CSS class name
*/ */
export const setCssClass = function (itemIds, cssClassName) { setCssClass(itemIds, cssClassName) {
itemIds.split(',').forEach(function (id) { itemIds.split(',').forEach((id) => {
let foundState = getState(id); let foundState = this.getState(id);
if (foundState === undefined) { if (foundState === undefined) {
const trimmedId = id.trim(); const trimmedId = id.trim();
addState(trimmedId); this.addState(trimmedId);
foundState = getState(trimmedId); foundState = this.getState(trimmedId);
} }
foundState.classes.push(cssClassName); foundState.classes.push(cssClassName);
}); });
}; }
/** /**
* Add a style to a state with the given id. * Add a style to a state with the given id.
@@ -560,12 +622,12 @@ export const setCssClass = function (itemIds, cssClassName) {
* @param itemId The id of item to apply the style to * @param itemId The id of item to apply the style to
* @param styleText - the text of the attributes for the style * @param styleText - the text of the attributes for the style
*/ */
export const setStyle = function (itemId, styleText) { setStyle(itemId, styleText) {
const item = getState(itemId); const item = this.getState(itemId);
if (item !== undefined) { if (item !== undefined) {
item.styles.push(styleText); item.styles.push(styleText);
} }
}; }
/** /**
* Add a text style to a state with the given id * Add a text style to a state with the given id
@@ -573,54 +635,42 @@ export const setStyle = function (itemId, styleText) {
* @param itemId The id of item to apply the css class to * @param itemId The id of item to apply the css class to
* @param cssClassName CSS class name * @param cssClassName CSS class name
*/ */
export const setTextStyle = function (itemId, cssClassName) { setTextStyle(itemId, cssClassName) {
const item = getState(itemId); const item = this.getState(itemId);
if (item !== undefined) { if (item !== undefined) {
item.textStyles.push(cssClassName); item.textStyles.push(cssClassName);
} }
}; }
const getDirection = () => direction; getDirection() {
const setDirection = (dir) => { return this.direction;
direction = dir; }
}; setDirection(dir) {
this.direction = dir;
}
const trimColon = (str) => (str && str[0] === ':' ? str.substr(1).trim() : str.trim()); trimColon(str) {
return str && str[0] === ':' ? str.substr(1).trim() : str.trim();
}
export const getData = () => { getData() {
const config = getConfig(); const config = getConfig();
return { nodes, edges, other: {}, config, direction: getDir(getRootDocV2()) }; return {
nodes: this.nodes,
edges: this.edges,
other: {},
config,
direction: getDir(this.getRootDocV2()),
}; };
}
export default { getConfig() {
getConfig: () => getConfig().state, return getConfig().state;
getData, }
addState, getAccTitle = getAccTitle;
clear, setAccTitle = setAccTitle;
getState, getAccDescription = getAccDescription;
getStates, setAccDescription = setAccDescription;
getRelations, setDiagramTitle = setDiagramTitle;
getClasses, getDiagramTitle = getDiagramTitle;
getDirection, }
addRelation,
getDividerId,
setDirection,
cleanupLabel,
lineType,
relationType,
logDocuments,
getRootDoc,
setRootDoc,
getRootDocV2,
extract,
trimColon,
getAccTitle,
setAccTitle,
getAccDescription,
setAccDescription,
addStyleClass,
setCssClass,
addDescription,
setDiagramTitle,
getDiagramTitle,
};

View File

@@ -1,8 +1,9 @@
import stateDb from './stateDb.js'; import { StateDB } from './stateDb.js';
describe('State Diagram stateDb', () => { describe('State Diagram stateDb', () => {
let stateDb;
beforeEach(() => { beforeEach(() => {
stateDb.clear(); stateDb = new StateDB();
}); });
describe('addStyleClass', () => { describe('addStyleClass', () => {
@@ -20,8 +21,9 @@ describe('State Diagram stateDb', () => {
}); });
describe('addDescription to a state', () => { describe('addDescription to a state', () => {
let stateDb;
beforeEach(() => { beforeEach(() => {
stateDb.clear(); stateDb = new StateDB();
stateDb.addState('state1'); stateDb.addState('state1');
}); });
@@ -73,3 +75,25 @@ describe('State Diagram stateDb', () => {
}); });
}); });
}); });
describe('state db class', () => {
let stateDb;
beforeEach(() => {
stateDb = new StateDB();
});
// This is to ensure that functions used in state JISON are exposed as function from StateDb
it('should have functions used in flow JISON as own property', () => {
const functionsUsedInParser = [
'setRootDoc',
'trimColon',
'getDividerId',
'setAccTitle',
'setAccDescription',
'setDirection',
];
for (const fun of functionsUsedInParser) {
expect(Object.hasOwn(stateDb, fun)).toBe(true);
}
});
});

View File

@@ -1,11 +1,13 @@
import { parser } from './parser/stateDiagram.jison'; import { parser } from './parser/stateDiagram.jison';
import stateDb from './stateDb.js'; import { StateDB } from './stateDb.js';
import stateDiagram from './parser/stateDiagram.jison'; import stateDiagram from './parser/stateDiagram.jison';
describe('state diagram V2, ', function () { describe('state diagram V2, ', function () {
// TODO - these examples should be put into ./parser/stateDiagram.spec.js // TODO - these examples should be put into ./parser/stateDiagram.spec.js
describe('when parsing an info graph it', function () { describe('when parsing an info graph it', function () {
let stateDb;
beforeEach(function () { beforeEach(function () {
stateDb = new StateDB();
parser.yy = stateDb; parser.yy = stateDb;
stateDiagram.parser.yy = stateDb; stateDiagram.parser.yy = stateDb;
stateDiagram.parser.yy.clear(); stateDiagram.parser.yy.clear();

View File

@@ -1,13 +1,15 @@
import type { DiagramDefinition } from '../../diagram-api/types.js'; import type { DiagramDefinition } from '../../diagram-api/types.js';
// @ts-ignore: JISON doesn't support types // @ts-ignore: JISON doesn't support types
import parser from './parser/stateDiagram.jison'; import parser from './parser/stateDiagram.jison';
import db from './stateDb.js'; import { StateDB } from './stateDb.js';
import styles from './styles.js'; import styles from './styles.js';
import renderer from './stateRenderer-v3-unified.js'; import renderer from './stateRenderer-v3-unified.js';
export const diagram: DiagramDefinition = { export const diagram: DiagramDefinition = {
parser, parser,
db, get db() {
return new StateDB();
},
renderer, renderer,
styles, styles,
init: (cnf) => { init: (cnf) => {
@@ -15,6 +17,5 @@ export const diagram: DiagramDefinition = {
cnf.state = {}; cnf.state = {};
} }
cnf.state.arrowMarkerAbsolute = cnf.arrowMarkerAbsolute; cnf.state.arrowMarkerAbsolute = cnf.arrowMarkerAbsolute;
db.clear();
}, },
}; };

View File

@@ -1,9 +1,11 @@
import { parser } from './parser/stateDiagram.jison'; import { parser } from './parser/stateDiagram.jison';
import stateDb from './stateDb.js'; import { StateDB } from './stateDb.js';
describe('state diagram, ', function () { describe('state diagram, ', function () {
describe('when parsing an info graph it', function () { describe('when parsing an info graph it', function () {
let stateDb;
beforeEach(function () { beforeEach(function () {
stateDb = new StateDB();
parser.yy = stateDb; parser.yy = stateDb;
}); });

View File

@@ -1,13 +1,15 @@
import type { DiagramDefinition } from '../../diagram-api/types.js'; import type { DiagramDefinition } from '../../diagram-api/types.js';
// @ts-ignore: JISON doesn't support types // @ts-ignore: JISON doesn't support types
import parser from './parser/stateDiagram.jison'; import parser from './parser/stateDiagram.jison';
import db from './stateDb.js'; import { StateDB } from './stateDb.js';
import styles from './styles.js'; import styles from './styles.js';
import renderer from './stateRenderer.js'; import renderer from './stateRenderer.js';
export const diagram: DiagramDefinition = { export const diagram: DiagramDefinition = {
parser, parser,
db, get db() {
return new StateDB();
},
renderer, renderer,
styles, styles,
init: (cnf) => { init: (cnf) => {
@@ -15,6 +17,5 @@ export const diagram: DiagramDefinition = {
cnf.state = {}; cnf.state = {};
} }
cnf.state.arrowMarkerAbsolute = cnf.arrowMarkerAbsolute; cnf.state.arrowMarkerAbsolute = cnf.arrowMarkerAbsolute;
db.clear();
}, },
}; };

View File

@@ -1,4 +1,4 @@
import { beforeEach, describe, expect, it, vi } from 'vitest'; import { assert, beforeEach, describe, expect, it, vi } from 'vitest';
// ------------------------------------- // -------------------------------------
// Mocks and mocking // Mocks and mocking
@@ -69,6 +69,8 @@ import { compile, serialize } from 'stylis';
import { Diagram } from './Diagram.js'; import { Diagram } from './Diagram.js';
import { decodeEntities, encodeEntities } from './utils.js'; import { decodeEntities, encodeEntities } from './utils.js';
import { toBase64 } from './utils/base64.js'; import { toBase64 } from './utils/base64.js';
import { ClassDB } from './diagrams/class/classDb.js';
import { StateDB } from './diagrams/state/stateDb.js';
import { FlowDB } from './diagrams/flowchart/flowDb.js'; import { FlowDB } from './diagrams/flowchart/flowDb.js';
/** /**
@@ -853,40 +855,102 @@ graph TD;A--x|text including URL space|B;`
}); });
it('should not modify db when rendering different diagrams', async () => { it('should not modify db when rendering different diagrams', async () => {
const stateDiagram1 = await mermaidAPI.getDiagramFromText(
`stateDiagram
direction LR
[*] --> Still
Still --> [*]
Still --> Moving
Moving --> Still
Moving --> Crash
Crash --> [*]`
);
const stateDiagram2 = await mermaidAPI.getDiagramFromText(
`stateDiagram
direction TB
[*] --> Still
Still --> [*]
Still --> Moving
Moving --> Still
Moving --> Crash
Crash --> [*]`
);
// Since stateDiagram will return new Db object each time, we can compare the db to be different.
expect(stateDiagram1.db).not.toBe(stateDiagram2.db);
assert(stateDiagram1.db instanceof StateDB);
assert(stateDiagram2.db instanceof StateDB);
expect(stateDiagram1.db.getDirection()).not.toEqual(stateDiagram2.db.getDirection());
const flowDiagram1 = await mermaidAPI.getDiagramFromText( const flowDiagram1 = await mermaidAPI.getDiagramFromText(
`flowchart LR `flowchart LR
A -- text --> B -- text2 --> C` A -- text --> B -- text2 --> C`
); );
const flwoDiagram2 = await mermaidAPI.getDiagramFromText( const flowDiagram2 = await mermaidAPI.getDiagramFromText(
`flowchart TD `flowchart TD
A -- text --> B -- text2 --> C` A -- text --> B -- text2 --> C`
); );
// Since flowDiagram will return new Db object each time, we can compare the db to be different. // Since flowDiagram will return new Db object each time, we can compare the db to be different.
expect(flowDiagram1.db).not.toBe(flwoDiagram2.db); expect(flowDiagram1.db).not.toBe(flowDiagram2.db);
assert(flowDiagram1.db instanceof FlowDB); assert(flowDiagram1.db instanceof FlowDB);
assert(flwoDiagram2.db instanceof FlowDB); assert(flowDiagram2.db instanceof FlowDB);
expect(flowDiagram1.db.getDirection()).not.toEqual(flwoDiagram2.db.getDirection()); expect(flowDiagram1.db.getDirection()).not.toEqual(flowDiagram2.db.getDirection());
const classDiagram1 = await mermaidAPI.getDiagramFromText( const classDiagram1 = await mermaidAPI.getDiagramFromText(
`stateDiagram `classDiagram
[*] --> Still direction TB
Still --> [*] class Student {
Still --> Moving -idCard : IdCard
Moving --> Still }
Moving --> Crash class IdCard{
Crash --> [*]` -id : int
-name : string
}
class Bike{
-id : int
-name : string
}
Student "1" --o "1" IdCard : carries
Student "1" --o "1" Bike : rides`
); );
const classDiagram2 = await mermaidAPI.getDiagramFromText( const classDiagram2 = await mermaidAPI.getDiagramFromText(
`stateDiagram `classDiagram
[*] --> Still direction LR
Still --> [*] class Student {
Still --> Moving -idCard : IdCard
Moving --> Still }
Moving --> Crash class IdCard{
Crash --> [*]` -id : int
-name : string
}
class Bike{
-id : int
-name : string
}
Student "1" --o "1" IdCard : carries
Student "1" --o "1" Bike : rides`
);
// Since classDiagram will return new Db object each time, we can compare the db to be different.
expect(classDiagram1.db).not.toBe(classDiagram2.db);
assert(classDiagram1.db instanceof ClassDB);
assert(classDiagram2.db instanceof ClassDB);
expect(classDiagram1.db.getDirection()).not.toEqual(classDiagram2.db.getDirection());
const sequenceDiagram1 = await mermaidAPI.getDiagramFromText(
`sequenceDiagram
Alice->>+John: Hello John, how are you?
Alice->>+John: John, can you hear me?
John-->>-Alice: Hi Alice, I can hear you!
John-->>-Alice: I feel great!`
);
const sequenceDiagram2 = await mermaidAPI.getDiagramFromText(
`sequenceDiagram
Alice->>+John: Hello John, how are you?
Alice->>+John: John, can you hear me?
John-->>-Alice: Hi Alice, I can hear you!
John-->>-Alice: I feel great!`
); );
// Since sequenceDiagram will return same Db object each time, we can compare the db to be same. // Since sequenceDiagram will return same Db object each time, we can compare the db to be same.
expect(classDiagram1.db).toBe(classDiagram2.db); expect(sequenceDiagram1.db).toBe(sequenceDiagram2.db);
}); });
}); });