Merge branch 'develop' into sidv/examples

This commit is contained in:
Sidharth Vinod
2025-04-17 09:06:50 -07:00
committed by GitHub
73 changed files with 3690 additions and 2142 deletions

View File

@@ -78,7 +78,7 @@
"d3-sankey": "^0.12.3",
"dagre-d3-es": "7.0.11",
"dayjs": "^1.11.13",
"dompurify": "^3.2.4",
"dompurify": "^3.2.5",
"katex": "^0.16.9",
"khroma": "^2.1.0",
"lodash-es": "^4.17.21",

View File

@@ -559,6 +559,10 @@ export interface JourneyDiagramConfig extends BaseDiagramConfig {
* Margin between actors
*/
leftMargin?: number;
/**
* Maximum width of actor labels
*/
maxLabelWidth?: number;
/**
* Width of actor boxes
*/
@@ -617,6 +621,18 @@ export interface JourneyDiagramConfig extends BaseDiagramConfig {
actorColours?: string[];
sectionFills?: string[];
sectionColours?: string[];
/**
* Color of the title text in Journey Diagrams
*/
titleColor?: string;
/**
* Font family to be used for the title text in Journey Diagrams
*/
titleFontFamily?: string;
/**
* Font size to be used for the title text in Journey Diagrams
*/
titleFontSize?: string;
}
/**
* This interface was referenced by `MermaidConfig`'s JSON-Schema
@@ -935,6 +951,10 @@ export interface XYChartConfig extends BaseDiagramConfig {
* Top and bottom space from the chart title
*/
titlePadding?: number;
/**
* Should show the value corresponding to the bar within the bar
*/
showDataLabel?: boolean;
/**
* Should show the chart title
*/

View File

@@ -0,0 +1,70 @@
import { it, describe, expect } from 'vitest';
import { db } from './architectureDb.js';
import { parser } from './architectureParser.js';
const {
clear,
getDiagramTitle,
getAccTitle,
getAccDescription,
getServices,
getGroups,
getEdges,
getJunctions,
} = db;
describe('architecture diagrams', () => {
beforeEach(() => {
clear();
});
describe('architecture diagram definitions', () => {
it('should handle the architecture keyword', async () => {
const str = `architecture-beta`;
await expect(parser.parse(str)).resolves.not.toThrow();
});
it('should handle an simple radar definition', async () => {
const str = `architecture-beta
service db
`;
await expect(parser.parse(str)).resolves.not.toThrow();
});
});
describe('should handle TitleAndAccessibilities', () => {
it('should handle title on the first line', async () => {
const str = `architecture-beta title Simple Architecture Diagram`;
await expect(parser.parse(str)).resolves.not.toThrow();
expect(getDiagramTitle()).toBe('Simple Architecture Diagram');
});
it('should handle title on another line', async () => {
const str = `architecture-beta
title Simple Architecture Diagram
`;
await expect(parser.parse(str)).resolves.not.toThrow();
expect(getDiagramTitle()).toBe('Simple Architecture Diagram');
});
it('should handle accessibility title and description', async () => {
const str = `architecture-beta
accTitle: Accessibility Title
accDescr: Accessibility Description
`;
await expect(parser.parse(str)).resolves.not.toThrow();
expect(getAccTitle()).toBe('Accessibility Title');
expect(getAccDescription()).toBe('Accessibility Description');
});
it('should handle multiline accessibility description', async () => {
const str = `architecture-beta
accDescr {
Accessibility Description
}
`;
await expect(parser.parse(str)).resolves.not.toThrow();
expect(getAccDescription()).toBe('Accessibility Description');
});
});
});

View File

@@ -1,6 +1,6 @@
import type { ArchitectureDiagramConfig } from '../../config.type.js';
import DEFAULT_CONFIG from '../../defaultConfig.js';
import { getConfig } from '../../diagram-api/diagramAPI.js';
import { getConfig as commonGetConfig } from '../../config.js';
import type { D3Element } from '../../types.js';
import { ImperativeState } from '../../utils/imperativeState.js';
import {
@@ -33,6 +33,7 @@ import {
isArchitectureService,
shiftPositionByArchitectureDirectionPair,
} from './architectureTypes.js';
import { cleanAndMerge } from '../../utils.js';
const DEFAULT_ARCHITECTURE_CONFIG: Required<ArchitectureDiagramConfig> =
DEFAULT_CONFIG.architecture;
@@ -316,6 +317,14 @@ const setElementForId = (id: string, element: D3Element) => {
};
const getElementById = (id: string) => state.records.elements[id];
const getConfig = (): Required<ArchitectureDiagramConfig> => {
const config = cleanAndMerge({
...DEFAULT_ARCHITECTURE_CONFIG,
...commonGetConfig().architecture,
});
return config;
};
export const db: ArchitectureDB = {
clear,
setDiagramTitle,
@@ -324,6 +333,7 @@ export const db: ArchitectureDB = {
getAccTitle,
setAccDescription,
getAccDescription,
getConfig,
addService,
getServices,
@@ -348,9 +358,5 @@ export const db: ArchitectureDB = {
export function getConfigField<T extends keyof ArchitectureDiagramConfig>(
field: T
): Required<ArchitectureDiagramConfig>[T] {
const arch = getConfig().architecture;
if (arch?.[field]) {
return arch[field] as Required<ArchitectureDiagramConfig>[T];
}
return DEFAULT_ARCHITECTURE_CONFIG[field];
return getConfig()[field];
}

View File

@@ -500,6 +500,8 @@ function layoutArchitecture(
}
export const draw: DrawDefinition = async (text, id, _version, diagObj: Diagram) => {
// TODO: Add title support for architecture diagrams
const db = diagObj.db as ArchitectureDB;
const services = db.getServices();

View File

@@ -1,4 +1,4 @@
import type { DiagramDB } from '../../diagram-api/types.js';
import type { DiagramDBBase } from '../../diagram-api/types.js';
import type { ArchitectureDiagramConfig } from '../../config.type.js';
import type { D3Element } from '../../types.js';
import type cytoscape from 'cytoscape';
@@ -242,7 +242,7 @@ export interface ArchitectureEdge<DT = ArchitectureDirection> {
title?: string;
}
export interface ArchitectureDB extends DiagramDB {
export interface ArchitectureDB extends DiagramDBBase<ArchitectureDiagramConfig> {
clear: () => void;
addService: (service: Omit<ArchitectureService, 'edges'>) => void;
getServices: () => ArchitectureService[];

View File

@@ -1,11 +1,9 @@
import { it, describe, expect } from 'vitest';
import { db } from './db.js';
import { parser } from './parser.js';
import { renderer, relativeRadius, closedRoundCurve } from './renderer.js';
import { relativeRadius, closedRoundCurve } from './renderer.js';
import { Diagram } from '../../Diagram.js';
import mermaidAPI from '../../mermaidAPI.js';
import { a } from 'vitest/dist/chunks/suite.qtkXWc6R.js';
import { buildRadarStyleOptions } from './styles.js';
const {
clear,

View File

@@ -1,3 +1,4 @@
import type { MermaidConfig } from '../../config.type.js';
import { getConfig } from '../../diagram-api/diagramAPI.js';
import { log } from '../../logger.js';
import common from '../common/common.js';
@@ -33,9 +34,10 @@ import {
STMT_RELATION,
STMT_STATE,
} from './stateCommon.js';
import type { Edge, NodeData, StateStmt, Stmt, StyleClass } from './stateDb.js';
// List of nodes created from the parsed diagram statement items
let nodeDb = new Map();
const nodeDb = new Map<string, NodeData>();
let graphItemCount = 0; // used to construct ids, etc.
@@ -43,18 +45,27 @@ let graphItemCount = 0; // used to construct ids, etc.
* Create a standard string for the dom ID of an item.
* If a type is given, insert that before the counter, preceded by the type spacer
*
* @param itemId
* @param counter
* @param {string | null} type
* @param typeSpacer
* @returns {string}
*/
export function stateDomId(itemId = '', counter = 0, type = '', typeSpacer = DOMID_TYPE_SPACER) {
export function stateDomId(
itemId = '',
counter = 0,
type: string | null = '',
typeSpacer = DOMID_TYPE_SPACER
) {
const typeStr = type !== null && type.length > 0 ? `${typeSpacer}${type}` : '';
return `${DOMID_STATE}-${itemId}${typeStr}-${counter}`;
}
const setupDoc = (parentParsedItem, doc, diagramStates, nodes, edges, altFlag, look, classes) => {
const setupDoc = (
parentParsedItem: StateStmt | undefined,
doc: Stmt[],
diagramStates: Map<string, StateStmt>,
nodes: NodeData[],
edges: Edge[],
altFlag: boolean,
look: MermaidConfig['look'],
classes: Map<string, StyleClass>
) => {
// graphItemCount = 0;
log.trace('items', doc);
doc.forEach((item) => {
@@ -95,7 +106,7 @@ const setupDoc = (parentParsedItem, doc, diagramStates, nodes, edges, altFlag, l
arrowTypeEnd: 'arrow_barb',
style: G_EDGE_STYLE,
labelStyle: '',
label: common.sanitizeText(item.description, getConfig()),
label: common.sanitizeText(item.description ?? '', getConfig()),
arrowheadStyle: G_EDGE_ARROWHEADSTYLE,
labelpos: G_EDGE_LABELPOS,
labelType: G_EDGE_LABELTYPE,
@@ -115,11 +126,10 @@ const setupDoc = (parentParsedItem, doc, diagramStates, nodes, edges, altFlag, l
* Get the direction from the statement items.
* Look through all of the documents (docs) in the parsedItems
* Because is a _document_ direction, the default direction is not necessarily the same as the overall default _diagram_ direction.
* @param {object[]} parsedItem - the parsed statement item to look through
* @param [defaultDir] - the direction to use if none is found
* @returns {string}
* @param parsedItem - the parsed statement item to look through
* @param defaultDir - the direction to use if none is found
*/
const getDir = (parsedItem, defaultDir = DEFAULT_NESTED_DOC_DIR) => {
const getDir = (parsedItem: { doc?: Stmt[] }, defaultDir = DEFAULT_NESTED_DOC_DIR) => {
let dir = defaultDir;
if (parsedItem.doc) {
for (const parsedItemDoc of parsedItem.doc) {
@@ -131,7 +141,11 @@ const getDir = (parsedItem, defaultDir = DEFAULT_NESTED_DOC_DIR) => {
return dir;
};
function insertOrUpdateNode(nodes, nodeData, classes) {
function insertOrUpdateNode(
nodes: NodeData[],
nodeData: NodeData,
classes: Map<string, StyleClass>
) {
if (!nodeData.id || nodeData.id === '</join></fork>' || nodeData.id === '</choice>') {
return;
}
@@ -143,9 +157,9 @@ function insertOrUpdateNode(nodes, nodeData, classes) {
}
nodeData.cssClasses.split(' ').forEach((cssClass) => {
if (classes.get(cssClass)) {
const classDef = classes.get(cssClass);
nodeData.cssCompiledStyles = [...nodeData.cssCompiledStyles, ...classDef.styles];
const classDef = classes.get(cssClass);
if (classDef) {
nodeData.cssCompiledStyles = [...(nodeData.cssCompiledStyles ?? []), ...classDef.styles];
}
});
}
@@ -162,31 +176,30 @@ function insertOrUpdateNode(nodes, nodeData, classes) {
* If there aren't any or if dbInfoItem isn't defined, return an empty string.
* Else create 1 string from the list of classes found
*
* @param {undefined | null | object} dbInfoItem
* @returns {string}
*/
function getClassesFromDbInfo(dbInfoItem) {
function getClassesFromDbInfo(dbInfoItem?: StateStmt): string {
return dbInfoItem?.classes?.join(' ') ?? '';
}
function getStylesFromDbInfo(dbInfoItem) {
function getStylesFromDbInfo(dbInfoItem?: StateStmt): string[] {
return dbInfoItem?.styles ?? [];
}
export const dataFetcher = (
parent,
parsedItem,
diagramStates,
nodes,
edges,
altFlag,
look,
classes
parent: StateStmt | undefined,
parsedItem: StateStmt,
diagramStates: Map<string, StateStmt>,
nodes: NodeData[],
edges: Edge[],
altFlag: boolean,
look: MermaidConfig['look'],
classes: Map<string, StyleClass>
) => {
const itemId = parsedItem.id;
const dbState = diagramStates.get(itemId);
const classStr = getClassesFromDbInfo(dbState);
const style = getStylesFromDbInfo(dbState);
const config = getConfig();
log.info('dataFetcher parsedItem', parsedItem, dbState, style);
@@ -207,13 +220,13 @@ export const dataFetcher = (
nodeDb.set(itemId, {
id: itemId,
shape,
description: common.sanitizeText(itemId, getConfig()),
description: common.sanitizeText(itemId, config),
cssClasses: `${classStr} ${CSS_DIAGRAM_STATE}`,
cssStyles: style,
});
}
const newNode = nodeDb.get(itemId);
const newNode = nodeDb.get(itemId)!;
// Save data for description and group so that for instance a statement without description overwrites
// one with description @todo TODO What does this mean? If important, add a test for it
@@ -225,7 +238,7 @@ export const dataFetcher = (
newNode.shape = SHAPE_STATE_WITH_DESC;
newNode.description.push(parsedItem.description);
} else {
if (newNode.description?.length > 0) {
if (newNode.description?.length && newNode.description.length > 0) {
// if there is a description already transform it to an array
newNode.shape = SHAPE_STATE_WITH_DESC;
if (newNode.description === itemId) {
@@ -239,7 +252,7 @@ export const dataFetcher = (
newNode.description = parsedItem.description;
}
}
newNode.description = common.sanitizeTextOrArray(newNode.description, getConfig());
newNode.description = common.sanitizeTextOrArray(newNode.description, config);
}
// If there's only 1 description entry, just use a regular state shape
@@ -262,7 +275,7 @@ export const dataFetcher = (
}
// This is what will be added to the graph
const nodeData = {
const nodeData: NodeData = {
labelStyle: '',
shape: newNode.shape,
label: newNode.description,
@@ -294,19 +307,19 @@ export const dataFetcher = (
if (parsedItem.note) {
// Todo: set random id
const noteData = {
const noteData: NodeData = {
labelStyle: '',
shape: SHAPE_NOTE,
label: parsedItem.note.text,
cssClasses: CSS_DIAGRAM_NOTE,
// useHtmlLabels: false,
cssStyles: [],
cssCompilesStyles: [],
cssCompiledStyles: [],
id: itemId + NOTE_ID + '-' + graphItemCount,
domId: stateDomId(itemId, graphItemCount, NOTE),
type: newNode.type,
isGroup: newNode.type === 'group',
padding: getConfig().flowchart.padding,
padding: config.flowchart?.padding,
look,
position: parsedItem.note.position,
};

View File

@@ -1,16 +0,0 @@
const idCache = {};
export const set = (key, val) => {
idCache[key] = val;
};
export const get = (k) => idCache[k];
export const keys = () => Object.keys(idCache);
export const size = () => keys().length;
export default {
get,
set,
keys,
size,
};

View File

@@ -1,5 +1,4 @@
import { line, curveBasis } from 'd3';
import idCache from './id-cache.js';
import { StateDB } from './stateDb.js';
import utils from '../../utils.js';
import common from '../common/common.js';
@@ -405,8 +404,6 @@ export const drawState = function (elem, stateDef) {
stateInfo.width = stateBox.width + 2 * getConfig().state.padding;
stateInfo.height = stateBox.height + 2 * getConfig().state.padding;
idCache.set(id, stateInfo);
// stateCnt++;
return stateInfo;
};

View File

@@ -13,6 +13,10 @@ export const STMT_DIRECTION = 'dir';
// parsed statement type for a state
export const STMT_STATE = 'state';
// parsed statement type for a root
export const STMT_ROOT = 'root';
// parsed statement type for a relation
export const STMT_RELATION = 'relation';
// parsed statement type for a classDef

View File

@@ -1,706 +0,0 @@
import { getConfig } from '../../diagram-api/diagramAPI.js';
import { log } from '../../logger.js';
import { generateId } from '../../utils.js';
import common from '../common/common.js';
import {
clear as commonClear,
getAccDescription,
getAccTitle,
getDiagramTitle,
setAccDescription,
setAccTitle,
setDiagramTitle,
} from '../common/commonDb.js';
import { dataFetcher, reset as resetDataFetching } from './dataFetcher.js';
import { getDir } from './stateRenderer-v3-unified.js';
import {
DEFAULT_DIAGRAM_DIRECTION,
DEFAULT_STATE_TYPE,
DIVIDER_TYPE,
STMT_APPLYCLASS,
STMT_CLASSDEF,
STMT_DIRECTION,
STMT_RELATION,
STMT_STATE,
STMT_STYLEDEF,
} from './stateCommon.js';
const START_NODE = '[*]';
const START_TYPE = 'start';
const END_NODE = START_NODE;
const END_TYPE = 'end';
const COLOR_KEYWORD = 'color';
const FILL_KEYWORD = 'fill';
const BG_FILL = 'bgFill';
const STYLECLASS_SEP = ',';
/**
* Returns a new list of classes.
* In the future, this can be replaced with a class common to all diagrams.
* ClassDef information = { id: id, styles: [], textStyles: [] }
*
* @returns {Map<string, any>}
*/
function newClassesList() {
return new Map();
}
const newDoc = () => {
return {
/** @type {{ id1: string, id2: string, relationTitle: string }[]} */
relations: [],
states: new Map(),
documents: {},
};
};
const clone = (o) => JSON.parse(JSON.stringify(o));
export class StateDB {
/**
* @param {1 | 2} version - v1 renderer or v2 renderer.
*/
constructor(version) {
this.clear();
this.version = version;
// 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 {1 | 2}
*/
version;
/**
* @private
* @type {Array}
*/
nodes = [];
/**
* @private
* @type {Array}
*/
edges = [];
/**
* @private
* @type {Array}
*/
rootDoc = [];
/**
* @private
* @type {Map<string, any>}
*/
classes = newClassesList(); // style classes defined by a classDef
/**
* @private
* @type {Object}
*/
documents = {
root: newDoc(),
};
/**
* @private
* @type {Object}
*/
currentDocument = this.documents.root;
/**
* @private
* @type {number}
*/
startEndCount = 0;
/**
* @private
* @type {number}
*/
dividerCnt = 0;
static relationType = {
AGGREGATION: 0,
EXTENSION: 1,
COMPOSITION: 2,
DEPENDENCY: 3,
};
setRootDoc(o) {
log.info('Setting root doc', o);
// rootDoc = { id: 'root', doc: o };
this.rootDoc = o;
if (this.version === 1) {
this.extract(o);
} else {
this.extract(this.getRootDocV2());
}
}
getRootDoc() {
return this.rootDoc;
}
/**
* @private
* @param {Object} parent
* @param {Object} node
* @param {boolean} first
*/
docTranslator(parent, node, first) {
if (node.stmt === STMT_RELATION) {
this.docTranslator(parent, node.state1, true);
this.docTranslator(parent, node.state2, false);
} else {
if (node.stmt === STMT_STATE) {
if (node.id === '[*]') {
node.id = first ? parent.id + '_start' : parent.id + '_end';
node.start = first;
} else {
// This is just a plain state, not a start or end
node.id = node.id.trim();
}
}
if (node.doc) {
const doc = [];
// Check for concurrency
let currentDoc = [];
let i;
for (i = 0; i < node.doc.length; i++) {
if (node.doc[i].type === DIVIDER_TYPE) {
const newNode = clone(node.doc[i]);
newNode.doc = clone(currentDoc);
doc.push(newNode);
currentDoc = [];
} else {
currentDoc.push(node.doc[i]);
}
}
// If any divider was encountered
if (doc.length > 0 && currentDoc.length > 0) {
const newNode = {
stmt: STMT_STATE,
id: generateId(),
type: 'divider',
doc: clone(currentDoc),
};
doc.push(clone(newNode));
node.doc = doc;
}
node.doc.forEach((docNode) => this.docTranslator(node, docNode, true));
}
}
}
/**
* @private
*/
getRootDocV2() {
this.docTranslator({ id: 'root' }, { id: 'root', doc: this.rootDoc }, true);
return { id: 'root', doc: this.rootDoc };
// Here
}
/**
* Convert all of the statements (stmts) that were parsed into states and relationships.
* This is done because a state diagram may have nested sections,
* where each section is a 'document' and has its own set of statements.
* Ex: the section within a fork has its own statements, and incoming and outgoing statements
* refer to the fork as a whole (document).
* See the parser grammar: the definition of a document is a document then a 'line', where a line can be a statement.
* This will push the statement into the list of statements for the current document.
* @private
* @param _doc
*/
extract(_doc) {
// const res = { states: [], relations: [] };
let doc;
if (_doc.doc) {
doc = _doc.doc;
} else {
doc = _doc;
}
// let doc = root.doc;
// if (!doc) {
// doc = root;
// }
log.info(doc);
this.clear(true);
log.info('Extract initial document:', doc);
doc.forEach((item) => {
log.warn('Statement', item.stmt);
switch (item.stmt) {
case STMT_STATE:
this.addState(
item.id.trim(),
item.type,
item.doc,
item.description,
item.note,
item.classes,
item.styles,
item.textStyles
);
break;
case STMT_RELATION:
this.addRelation(item.state1, item.state2, item.description);
break;
case STMT_CLASSDEF:
this.addStyleClass(item.id.trim(), item.classes);
break;
case STMT_STYLEDEF:
{
const ids = item.id.trim().split(',');
const styles = item.styleClass.split(',');
ids.forEach((id) => {
let foundState = this.getState(id);
if (foundState === undefined) {
const trimmedId = id.trim();
this.addState(trimmedId);
foundState = this.getState(trimmedId);
}
foundState.styles = styles.map((s) => s.replace(/;/g, '')?.trim());
});
}
break;
case STMT_APPLYCLASS:
this.setCssClass(item.id.trim(), item.styleClass);
break;
}
});
const diagramStates = this.getStates();
const config = getConfig();
const look = config.look;
resetDataFetching();
dataFetcher(
undefined,
this.getRootDocV2(),
diagramStates,
this.nodes,
this.edges,
true,
look,
this.classes
);
this.nodes.forEach((node) => {
if (Array.isArray(node.label)) {
// add the rest as description
node.description = node.label.slice(1);
if (node.isGroup && node.description.length > 0) {
throw new Error(
'Group nodes can only have label. Remove the additional description for node [' +
node.id +
']'
);
}
// add first description as label
node.label = node.label[0];
}
});
}
/**
* Function called by parser when a node definition has been found.
*
* @param {null | string} id
* @param {null | string} type
* @param {null | string} doc
* @param {null | string | string[]} descr - description for the state. Can be a string or a list or strings
* @param {null | string} note
* @param {null | string | string[]} classes - class styles to apply to this state. Can be a string (1 style) or an array of styles. If it's just 1 class, convert it to an array of that 1 class.
* @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.
*/
addState(
id,
type = DEFAULT_STATE_TYPE,
doc = null,
descr = null,
note = null,
classes = null,
styles = null,
textStyles = null
) {
const trimmedId = id?.trim();
// add the state if needed
if (!this.currentDocument.states.has(trimmedId)) {
log.info('Adding state ', trimmedId, descr);
this.currentDocument.states.set(trimmedId, {
id: trimmedId,
descriptions: [],
type,
doc,
note,
classes: [],
styles: [],
textStyles: [],
});
} else {
if (!this.currentDocument.states.get(trimmedId).doc) {
this.currentDocument.states.get(trimmedId).doc = doc;
}
if (!this.currentDocument.states.get(trimmedId).type) {
this.currentDocument.states.get(trimmedId).type = type;
}
}
if (descr) {
log.info('Setting state description', trimmedId, descr);
if (typeof descr === 'string') {
this.addDescription(trimmedId, descr.trim());
}
if (typeof descr === 'object') {
descr.forEach((des) => this.addDescription(trimmedId, des.trim()));
}
}
if (note) {
const doc2 = this.currentDocument.states.get(trimmedId);
doc2.note = note;
doc2.note.text = common.sanitizeText(doc2.note.text, getConfig());
}
if (classes) {
log.info('Setting state classes', trimmedId, classes);
const classesList = typeof classes === 'string' ? [classes] : classes;
classesList.forEach((cssClass) => this.setCssClass(trimmedId, cssClass.trim()));
}
if (styles) {
log.info('Setting state styles', trimmedId, styles);
const stylesList = typeof styles === 'string' ? [styles] : styles;
stylesList.forEach((style) => this.setStyle(trimmedId, style.trim()));
}
if (textStyles) {
log.info('Setting state styles', trimmedId, styles);
const textStylesList = typeof textStyles === 'string' ? [textStyles] : textStyles;
textStylesList.forEach((textStyle) => this.setTextStyle(trimmedId, textStyle.trim()));
}
}
clear(saveCommon) {
this.nodes = [];
this.edges = [];
this.documents = {
root: newDoc(),
};
this.currentDocument = this.documents.root;
// number of start and end nodes; used to construct ids
this.startEndCount = 0;
this.classes = newClassesList();
if (!saveCommon) {
commonClear();
}
}
getState(id) {
return this.currentDocument.states.get(id);
}
getStates() {
return this.currentDocument.states;
}
logDocuments() {
log.info('Documents = ', this.documents);
}
getRelations() {
return this.currentDocument.relations;
}
/**
* If the id is a start node ( [*] ), then return a new id constructed from
* the start node name and the current start node count.
* else return the given id
*
* @param {string} id
* @returns {string} - the id (original or constructed)
* @private
*/
startIdIfNeeded(id = '') {
let fixedId = id;
if (id === START_NODE) {
this.startEndCount++;
fixedId = `${START_TYPE}${this.startEndCount}`;
}
return fixedId;
}
/**
* If the id is a start node ( [*] ), then return the start type ('start')
* else return the given type
*
* @param {string} id
* @param {string} type
* @returns {string} - the type that should be used
* @private
*/
startTypeIfNeeded(id = '', type = DEFAULT_STATE_TYPE) {
return id === START_NODE ? START_TYPE : type;
}
/**
* If the id is an end node ( [*] ), then return a new id constructed from
* the end node name and the current start_end node count.
* else return the given id
*
* @param {string} id
* @returns {string} - the id (original or constructed)
* @private
*/
endIdIfNeeded(id = '') {
let fixedId = id;
if (id === END_NODE) {
this.startEndCount++;
fixedId = `${END_TYPE}${this.startEndCount}`;
}
return fixedId;
}
/**
* If the id is an end node ( [*] ), then return the end type
* else return the given type
*
* @param {string} id
* @param {string} type
* @returns {string} - the type that should be used
* @private
*/
endTypeIfNeeded(id = '', type = DEFAULT_STATE_TYPE) {
return id === END_NODE ? END_TYPE : type;
}
/**
*
* @param item1
* @param item2
* @param relationTitle
*/
addRelationObjs(item1, item2, relationTitle) {
let id1 = this.startIdIfNeeded(item1.id.trim());
let type1 = this.startTypeIfNeeded(item1.id.trim(), item1.type);
let id2 = this.startIdIfNeeded(item2.id.trim());
let type2 = this.startTypeIfNeeded(item2.id.trim(), item2.type);
this.addState(
id1,
type1,
item1.doc,
item1.description,
item1.note,
item1.classes,
item1.styles,
item1.textStyles
);
this.addState(
id2,
type2,
item2.doc,
item2.description,
item2.note,
item2.classes,
item2.styles,
item2.textStyles
);
this.currentDocument.relations.push({
id1,
id2,
relationTitle: common.sanitizeText(relationTitle, getConfig()),
});
}
/**
* Add a relation between two items. The items may be full objects or just the string id of a state.
*
* @param {string | object} item1
* @param {string | object} item2
* @param {string} title
*/
addRelation(item1, item2, title) {
if (typeof item1 === 'object') {
this.addRelationObjs(item1, item2, title);
} else {
const id1 = this.startIdIfNeeded(item1.trim());
const type1 = this.startTypeIfNeeded(item1);
const id2 = this.endIdIfNeeded(item2.trim());
const type2 = this.endTypeIfNeeded(item2);
this.addState(id1, type1);
this.addState(id2, type2);
this.currentDocument.relations.push({
id1,
id2,
title: common.sanitizeText(title, getConfig()),
});
}
}
addDescription(id, descr) {
const theState = this.currentDocument.states.get(id);
const _descr = descr.startsWith(':') ? descr.replace(':', '').trim() : descr;
theState.descriptions.push(common.sanitizeText(_descr, getConfig()));
}
cleanupLabel(label) {
if (label.substring(0, 1) === ':') {
return label.substr(2).trim();
} else {
return label.trim();
}
}
getDividerId() {
this.dividerCnt++;
return 'divider-id-' + this.dividerCnt;
}
/**
* Called when the parser comes across a (style) class definition
* @example classDef my-style fill:#f96;
*
* @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)
*/
addStyleClass(id, styleAttributes = '') {
// create a new style class object with this id
if (!this.classes.has(id)) {
this.classes.set(id, { id: id, styles: [], textStyles: [] }); // This is a classDef
}
const foundClass = this.classes.get(id);
if (styleAttributes !== undefined && styleAttributes !== null) {
styleAttributes.split(STYLECLASS_SEP).forEach((attrib) => {
// remove any trailing ;
const fixedAttrib = attrib.replace(/([^;]*);/, '$1').trim();
// replace some style keywords
if (RegExp(COLOR_KEYWORD).exec(attrib)) {
const newStyle1 = fixedAttrib.replace(FILL_KEYWORD, BG_FILL);
const newStyle2 = newStyle1.replace(COLOR_KEYWORD, FILL_KEYWORD);
foundClass.textStyles.push(newStyle2);
}
foundClass.styles.push(fixedAttrib);
});
}
}
/**
* Return all of the style classes
* @returns {{} | any | classes}
*/
getClasses() {
return this.classes;
}
/**
* Add a (style) class or css class to a state with the given id.
* If the state isn't already in the list of known states, add it.
* Might be called by parser when a style class or CSS class should be applied to a state
*
* @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
*/
setCssClass(itemIds, cssClassName) {
itemIds.split(',').forEach((id) => {
let foundState = this.getState(id);
if (foundState === undefined) {
const trimmedId = id.trim();
this.addState(trimmedId);
foundState = this.getState(trimmedId);
}
foundState.classes.push(cssClassName);
});
}
/**
* Add a style to a state with the given id.
* @example style stateId fill:#f9f,stroke:#333,stroke-width:4px
* where 'style' is the keyword
* stateId is the id of a state
* the rest of the string is the styleText (all of the attributes to be applied to the state)
*
* @param itemId The id of item to apply the style to
* @param styleText - the text of the attributes for the style
*/
setStyle(itemId, styleText) {
const item = this.getState(itemId);
if (item !== undefined) {
item.styles.push(styleText);
}
}
/**
* Add a text style to a state with the given id
*
* @param itemId The id of item to apply the css class to
* @param cssClassName CSS class name
*/
setTextStyle(itemId, cssClassName) {
const item = this.getState(itemId);
if (item !== undefined) {
item.textStyles.push(cssClassName);
}
}
/**
* Finds the direction statement in the root document.
* @private
* @returns {{ value: string } | undefined} - the direction statement if present
*/
getDirectionStatement() {
return this.rootDoc.find((doc) => doc.stmt === STMT_DIRECTION);
}
getDirection() {
return this.getDirectionStatement()?.value ?? DEFAULT_DIAGRAM_DIRECTION;
}
setDirection(dir) {
const doc = this.getDirectionStatement();
if (doc) {
doc.value = dir;
} else {
this.rootDoc.unshift({ stmt: STMT_DIRECTION, value: dir });
}
}
trimColon(str) {
return str && str[0] === ':' ? str.substr(1).trim() : str.trim();
}
getData() {
const config = getConfig();
return {
nodes: this.nodes,
edges: this.edges,
other: {},
config,
direction: getDir(this.getRootDocV2()),
};
}
getConfig() {
return getConfig().state;
}
getAccTitle = getAccTitle;
setAccTitle = setAccTitle;
getAccDescription = getAccDescription;
setAccDescription = setAccDescription;
setDiagramTitle = setDiagramTitle;
getDiagramTitle = getDiagramTitle;
}

View File

@@ -0,0 +1,693 @@
import { getConfig } from '../../diagram-api/diagramAPI.js';
import { log } from '../../logger.js';
import { generateId } from '../../utils.js';
import common from '../common/common.js';
import {
clear as commonClear,
getAccDescription,
getAccTitle,
getDiagramTitle,
setAccDescription,
setAccTitle,
setDiagramTitle,
} from '../common/commonDb.js';
import { dataFetcher, reset as resetDataFetcher } from './dataFetcher.js';
import { getDir } from './stateRenderer-v3-unified.js';
import {
DEFAULT_DIAGRAM_DIRECTION,
DEFAULT_STATE_TYPE,
DIVIDER_TYPE,
STMT_APPLYCLASS,
STMT_CLASSDEF,
STMT_RELATION,
STMT_ROOT,
STMT_DIRECTION,
STMT_STATE,
STMT_STYLEDEF,
} from './stateCommon.js';
import type { MermaidConfig } from '../../config.type.js';
const CONSTANTS = {
START_NODE: '[*]',
START_TYPE: 'start',
END_NODE: '[*]',
END_TYPE: 'end',
COLOR_KEYWORD: 'color',
FILL_KEYWORD: 'fill',
BG_FILL: 'bgFill',
STYLECLASS_SEP: ',',
} as const;
interface BaseStmt {
stmt: 'applyClass' | 'classDef' | 'dir' | 'relation' | 'state' | 'style' | 'root' | 'default';
}
interface ApplyClassStmt extends BaseStmt {
stmt: 'applyClass';
id: string;
styleClass: string;
}
interface ClassDefStmt extends BaseStmt {
stmt: 'classDef';
id: string;
classes: string;
}
interface DirectionStmt extends BaseStmt {
stmt: 'dir';
value: 'TB' | 'BT' | 'RL' | 'LR';
}
interface RelationStmt extends BaseStmt {
stmt: 'relation';
state1: StateStmt;
state2: StateStmt;
description?: string;
}
export interface StateStmt extends BaseStmt {
stmt: 'state' | 'default';
id: string;
type: 'default' | 'fork' | 'join' | 'choice' | 'divider' | 'start' | 'end';
description?: string;
descriptions?: string[];
doc?: Stmt[];
note?: Note;
start?: boolean;
classes?: string[];
styles?: string[];
textStyles?: string[];
}
interface StyleStmt extends BaseStmt {
stmt: 'style';
id: string;
styleClass: string;
}
export interface RootStmt {
id: 'root';
stmt: 'root';
doc?: Stmt[];
}
interface Note {
position?: 'left of' | 'right of';
text: string;
}
export type Stmt =
| ApplyClassStmt
| ClassDefStmt
| DirectionStmt
| RelationStmt
| StateStmt
| StyleStmt
| RootStmt;
interface DiagramEdge {
id1: string;
id2: string;
relationTitle?: string;
}
interface Document {
relations: DiagramEdge[];
states: Map<string, StateStmt>;
documents: Record<string, Document>;
}
export interface StyleClass {
id: string;
styles: string[];
textStyles: string[];
}
export interface NodeData {
labelStyle?: string;
shape: string;
label?: string | string[];
cssClasses: string;
cssCompiledStyles?: string[];
cssStyles: string[];
id: string;
dir?: string;
domId?: string;
type?: string;
isGroup?: boolean;
padding?: number;
rx?: number;
ry?: number;
look?: MermaidConfig['look'];
parentId?: string;
centerLabel?: boolean;
position?: string;
description?: string | string[];
}
export interface Edge {
id: string;
start: string;
end: string;
arrowhead: string;
arrowTypeEnd: string;
style: string;
labelStyle: string;
label?: string;
arrowheadStyle: string;
labelpos: string;
labelType: string;
thickness: string;
classes: string;
look: MermaidConfig['look'];
}
/**
* Returns a new list of classes.
* In the future, this can be replaced with a class common to all diagrams.
* ClassDef information = \{ id: id, styles: [], textStyles: [] \}
*/
const newClassesList = (): Map<string, StyleClass> => new Map();
const newDoc = (): Document => ({
relations: [],
states: new Map(),
documents: {},
});
const clone = <T>(o: T): T => JSON.parse(JSON.stringify(o));
export class StateDB {
private nodes: NodeData[] = [];
private edges: Edge[] = [];
private rootDoc: Stmt[] = [];
private classes = newClassesList();
private documents = { root: newDoc() };
private currentDocument = this.documents.root;
private startEndCount = 0;
private dividerCnt = 0;
static readonly relationType = {
AGGREGATION: 0,
EXTENSION: 1,
COMPOSITION: 2,
DEPENDENCY: 3,
} as const;
constructor(private version: 1 | 2) {
this.clear();
// Bind methods used by JISON
this.setRootDoc = this.setRootDoc.bind(this);
this.getDividerId = this.getDividerId.bind(this);
this.setDirection = this.setDirection.bind(this);
this.trimColon = this.trimColon.bind(this);
}
/**
* Convert all of the statements (stmts) that were parsed into states and relationships.
* This is done because a state diagram may have nested sections,
* where each section is a 'document' and has its own set of statements.
* Ex: the section within a fork has its own statements, and incoming and outgoing statements
* refer to the fork as a whole (document).
* See the parser grammar: the definition of a document is a document then a 'line', where a line can be a statement.
* This will push the statement into the list of statements for the current document.
*/
extract(statements: Stmt[] | { doc: Stmt[] }) {
this.clear(true);
for (const item of Array.isArray(statements) ? statements : statements.doc) {
switch (item.stmt) {
case STMT_STATE:
this.addState(item.id.trim(), item.type, item.doc, item.description, item.note);
break;
case STMT_RELATION:
this.addRelation(item.state1, item.state2, item.description);
break;
case STMT_CLASSDEF:
this.addStyleClass(item.id.trim(), item.classes);
break;
case STMT_STYLEDEF:
this.handleStyleDef(item);
break;
case STMT_APPLYCLASS:
this.setCssClass(item.id.trim(), item.styleClass);
break;
}
}
const diagramStates = this.getStates();
const config = getConfig();
resetDataFetcher();
dataFetcher(
undefined,
this.getRootDocV2() as StateStmt,
diagramStates,
this.nodes,
this.edges,
true,
config.look,
this.classes
);
// Process node labels
for (const node of this.nodes) {
if (!Array.isArray(node.label)) {
continue;
}
node.description = node.label.slice(1);
if (node.isGroup && node.description.length > 0) {
throw new Error(
`Group nodes can only have label. Remove the additional description for node [${node.id}]`
);
}
node.label = node.label[0];
}
}
private handleStyleDef(item: StyleStmt) {
const ids = item.id.trim().split(',');
const styles = item.styleClass.split(',');
for (const id of ids) {
let state = this.getState(id);
if (!state) {
const trimmedId = id.trim();
this.addState(trimmedId);
state = this.getState(trimmedId);
}
if (state) {
state.styles = styles.map((s) => s.replace(/;/g, '')?.trim());
}
}
}
setRootDoc(o: Stmt[]) {
log.info('Setting root doc', o);
this.rootDoc = o;
if (this.version === 1) {
this.extract(o);
} else {
this.extract(this.getRootDocV2());
}
}
docTranslator(parent: RootStmt | StateStmt, node: Stmt, first: boolean) {
if (node.stmt === STMT_RELATION) {
this.docTranslator(parent, node.state1, true);
this.docTranslator(parent, node.state2, false);
return;
}
if (node.stmt === STMT_STATE) {
if (node.id === CONSTANTS.START_NODE) {
node.id = parent.id + (first ? '_start' : '_end');
node.start = first;
} else {
// This is just a plain state, not a start or end
node.id = node.id.trim();
}
}
if ((node.stmt !== STMT_ROOT && node.stmt !== STMT_STATE) || !node.doc) {
return;
}
const doc = [];
// Check for concurrency
let currentDoc = [];
for (const stmt of node.doc) {
if ((stmt as StateStmt).type === DIVIDER_TYPE) {
const newNode = clone(stmt as StateStmt);
newNode.doc = clone(currentDoc);
doc.push(newNode);
currentDoc = [];
} else {
currentDoc.push(stmt);
}
}
// If any divider was encountered
if (doc.length > 0 && currentDoc.length > 0) {
const newNode = {
stmt: STMT_STATE,
id: generateId(),
type: 'divider',
doc: clone(currentDoc),
} satisfies StateStmt;
doc.push(clone(newNode));
node.doc = doc;
}
node.doc.forEach((docNode) => this.docTranslator(node, docNode, true));
}
private getRootDocV2() {
this.docTranslator(
{ id: STMT_ROOT, stmt: STMT_ROOT },
{ id: STMT_ROOT, stmt: STMT_ROOT, doc: this.rootDoc },
true
);
return { id: STMT_ROOT, doc: this.rootDoc };
}
/**
* Function called by parser when a node definition has been found.
*
* @param descr - description for the state. Can be a string or a list or strings
* @param classes - class styles to apply to this state. Can be a string (1 style) or an array of styles. If it's just 1 class, convert it to an array of that 1 class.
* @param 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 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.
*/
addState(
id: string,
type: StateStmt['type'] = DEFAULT_STATE_TYPE,
doc: Stmt[] | undefined = undefined,
descr: string | string[] | undefined = undefined,
note: Note | undefined = undefined,
classes: string | string[] | undefined = undefined,
styles: string | string[] | undefined = undefined,
textStyles: string | string[] | undefined = undefined
) {
const trimmedId = id?.trim();
if (!this.currentDocument.states.has(trimmedId)) {
log.info('Adding state ', trimmedId, descr);
this.currentDocument.states.set(trimmedId, {
stmt: STMT_STATE,
id: trimmedId,
descriptions: [],
type,
doc,
note,
classes: [],
styles: [],
textStyles: [],
});
} else {
const state = this.currentDocument.states.get(trimmedId);
if (!state) {
throw new Error(`State not found: ${trimmedId}`);
}
if (!state.doc) {
state.doc = doc;
}
if (!state.type) {
state.type = type;
}
}
if (descr) {
log.info('Setting state description', trimmedId, descr);
const descriptions = Array.isArray(descr) ? descr : [descr];
descriptions.forEach((des) => this.addDescription(trimmedId, des.trim()));
}
if (note) {
const doc2 = this.currentDocument.states.get(trimmedId);
if (!doc2) {
throw new Error(`State not found: ${trimmedId}`);
}
doc2.note = note;
doc2.note.text = common.sanitizeText(doc2.note.text, getConfig());
}
if (classes) {
log.info('Setting state classes', trimmedId, classes);
const classesList = Array.isArray(classes) ? classes : [classes];
classesList.forEach((cssClass) => this.setCssClass(trimmedId, cssClass.trim()));
}
if (styles) {
log.info('Setting state styles', trimmedId, styles);
const stylesList = Array.isArray(styles) ? styles : [styles];
stylesList.forEach((style) => this.setStyle(trimmedId, style.trim()));
}
if (textStyles) {
log.info('Setting state styles', trimmedId, styles);
const textStylesList = Array.isArray(textStyles) ? textStyles : [textStyles];
textStylesList.forEach((textStyle) => this.setTextStyle(trimmedId, textStyle.trim()));
}
}
clear(saveCommon?: boolean) {
this.nodes = [];
this.edges = [];
this.documents = { root: newDoc() };
this.currentDocument = this.documents.root;
// number of start and end nodes; used to construct ids
this.startEndCount = 0;
this.classes = newClassesList();
if (!saveCommon) {
commonClear();
}
}
getState(id: string) {
return this.currentDocument.states.get(id);
}
getStates() {
return this.currentDocument.states;
}
logDocuments() {
log.info('Documents = ', this.documents);
}
getRelations() {
return this.currentDocument.relations;
}
/**
* If the id is a start node ( [*] ), then return a new id constructed from
* the start node name and the current start node count.
* else return the given id
*/
startIdIfNeeded(id = '') {
if (id === CONSTANTS.START_NODE) {
this.startEndCount++;
return `${CONSTANTS.START_TYPE}${this.startEndCount}`;
}
return id;
}
/**
* If the id is a start node ( [*] ), then return the start type ('start')
* else return the given type
*/
startTypeIfNeeded(id = '', type: StateStmt['type'] = DEFAULT_STATE_TYPE) {
return id === CONSTANTS.START_NODE ? CONSTANTS.START_TYPE : type;
}
/**
* If the id is an end node ( [*] ), then return a new id constructed from
* the end node name and the current start_end node count.
* else return the given id
*/
endIdIfNeeded(id = '') {
if (id === CONSTANTS.END_NODE) {
this.startEndCount++;
return `${CONSTANTS.END_TYPE}${this.startEndCount}`;
}
return id;
}
/**
* If the id is an end node ( [*] ), then return the end type
* else return the given type
*
*/
endTypeIfNeeded(id = '', type: StateStmt['type'] = DEFAULT_STATE_TYPE) {
return id === CONSTANTS.END_NODE ? CONSTANTS.END_TYPE : type;
}
addRelationObjs(item1: StateStmt, item2: StateStmt, relationTitle = '') {
const id1 = this.startIdIfNeeded(item1.id.trim());
const type1 = this.startTypeIfNeeded(item1.id.trim(), item1.type);
const id2 = this.startIdIfNeeded(item2.id.trim());
const type2 = this.startTypeIfNeeded(item2.id.trim(), item2.type);
this.addState(
id1,
type1,
item1.doc,
item1.description,
item1.note,
item1.classes,
item1.styles,
item1.textStyles
);
this.addState(
id2,
type2,
item2.doc,
item2.description,
item2.note,
item2.classes,
item2.styles,
item2.textStyles
);
this.currentDocument.relations.push({
id1,
id2,
relationTitle: common.sanitizeText(relationTitle, getConfig()),
});
}
/**
* Add a relation between two items. The items may be full objects or just the string id of a state.
*/
addRelation(item1: string | StateStmt, item2: string | StateStmt, title?: string) {
if (typeof item1 === 'object' && typeof item2 === 'object') {
this.addRelationObjs(item1, item2, title);
} else if (typeof item1 === 'string' && typeof item2 === 'string') {
const id1 = this.startIdIfNeeded(item1.trim());
const type1 = this.startTypeIfNeeded(item1);
const id2 = this.endIdIfNeeded(item2.trim());
const type2 = this.endTypeIfNeeded(item2);
this.addState(id1, type1);
this.addState(id2, type2);
this.currentDocument.relations.push({
id1,
id2,
relationTitle: title ? common.sanitizeText(title, getConfig()) : undefined,
});
}
}
addDescription(id: string, descr: string) {
const theState = this.currentDocument.states.get(id);
const _descr = descr.startsWith(':') ? descr.replace(':', '').trim() : descr;
theState?.descriptions?.push(common.sanitizeText(_descr, getConfig()));
}
cleanupLabel(label: string) {
return label.startsWith(':') ? label.slice(2).trim() : label.trim();
}
getDividerId() {
this.dividerCnt++;
return `divider-id-${this.dividerCnt}`;
}
/**
* Called when the parser comes across a (style) class definition
* @example classDef my-style fill:#f96;
*
* @param id - the id of this (style) class
* @param styleAttributes - the string with 1 or more style attributes (each separated by a comma)
*/
addStyleClass(id: string, styleAttributes = '') {
// create a new style class object with this id
if (!this.classes.has(id)) {
this.classes.set(id, { id, styles: [], textStyles: [] });
}
const foundClass = this.classes.get(id);
if (styleAttributes && foundClass) {
styleAttributes.split(CONSTANTS.STYLECLASS_SEP).forEach((attrib) => {
const fixedAttrib = attrib.replace(/([^;]*);/, '$1').trim();
if (RegExp(CONSTANTS.COLOR_KEYWORD).exec(attrib)) {
const newStyle1 = fixedAttrib.replace(CONSTANTS.FILL_KEYWORD, CONSTANTS.BG_FILL);
const newStyle2 = newStyle1.replace(CONSTANTS.COLOR_KEYWORD, CONSTANTS.FILL_KEYWORD);
foundClass.textStyles.push(newStyle2);
}
foundClass.styles.push(fixedAttrib);
});
}
}
getClasses() {
return this.classes;
}
/**
* Add a (style) class or css class to a state with the given id.
* If the state isn't already in the list of known states, add it.
* Might be called by parser when a style class or CSS class should be applied to a state
*
* @param itemIds - The id or a list of ids of the item(s) to apply the css class to
* @param cssClassName - CSS class name
*/
setCssClass(itemIds: string, cssClassName: string) {
itemIds.split(',').forEach((id) => {
let foundState = this.getState(id);
if (!foundState) {
const trimmedId = id.trim();
this.addState(trimmedId);
foundState = this.getState(trimmedId);
}
foundState?.classes?.push(cssClassName);
});
}
/**
* Add a style to a state with the given id.
* @example style stateId fill:#f9f,stroke:#333,stroke-width:4px
* where 'style' is the keyword
* stateId is the id of a state
* the rest of the string is the styleText (all of the attributes to be applied to the state)
*
* @param itemId - The id of item to apply the style to
* @param styleText - the text of the attributes for the style
*/
setStyle(itemId: string, styleText: string) {
this.getState(itemId)?.styles?.push(styleText);
}
/**
* Add a text style to a state with the given id
*
* @param itemId - The id of item to apply the css class to
* @param cssClassName - CSS class name
*/
setTextStyle(itemId: string, cssClassName: string) {
this.getState(itemId)?.textStyles?.push(cssClassName);
}
/**
* Finds the direction statement in the root document.
* @returns the direction statement if present
*/
private getDirectionStatement() {
return this.rootDoc.find((doc): doc is DirectionStmt => doc.stmt === STMT_DIRECTION);
}
getDirection() {
return this.getDirectionStatement()?.value ?? DEFAULT_DIAGRAM_DIRECTION;
}
setDirection(dir: DirectionStmt['value']) {
const doc = this.getDirectionStatement();
if (doc) {
doc.value = dir;
} else {
this.rootDoc.unshift({ stmt: STMT_DIRECTION, value: dir });
}
}
trimColon(str: string) {
return str.startsWith(':') ? str.slice(1).trim() : str.trim();
}
getData() {
const config = getConfig();
return {
nodes: this.nodes,
edges: this.edges,
other: {},
config,
direction: getDir(this.getRootDocV2()),
};
}
getConfig() {
return getConfig().state;
}
getAccTitle = getAccTitle;
setAccTitle = setAccTitle;
getAccDescription = getAccDescription;
setAccDescription = setAccDescription;
setDiagramTitle = setDiagramTitle;
getDiagramTitle = getDiagramTitle;
}

View File

@@ -5,6 +5,7 @@ import { StateDB } from './stateDb.js';
describe('state diagram V2, ', function () {
// TODO - these examples should be put into ./parser/stateDiagram.spec.js
describe('when parsing an info graph it', function () {
/** @type {StateDB} */
let stateDb;
beforeEach(function () {
stateDb = new StateDB(2);
@@ -347,6 +348,20 @@ describe('state diagram V2, ', function () {
`;
parser.parse(str);
expect(stateDb.getState('Active').note).toMatchInlineSnapshot(`
{
"position": "left of",
"text": "this is a short<br>note",
}
`);
expect(stateDb.getState('Inactive').note).toMatchInlineSnapshot(`
{
"position": "right of",
"text": "A note can also
be defined on
several lines",
}
`);
});
it('should handle multiline notes with different line breaks', function () {
const str = `stateDiagram-v2
@@ -357,6 +372,12 @@ describe('state diagram V2, ', function () {
`;
parser.parse(str);
expect(stateDb.getStates().get('State1').note).toMatchInlineSnapshot(`
{
"position": "right of",
"text": "Line1<br>Line2<br>Line3<br>Line4<br>Line5",
}
`);
});
it('should handle floating notes', function () {
const str = `stateDiagram-v2
@@ -367,15 +388,14 @@ describe('state diagram V2, ', function () {
parser.parse(str);
});
it('should handle floating notes', function () {
const str = `stateDiagram-v2\n
const str = `stateDiagram-v2
state foo
note "This is a floating note" as N1
`;
parser.parse(str);
});
it('should handle notes for composite (nested) states', function () {
const str = `stateDiagram-v2\n
const str = `stateDiagram-v2
[*] --> NotShooting
state "Not Shooting State" as NotShooting {
@@ -390,6 +410,12 @@ describe('state diagram V2, ', function () {
`;
parser.parse(str);
expect(stateDb.getState('NotShooting').note).toMatchInlineSnapshot(`
{
"position": "right of",
"text": "This is a note on a composite state",
}
`);
});
it('A composite state should be able to link to itself', () => {

View File

@@ -13,15 +13,17 @@ export const setConf = function (cnf) {
};
const actors = {};
let maxWidth = 0;
/** @param diagram - The diagram to draw to. */
function drawActorLegend(diagram) {
const conf = getConfig().journey;
// Draw the actors
const maxLabelWidth = conf.maxLabelWidth;
maxWidth = 0;
let yPos = 60;
Object.keys(actors).forEach((person) => {
const colour = actors[person].color;
const circleData = {
cx: 20,
cy: yPos,
@@ -32,25 +34,97 @@ function drawActorLegend(diagram) {
};
svgDraw.drawCircle(diagram, circleData);
const labelData = {
x: 40,
y: yPos + 7,
fill: '#666',
text: person,
textMargin: conf.boxTextMargin | 5,
};
svgDraw.drawText(diagram, labelData);
// First, measure the full text width without wrapping.
let measureText = diagram.append('text').attr('visibility', 'hidden').text(person);
const fullTextWidth = measureText.node().getBoundingClientRect().width;
measureText.remove();
yPos += 20;
let lines = [];
// If the text is naturally within the max width, use it as a single line.
if (fullTextWidth <= maxLabelWidth) {
lines = [person];
} else {
// Otherwise, wrap the text using the knuth-plass algorithm.
const words = person.split(' '); // Split the text into words.
let currentLine = '';
measureText = diagram.append('text').attr('visibility', 'hidden');
words.forEach((word) => {
// check the width of the line with the new word.
const testLine = currentLine ? `${currentLine} ${word}` : word;
measureText.text(testLine);
const textWidth = measureText.node().getBoundingClientRect().width;
if (textWidth > maxLabelWidth) {
// If adding the new word exceeds max width, push the current line.
if (currentLine) {
lines.push(currentLine);
}
currentLine = word; // Start a new line with the current word.
// If the word itself is too long, break it with a hyphen.
measureText.text(word);
if (measureText.node().getBoundingClientRect().width > maxLabelWidth) {
let brokenWord = '';
for (const char of word) {
brokenWord += char;
measureText.text(brokenWord + '-');
if (measureText.node().getBoundingClientRect().width > maxLabelWidth) {
// Push the broken part with a hyphen.
lines.push(brokenWord.slice(0, -1) + '-');
brokenWord = char;
}
}
currentLine = brokenWord;
}
} else {
// If the line with the new word fits, add the new word to the current line.
currentLine = testLine;
}
});
// Push the last line.
if (currentLine) {
lines.push(currentLine);
}
measureText.remove(); // Remove the text element used for measuring.
}
lines.forEach((line, index) => {
const labelData = {
x: 40,
y: yPos + 7 + index * 20,
fill: '#666',
text: line,
textMargin: conf.boxTextMargin ?? 5,
};
// Draw the text and measure the width.
const textElement = svgDraw.drawText(diagram, labelData);
const lineWidth = textElement.node().getBoundingClientRect().width;
// Use conf.leftMargin as the initial spacing baseline,
// but expand maxWidth if the line is wider.
if (lineWidth > maxWidth && lineWidth > conf.leftMargin - lineWidth) {
maxWidth = lineWidth;
}
});
yPos += Math.max(20, lines.length * 20);
});
}
// TODO: Cleanup?
const conf = getConfig().journey;
const LEFT_MARGIN = conf.leftMargin;
let leftMargin = 0;
export const draw = function (text, id, version, diagObj) {
const conf = getConfig().journey;
const configObject = getConfig();
const titleColor = configObject.journey.titleColor;
const titleFontSize = configObject.journey.titleFontSize;
const titleFontFamily = configObject.journey.titleFontFamily;
const securityLevel = getConfig().securityLevel;
const securityLevel = configObject.securityLevel;
// Handle root and Document for when rendering in sandbox mode
let sandboxElement;
if (securityLevel === 'sandbox') {
@@ -84,7 +158,8 @@ export const draw = function (text, id, version, diagObj) {
});
drawActorLegend(diagram);
bounds.insert(0, 0, LEFT_MARGIN, Object.keys(actors).length * 50);
leftMargin = conf.leftMargin + maxWidth;
bounds.insert(0, 0, leftMargin, Object.keys(actors).length * 50);
drawTasks(diagram, tasks, 0);
const box = bounds.getBounds();
@@ -92,23 +167,25 @@ export const draw = function (text, id, version, diagObj) {
diagram
.append('text')
.text(title)
.attr('x', LEFT_MARGIN)
.attr('font-size', '4ex')
.attr('x', leftMargin)
.attr('font-size', titleFontSize)
.attr('font-weight', 'bold')
.attr('y', 25);
.attr('y', 25)
.attr('fill', titleColor)
.attr('font-family', titleFontFamily);
}
const height = box.stopy - box.starty + 2 * conf.diagramMarginY;
const width = LEFT_MARGIN + box.stopx + 2 * conf.diagramMarginX;
const width = leftMargin + box.stopx + 2 * conf.diagramMarginX;
configureSvgSize(diagram, height, width, conf.useMaxWidth);
// Draw activity line
diagram
.append('line')
.attr('x1', LEFT_MARGIN)
.attr('x1', leftMargin)
.attr('y1', conf.height * 4) // One section head + one task + margins
.attr('x2', width - LEFT_MARGIN - 4) // Subtract stroke width so arrow point is retained
.attr('x2', width - leftMargin - 4) // Subtract stroke width so arrow point is retained
.attr('y2', conf.height * 4)
.attr('stroke-width', 4)
.attr('stroke', 'black')
@@ -234,7 +311,7 @@ export const drawTasks = function (diagram, tasks, verticalPos) {
}
const section = {
x: i * conf.taskMargin + i * conf.width + LEFT_MARGIN,
x: i * conf.taskMargin + i * conf.width + leftMargin,
y: 50,
text: task.section,
fill,
@@ -258,7 +335,7 @@ export const drawTasks = function (diagram, tasks, verticalPos) {
}, {});
// Add some rendering data to the object
task.x = i * conf.taskMargin + i * conf.width + LEFT_MARGIN;
task.x = i * conf.taskMargin + i * conf.width + leftMargin;
task.y = taskPos;
task.width = conf.diagramMarginX;
task.height = conf.diagramMarginY;

View File

@@ -93,6 +93,7 @@ export interface XYChartConfig {
titleFontSize: number;
titlePadding: number;
showTitle: boolean;
showDataLabel: boolean;
xAxis: XYChartAxisConfig;
yAxis: XYChartAxisConfig;
chartOrientation: 'vertical' | 'horizontal';

View File

@@ -195,6 +195,10 @@ function getChartConfig() {
return xyChartConfig;
}
function getXYChartData() {
return xyChartData;
}
const clear = function () {
commonClear();
plotIndex = 0;
@@ -226,4 +230,5 @@ export default {
setTmpSVGG,
getChartThemeConfig,
getChartConfig,
getXYChartData,
};

View File

@@ -14,6 +14,7 @@ export const draw = (txt: string, id: string, _version: string, diagObj: Diagram
const db = diagObj.db as typeof XYChartDB;
const themeConfig = db.getChartThemeConfig();
const chartConfig = db.getChartConfig();
const labelData = db.getXYChartData().plots[0].data.map((data) => data[1]);
function getDominantBaseLine(horizontalPos: TextVerticalPos) {
return horizontalPos === 'top' ? 'text-before-edge' : 'middle';
}
@@ -49,6 +50,16 @@ export const draw = (txt: string, id: string, _version: string, diagObj: Diagram
const groups: Record<string, any> = {};
interface BarItem {
data: {
x: number;
y: number;
width: number;
height: number;
};
label: string;
}
function getGroup(gList: string[]) {
let elem = group;
let prefix = '';
@@ -87,6 +98,113 @@ export const draw = (txt: string, id: string, _version: string, diagObj: Diagram
.attr('fill', (data) => data.fill)
.attr('stroke', (data) => data.strokeFill)
.attr('stroke-width', (data) => data.strokeWidth);
if (chartConfig.showDataLabel) {
if (chartConfig.chartOrientation === 'horizontal') {
// Factor to approximate each character's width.
const charWidthFactor = 0.7;
// Filter out bars that have zero width or height.
const validItems = shape.data
.map((d, i) => ({ data: d, label: labelData[i].toString() }))
.filter((item) => item.data.width > 0 && item.data.height > 0);
// Helper function to check if the text fits horizontally with a 10px right margin.
function fitsHorizontally(item: BarItem, fontSize: number): boolean {
const { data, label } = item;
// Approximate the text width.
const textWidth: number = fontSize * label.length * charWidthFactor;
// The available width is the bar's width minus a 10px right margin.
return textWidth <= data.width - 10;
}
// For each valid bar, start with an initial candidate font size (70% of the bar's height),
// then reduce it until the text fits horizontally.
const candidateFontSizes = validItems.map((item) => {
const { data } = item;
let fontSize = data.height * 0.7;
// Decrease fontSize until the text fits horizontally.
while (!fitsHorizontally(item, fontSize) && fontSize > 0) {
fontSize -= 1;
}
return fontSize;
});
// Choose the smallest candidate font size across all valid bars for uniformity.
const uniformFontSize = Math.floor(Math.min(...candidateFontSizes));
shapeGroup
.selectAll('text')
.data(validItems)
.enter()
.append('text')
.attr('x', (item) => item.data.x + item.data.width - 10)
.attr('y', (item) => item.data.y + item.data.height / 2)
.attr('text-anchor', 'end')
.attr('dominant-baseline', 'middle')
.attr('fill', 'black')
.attr('font-size', `${uniformFontSize}px`)
.text((item) => item.label);
} else {
const yOffset = 10;
// filter out bars that have zero width or height.
const validItems = shape.data
.map((d, i) => ({ data: d, label: labelData[i].toString() }))
.filter((item) => item.data.width > 0 && item.data.height > 0);
// Helper function that checks if the text with a given fontSize fits within the bar boundaries.
function fitsInBar(item: BarItem, fontSize: number, yOffset: number): boolean {
const { data, label } = item;
const charWidthFactor = 0.7;
const textWidth = fontSize * label.length * charWidthFactor;
// Compute horizontal boundaries using the center.
const centerX = data.x + data.width / 2;
const leftEdge = centerX - textWidth / 2;
const rightEdge = centerX + textWidth / 2;
// Check that text doesn't overflow horizontally.
const horizontalFits = leftEdge >= data.x && rightEdge <= data.x + data.width;
// For vertical placement, we use 'dominant-baseline: hanging' so that y marks the top of the text.
// Thus, the bottom edge is y + yOffset + fontSize.
const verticalFits = data.y + yOffset + fontSize <= data.y + data.height;
return horizontalFits && verticalFits;
}
// For each valid item, start with a candidate font size based on the width,
// then reduce it until the text fits within both the horizontal and vertical boundaries.
const candidateFontSizes = validItems.map((item) => {
const { data, label } = item;
let fontSize = data.width / (label.length * 0.7);
// Decrease the font size until the text fits or fontSize reaches 0.
while (!fitsInBar(item, fontSize, yOffset) && fontSize > 0) {
fontSize -= 1;
}
return fontSize;
});
// Choose the smallest candidate across all valid bars for uniformity.
const uniformFontSize = Math.floor(Math.min(...candidateFontSizes));
// Render text only for valid items.
shapeGroup
.selectAll('text')
.data(validItems)
.enter()
.append('text')
.attr('x', (item) => item.data.x + item.data.width / 2)
.attr('y', (item) => item.data.y + yOffset)
.attr('text-anchor', 'middle')
.attr('dominant-baseline', 'hanging')
.attr('fill', 'black')
.attr('font-size', `${uniformFontSize}px`)
.text((item) => item.label);
}
}
break;
case 'text':
shapeGroup

View File

@@ -75,7 +75,7 @@ When deployed within code, init is called before the graph/diagram description.
**for example**:
```mermaid
```mermaid-example
%%{init: {"theme": "default", "logLevel": 1 }}%%
graph LR
a-->b

View File

@@ -88,7 +88,7 @@ Here the directive declaration will set the `logLevel` to `debug` and the `theme
Note: You can use 'init' or 'initialize' as both are acceptable as init directives. Also note that `%%init%%` and `%%initialize%%` directives will be grouped together after they are parsed.
```mermaid
```mermaid-example
%%{init: { 'logLevel': 'debug', 'theme': 'forest' } }%%
%%{initialize: { 'logLevel': 'fatal', "theme":'dark', 'startOnLoad': true } }%%
...

View File

@@ -10,7 +10,7 @@ Note that at the moment, the only supported diagrams are below:
### Flowcharts
```mermaid
```mermaid-example
graph LR
A["$$x^2$$"] -->|"$$\sqrt{x+3}$$"| B("$$\frac{1}{2}$$")
A -->|"$$\overbrace{a+b+c}^{\text{note}}$$"| C("$$\pi r^2$$")
@@ -20,7 +20,7 @@ Note that at the moment, the only supported diagrams are below:
### Sequence
```mermaid
```mermaid-example
sequenceDiagram
autonumber
participant 1 as $$\alpha$$

View File

@@ -41,12 +41,6 @@ Example of `init` directive setting the `theme` to `forest`:
a --> b
```
```mermaid
%%{init: {'theme':'forest'}}%%
graph TD
a --> b
```
> **Reminder**: the only theme that can be customized is the `base` theme. The following section covers how to use `themeVariables` for customizations.
## Customizing Themes with `themeVariables`
@@ -91,36 +85,6 @@ Example of modifying `themeVariables` using the `init` directive:
end
```
```mermaid
%%{
init: {
'theme': 'base',
'themeVariables': {
'primaryColor': '#BB2528',
'primaryTextColor': '#fff',
'primaryBorderColor': '#7C0000',
'lineColor': '#F8B229',
'secondaryColor': '#006100',
'tertiaryColor': '#fff'
}
}
}%%
graph TD
A[Christmas] -->|Get money| B(Go shopping)
B --> C{Let me think}
B --> G[/Another/]
C ==>|One| D[Laptop]
C -->|Two| E[iPhone]
C -->|Three| F[fa:fa-car Car]
subgraph section
C
D
E
F
G
end
```
## Color and Color Calculation
To ensure diagram readability, the default value of certain variables is calculated or derived from other variables. For example, `primaryBorderColor` is derived from the `primaryColor` variable. So if the `primaryColor` variable is customized, Mermaid will adjust `primaryBorderColor` automatically. Adjustments can mean a color inversion, a hue change, a darkening/lightening by 10%, etc.

View File

@@ -35,6 +35,7 @@ To add an integration to this list, see the [Integrations - create page](./integ
- [Mermaid Charts & Diagrams for Jira](https://marketplace.atlassian.com/apps/1224537/)
- [Mermaid for Jira Cloud - Draw UML diagrams easily](https://marketplace.atlassian.com/apps/1223053/mermaid-for-jira-cloud-draw-uml-diagrams-easily?hosting=cloud&tab=overview)
- [CloudScript.io Mermaid Addon](https://marketplace.atlassian.com/apps/1219878/cloudscript-io-mermaid-addon?hosting=cloud&tab=overview)
- [Mermaid plus for Confluence](https://marketplace.atlassian.com/apps/1236814/mermaid-plus-for-confluence?hosting=cloud&tab=overview)
- [Azure Devops](https://learn.microsoft.com/en-us/azure/devops/project/wiki/markdown-guidance?view=azure-devops#add-mermaid-diagrams-to-a-wiki-page) ✅
- [Deepdwn](https://billiam.itch.io/deepdwn) ✅
- [Doctave](https://www.doctave.com/) ✅
@@ -262,7 +263,5 @@ Communication tools and platforms
- [reveal.js-mermaid-plugin](https://github.com/ludwick/reveal.js-mermaid-plugin)
- [Reveal CK](https://github.com/jedcn/reveal-ck)
- [reveal-ck-mermaid-plugin](https://github.com/tmtm/reveal-ck-mermaid-plugin)
- [mermaid-isomorphic](https://github.com/remcohaszing/mermaid-isomorphic)
- [mermaid-server: Generate diagrams using a HTTP request](https://github.com/TomWright/mermaid-server)
<!--- cspell:ignore Blazorade HueHive --->

View File

@@ -41,7 +41,7 @@ In the `Code` panel, write or edit Mermaid code, and instantly `Preview` the ren
Here is an example of Mermaid code and its rendered result:
```mermaid
```mermaid-example
graph TD
A[Enter Chart Definition] --> B(Preview)
B --> C{decide}

View File

@@ -83,7 +83,7 @@ Mermaid offers a variety of styles or “looks” for your diagrams, allowing yo
You can select a look by adding the look parameter in the metadata section of your Mermaid diagram code. Heres an example:
```mermaid
```mermaid-example
---
config:
look: handDrawn
@@ -108,7 +108,7 @@ In addition to customizing the look of your diagrams, Mermaid Chart now allows y
You can specify the layout algorithm directly in the metadata section of your Mermaid diagram code. Heres an example:
```mermaid
```mermaid-example
---
config:
layout: elk

View File

@@ -17,7 +17,7 @@
},
"dependencies": {
"@mdi/font": "^7.4.47",
"@vueuse/core": "^12.7.0",
"@vueuse/core": "^13.1.0",
"font-awesome": "^4.7.0",
"jiti": "^2.4.2",
"mermaid": "workspace:^",
@@ -26,7 +26,7 @@
"devDependencies": {
"@iconify-json/carbon": "^1.1.37",
"@unocss/reset": "^66.0.0",
"@vite-pwa/vitepress": "^0.5.3",
"@vite-pwa/vitepress": "^1.0.0",
"@vitejs/plugin-vue": "^5.0.5",
"fast-glob": "^3.3.3",
"https-localhost": "^4.7.1",
@@ -34,7 +34,7 @@
"unocss": "^66.0.0",
"unplugin-vue-components": "^28.4.0",
"vite": "^6.1.1",
"vite-plugin-pwa": "^0.21.1",
"vite-plugin-pwa": "^1.0.0",
"vitepress": "1.6.3",
"workbox-window": "^7.3.0"
}

View File

@@ -7,7 +7,7 @@ outline: 'deep' # shows all h3 headings in outline in Vitepress
## Introduction to Block Diagrams
```mermaid
```mermaid-example
block-beta
columns 1
db(("DB"))

View File

@@ -248,7 +248,7 @@ classE o-- classF : aggregation
Relations can logically represent an N:M association:
```mermaid
```mermaid-example
classDiagram
Animal <|--|> Zebra
```

View File

@@ -141,7 +141,7 @@ sequenceDiagram
## A commit flow diagram.
```mermaid
```mermaid-example
gitGraph:
commit "Ashish"
branch newbranch

View File

@@ -721,7 +721,7 @@ To give an edge an ID, prepend the edge syntax with the ID followed by an `@` ch
```mermaid
flowchart LR
A e1@> B
A e1@--> B
```
In this example, `e1` is the ID of the edge connecting `A` to `B`. You can then use this ID in later definitions or style statements, just like with nodes.
@@ -746,7 +746,7 @@ In the initial version, two animation speeds are supported: `fast` and `slow`. S
```mermaid
flowchart LR
A e1@> B
A e1@--> B
e1@{ animation: fast }
```
@@ -758,7 +758,7 @@ You can also animate edges by assigning a class to them and then defining animat
```mermaid
flowchart LR
A e1@> B
A e1@--> B
classDef animate stroke-dasharray: 9,5,stroke-dashoffset: 900,animation: dash 25s linear infinite;
class e1 animate
```

View File

@@ -259,7 +259,7 @@ gantt
The compact mode allows you to display multiple tasks in the same row. Compact mode can be enabled for a gantt chart by setting the display mode of the graph via preceding YAML settings.
```mermaid
```mermaid-example
---
displayMode: compact
---

View File

@@ -290,7 +290,13 @@ Sometimes you may want to hide the branch names and lines from the diagram. You
Usage example:
```mermaid-example
%%{init: { 'logLevel': 'debug', 'theme': 'base', 'gitGraph': {'showBranches': false}} }%%
---
config:
logLevel: 'debug'
theme: 'base'
gitGraph:
showBranches: false
---
gitGraph
commit
branch hotfix
@@ -346,7 +352,13 @@ You can change the layout of the commit labels by using the `rotateCommitLabel`
Usage example: Rotated commit labels
```mermaid-example
%%{init: { 'logLevel': 'debug', 'theme': 'base', 'gitGraph': {'rotateCommitLabel': true}} }%%
---
config:
logLevel: 'debug'
theme: 'base'
gitGraph:
rotateCommitLabel: true
---
gitGraph
commit id: "feat(api): ..."
commit id: "a"
@@ -367,7 +379,13 @@ gitGraph
Usage example: Horizontal commit labels
```mermaid-example
%%{init: { 'logLevel': 'debug', 'theme': 'base', 'gitGraph': {'rotateCommitLabel': false}} }%%
---
config:
logLevel: 'debug'
theme: 'base'
gitGraph:
rotateCommitLabel: false
---
gitGraph
commit id: "feat(api): ..."
commit id: "a"
@@ -392,7 +410,14 @@ Sometimes you may want to hide the commit labels from the diagram. You can do th
Usage example:
```mermaid-example
%%{init: { 'logLevel': 'debug', 'theme': 'base', 'gitGraph': {'showBranches': false,'showCommitLabel': false}} }%%
---
config:
logLevel: 'debug'
theme: 'base'
gitGraph:
showBranches: false
showCommitLabel: false
---
gitGraph
commit
branch hotfix
@@ -444,7 +469,15 @@ Sometimes you may want to customize the name of the main/default branch. You can
Usage example:
```mermaid-example
%%{init: { 'logLevel': 'debug', 'theme': 'base', 'gitGraph': {'showBranches': true, 'showCommitLabel':true,'mainBranchName': 'MetroLine1'}} }%%
---
config:
logLevel: 'debug'
theme: 'base'
gitGraph:
showBranches: true
showCommitLabel: true
mainBranchName: 'MetroLine1'
---
gitGraph
commit id:"NewYork"
commit id:"Dallas"
@@ -486,7 +519,14 @@ To fully control the order of all the branches, you must define `order` for all
Usage example:
```mermaid-example
%%{init: { 'logLevel': 'debug', 'theme': 'base', 'gitGraph': {'showBranches': true, 'showCommitLabel':true}} }%%
---
config:
logLevel: 'debug'
theme: 'base'
gitGraph:
showBranches: true
showCommitLabel: true
---
gitGraph
commit
branch test1 order: 3
@@ -500,7 +540,15 @@ Look at the diagram, all the branches are following the order defined.
Usage example:
```mermaid-example
%%{init: { 'logLevel': 'debug', 'theme': 'base', 'gitGraph': {'showBranches': true, 'showCommitLabel':true,'mainBranchOrder': 2}} }%%
---
config:
logLevel: 'debug'
theme: 'base'
gitGraph:
showBranches: true
showCommitLabel: true
mainBranchOrder: 2
---
gitGraph
commit
branch test1 order: 3
@@ -652,7 +700,11 @@ Let's put them to use, and see how our sample diagram looks in different themes:
### Base Theme
```mermaid-example
%%{init: { 'logLevel': 'debug', 'theme': 'base' } }%%
---
config:
logLevel: 'debug'
theme: 'base'
---
gitGraph
commit
branch hotfix
@@ -700,7 +752,11 @@ Let's put them to use, and see how our sample diagram looks in different themes:
### Forest Theme
```mermaid-example
%%{init: { 'logLevel': 'debug', 'theme': 'forest' } }%%
---
config:
logLevel: 'debug'
theme: 'forest'
---
gitGraph
commit
branch hotfix
@@ -748,7 +804,11 @@ Let's put them to use, and see how our sample diagram looks in different themes:
### Default Theme
```mermaid-example
%%{init: { 'logLevel': 'debug', 'theme': 'default' } }%%
---
config:
logLevel: 'debug'
theme: 'default'
---
gitGraph
commit type:HIGHLIGHT
branch hotfix
@@ -796,7 +856,11 @@ Let's put them to use, and see how our sample diagram looks in different themes:
### Dark Theme
```mermaid-example
%%{init: { 'logLevel': 'debug', 'theme': 'dark' } }%%
---
config:
logLevel: 'debug'
theme: 'dark'
---
gitGraph
commit
branch hotfix
@@ -844,7 +908,11 @@ Let's put them to use, and see how our sample diagram looks in different themes:
### Neutral Theme
```mermaid-example
%%{init: { 'logLevel': 'debug', 'theme': 'neutral' } }%%
---
config:
logLevel: 'debug'
theme: 'neutral'
---
gitGraph
commit
branch hotfix
@@ -898,7 +966,11 @@ For understanding let us take a sample diagram with theme `default`, the default
See how the default theme is used to set the colors for the branches:
```mermaid-example
%%{init: { 'logLevel': 'debug', 'theme': 'default' } }%%
---
config:
logLevel: 'debug'
theme: 'default'
---
gitGraph
commit
branch develop
@@ -929,16 +1001,20 @@ Example:
Now let's override the default values for the `git0` to `git3` variables:
```mermaid-example
%%{init: { 'logLevel': 'debug', 'theme': 'default' , 'themeVariables': {
'git0': '#ff0000',
'git1': '#00ff00',
'git2': '#0000ff',
'git3': '#ff00ff',
'git4': '#00ffff',
'git5': '#ffff00',
'git6': '#ff00ff',
'git7': '#00ffff'
} } }%%
---
config:
logLevel: 'debug'
theme: 'default'
themeVariables:
'git0': '#ff0000'
'git1': '#00ff00'
'git2': '#0000ff'
'git3': '#ff00ff'
'git4': '#00ffff'
'git5': '#ffff00'
'git6': '#ff00ff'
'git7': '#00ffff'
---
gitGraph
commit
branch develop
@@ -965,18 +1041,22 @@ Lets see how the default theme is used to set the colors for the branch labels:
Now let's override the default values for the `gitBranchLabel0` to `gitBranchLabel2` variables:
```mermaid-example
%%{init: { 'logLevel': 'debug', 'theme': 'default' , 'themeVariables': {
'gitBranchLabel0': '#ffffff',
'gitBranchLabel1': '#ffffff',
'gitBranchLabel2': '#ffffff',
'gitBranchLabel3': '#ffffff',
'gitBranchLabel4': '#ffffff',
'gitBranchLabel5': '#ffffff',
'gitBranchLabel6': '#ffffff',
'gitBranchLabel7': '#ffffff',
'gitBranchLabel8': '#ffffff',
'gitBranchLabel9': '#ffffff'
} } }%%
---
config:
logLevel: 'debug'
theme: 'default'
themeVariables:
'gitBranchLabel0': '#ffffff'
'gitBranchLabel1': '#ffffff'
'gitBranchLabel2': '#ffffff'
'gitBranchLabel3': '#ffffff'
'gitBranchLabel4': '#ffffff'
'gitBranchLabel5': '#ffffff'
'gitBranchLabel6': '#ffffff'
'gitBranchLabel7': '#ffffff'
'gitBranchLabel8': '#ffffff'
'gitBranchLabel9': '#ffffff'
---
gitGraph
checkout main
branch branch1
@@ -1002,10 +1082,14 @@ Example:
Now let's override the default values for the `commitLabelColor` to `commitLabelBackground` variables:
```mermaid-example
%%{init: { 'logLevel': 'debug', 'theme': 'default' , 'themeVariables': {
'commitLabelColor': '#ff0000',
'commitLabelBackground': '#00ff00'
} } }%%
---
config:
logLevel: 'debug'
theme: 'default'
themeVariables:
commitLabelColor: '#ff0000'
commitLabelBackground: '#00ff00'
---
gitGraph
commit
branch develop
@@ -1031,11 +1115,15 @@ Example:
Now let's override the default values for the `commitLabelFontSize` variable:
```mermaid-example
%%{init: { 'logLevel': 'debug', 'theme': 'default' , 'themeVariables': {
'commitLabelColor': '#ff0000',
'commitLabelBackground': '#00ff00',
'commitLabelFontSize': '16px'
} } }%%
---
config:
logLevel: 'debug'
theme: 'default'
themeVariables:
commitLabelColor: '#ff0000'
commitLabelBackground: '#00ff00'
commitLabelFontSize: '16px'
---
gitGraph
commit
branch develop
@@ -1061,11 +1149,15 @@ Example:
Now let's override the default values for the `tagLabelFontSize` variable:
```mermaid-example
%%{init: { 'logLevel': 'debug', 'theme': 'default' , 'themeVariables': {
'commitLabelColor': '#ff0000',
'commitLabelBackground': '#00ff00',
'tagLabelFontSize': '16px'
} } }%%
---
config:
logLevel: 'debug'
theme: 'default'
themeVariables:
commitLabelColor: '#ff0000'
commitLabelBackground: '#00ff00'
tagLabelFontSize: '16px'
---
gitGraph
commit
branch develop
@@ -1090,11 +1182,15 @@ Example:
Now let's override the default values for the `tagLabelColor`, `tagLabelBackground` and to `tagLabelBorder` variables:
```mermaid-example
%%{init: { 'logLevel': 'debug', 'theme': 'default' , 'themeVariables': {
'tagLabelColor': '#ff0000',
'tagLabelBackground': '#00ff00',
'tagLabelBorder': '#0000ff'
} } }%%
---
config:
logLevel: 'debug'
theme: 'default'
themeVariables:
tagLabelColor: '#ff0000'
tagLabelBackground: '#00ff00'
tagLabelBorder: '#0000ff'
---
gitGraph
commit
branch develop
@@ -1121,9 +1217,13 @@ Example:
Now let's override the default values for the `git0` to `git3` variables:
```mermaid-example
%%{init: { 'logLevel': 'debug', 'theme': 'default' , 'themeVariables': {
'gitInv0': '#ff0000'
} } }%%
---
config:
logLevel: 'debug'
theme: 'default'
themeVariables:
'gitInv0': '#ff0000'
---
gitGraph
commit
branch develop

View File

@@ -442,7 +442,7 @@ sequenceDiagram
Comments can be entered within a sequence diagram, which will be ignored by the parser. Comments need to be on their own line, and must be prefaced with `%%` (double percent signs). Any text after the start of the comment to the next newline will be treated as a comment, including any diagram syntax
```mermaid
```mermaid-example
sequenceDiagram
Alice->>John: Hello John, how are you?
%% this is a comment

View File

@@ -95,17 +95,18 @@ xychart-beta
## Chart Configurations
| Parameter | Description | Default value |
| ------------------------ | ---------------------------------------------- | :-----------: |
| width | Width of the chart | 700 |
| height | Height of the chart | 500 |
| titlePadding | Top and Bottom padding of the title | 10 |
| titleFontSize | Title font size | 20 |
| showTitle | Title to be shown or not | true |
| xAxis | xAxis configuration | AxisConfig |
| yAxis | yAxis configuration | AxisConfig |
| chartOrientation | 'vertical' or 'horizontal' | 'vertical' |
| plotReservedSpacePercent | Minimum space plots will take inside the chart | 50 |
| Parameter | Description | Default value |
| ------------------------ | ------------------------------------------------------------- | :-----------: |
| width | Width of the chart | 700 |
| height | Height of the chart | 500 |
| titlePadding | Top and Bottom padding of the title | 10 |
| titleFontSize | Title font size | 20 |
| showTitle | Title to be shown or not | true |
| xAxis | xAxis configuration | AxisConfig |
| yAxis | yAxis configuration | AxisConfig |
| chartOrientation | 'vertical' or 'horizontal' | 'vertical' |
| plotReservedSpacePercent | Minimum space plots will take inside the chart | 50 |
| showDataLabel | Should show the value corresponding to the bar within the bar | false |
### AxisConfig
@@ -152,6 +153,7 @@ config:
xyChart:
width: 900
height: 600
showDataLabel: true
themeVariables:
xyChart:
titleColor: "#ff0000"

View File

@@ -31,6 +31,7 @@ vi.mock('./diagrams/xychart/xychartRenderer.js');
vi.mock('./diagrams/requirement/requirementRenderer.js');
vi.mock('./diagrams/sequence/sequenceRenderer.js');
vi.mock('./diagrams/radar/renderer.js');
vi.mock('./diagrams/architecture/architectureRenderer.js');
// -------------------------------------
@@ -799,6 +800,7 @@ graph TD;A--x|text including URL space|B;`)
{ textDiagramType: 'sequenceDiagram', expectedType: 'sequence' },
{ textDiagramType: 'stateDiagram-v2', expectedType: 'stateDiagram' },
{ textDiagramType: 'radar-beta', expectedType: 'radar' },
{ textDiagramType: 'architecture-beta', expectedType: 'architecture' },
];
describe('accessibility', () => {

View File

@@ -562,7 +562,7 @@ export const insertEdge = function (elem, edge, clusterDb, diagramType, startNod
}
let svgPath;
let linePath = lineFunction(lineData);
const edgeStyles = Array.isArray(edge.style) ? edge.style : [edge.style];
const edgeStyles = Array.isArray(edge.style) ? edge.style : edge.style ? [edge.style] : [];
let strokeColor = edgeStyles.find((style) => style?.startsWith('stroke:'));
if (edge.look === 'handDrawn') {

View File

@@ -1228,6 +1228,10 @@ $defs: # JSON Schema definition (maybe we should move these to a separate file)
type: number
default: 10
minimum: 0
showDataLabel:
description: Should show the value corresponding to the bar within the bar
type: boolean
default: false
showTitle:
description: Should show the chart title
type: boolean
@@ -1484,6 +1488,9 @@ $defs: # JSON Schema definition (maybe we should move these to a separate file)
- bottomMarginAdj
- useMaxWidth
- rightAngles
- titleColor
- titleFontFamily
- titleFontSize
properties:
diagramMarginX:
$ref: '#/$defs/C4DiagramConfig/properties/diagramMarginX'
@@ -1496,6 +1503,10 @@ $defs: # JSON Schema definition (maybe we should move these to a separate file)
type: integer
default: 150
minimum: 0
maxLabelWidth:
description: Maximum width of actor labels
type: integer
default: 360
width:
description: Width of actor boxes
type: integer
@@ -1584,6 +1595,18 @@ $defs: # JSON Schema definition (maybe we should move these to a separate file)
items:
type: string
default: ['#fff']
titleColor:
description: Color of the title text in Journey Diagrams
type: string
default: ''
titleFontFamily:
description: Font family to be used for the title text in Journey Diagrams
type: string
default: '"trebuchet ms", verdana, arial, sans-serif'
titleFontSize:
description: Font size to be used for the title text in Journey Diagrams
type: string
default: '4ex'
TimelineDiagramConfig:
# added by https://github.com/mermaid-js/mermaid/commit/0d5246fbc730bf15463d7183fe4400a1e2fc492c

View File

@@ -0,0 +1,2 @@
terminal ARCH_ICON: /\([\w-:]+\)/;
terminal ARCH_TITLE: /\[[\w ]+\]/;

View File

@@ -1,14 +1,15 @@
grammar Architecture
import "../common/common";
import "arch";
entry Architecture:
NEWLINE*
"architecture-beta"
(
NEWLINE* TitleAndAccessibilities
| NEWLINE* Statement*
| NEWLINE*
)
NEWLINE
| TitleAndAccessibilities
| Statement
)*
;
fragment Statement:
@@ -31,25 +32,21 @@ fragment Arrow:
;
Group:
'group' id=ARCH_ID icon=ARCH_ICON? title=ARCH_TITLE? ('in' in=ARCH_ID)? EOL
'group' id=ID icon=ARCH_ICON? title=ARCH_TITLE? ('in' in=ID)? EOL
;
Service:
'service' id=ARCH_ID (iconText=ARCH_TEXT_ICON | icon=ARCH_ICON)? title=ARCH_TITLE? ('in' in=ARCH_ID)? EOL
'service' id=ID (iconText=STRING | icon=ARCH_ICON)? title=ARCH_TITLE? ('in' in=ID)? EOL
;
Junction:
'junction' id=ARCH_ID ('in' in=ARCH_ID)? EOL
'junction' id=ID ('in' in=ID)? EOL
;
Edge:
lhsId=ARCH_ID lhsGroup?=ARROW_GROUP? Arrow rhsId=ARCH_ID rhsGroup?=ARROW_GROUP? EOL
lhsId=ID lhsGroup?=ARROW_GROUP? Arrow rhsId=ID rhsGroup?=ARROW_GROUP? EOL
;
terminal ARROW_DIRECTION: 'L' | 'R' | 'T' | 'B';
terminal ARCH_ID: /[\w]+/;
terminal ARCH_TEXT_ICON: /\("[^"]+"\)/;
terminal ARCH_ICON: /\([\w-:]+\)/;
terminal ARCH_TITLE: /\[[\w ]+\]/;
terminal ARROW_GROUP: /\{group\}/;
terminal ARROW_INTO: /<|>/;

View File

@@ -1,22 +1,35 @@
interface Common {
accDescr?: string;
accTitle?: string;
title?: string;
}
fragment TitleAndAccessibilities:
((accDescr=ACC_DESCR | accTitle=ACC_TITLE | title=TITLE) EOL)+
;
// Base terminals and fragments for common language constructs
// Terminal Precedence: Lazy to Greedy
// When imported, the terminals are considered after the terminals in the importing grammar
// Note: Hence, to add a terminal greedier than the common terminals, import it separately after the common import
fragment EOL returns string:
NEWLINE+ | EOF
;
terminal NEWLINE: /\r?\n/;
fragment TitleAndAccessibilities:
((accDescr=ACC_DESCR | accTitle=ACC_TITLE | title=TITLE) EOL)+
;
terminal BOOLEAN returns boolean: 'true' | 'false';
terminal ACC_DESCR: /[\t ]*accDescr(?:[\t ]*:([^\n\r]*?(?=%%)|[^\n\r]*)|\s*{([^}]*)})/;
terminal ACC_TITLE: /[\t ]*accTitle[\t ]*:(?:[^\n\r]*?(?=%%)|[^\n\r]*)/;
terminal TITLE: /[\t ]*title(?:[\t ][^\n\r]*?(?=%%)|[\t ][^\n\r]*|)/;
terminal FLOAT returns number: /[0-9]+\.[0-9]+(?!\.)/;
terminal INT returns number: /0|[1-9][0-9]*(?!\.)/;
terminal NUMBER returns number: FLOAT | INT;
terminal STRING returns string: /"([^"\\]|\\.)*"|'([^'\\]|\\.)*'/;
// Alphanumerics with underscores and dashes
// Must start with an alphanumeric or an underscore
// Cant end with a dash
terminal ID returns string: /[\w]([-\w]*\w)?/;
terminal NEWLINE: /\r?\n/;
hidden terminal WHITESPACE: /[\t ]+/;
hidden terminal YAML: /---[\t ]*\r?\n(?:[\S\s]*?\r?\n)?---(?:\r?\n|(?!\S))/;
hidden terminal DIRECTIVE: /[\t ]*%%{[\S\s]*?}%%(?:\r?\n|(?!\S))/;

View File

@@ -1,39 +1,15 @@
grammar GitGraph
interface Common {
accDescr?: string;
accTitle?: string;
title?: string;
}
fragment TitleAndAccessibilities:
((accDescr=ACC_DESCR | accTitle=ACC_TITLE | title=TITLE) EOL)+
;
fragment EOL returns string:
NEWLINE+ | EOF
;
terminal NEWLINE: /\r?\n/;
terminal ACC_DESCR: /[\t ]*accDescr(?:[\t ]*:([^\n\r]*?(?=%%)|[^\n\r]*)|\s*{([^}]*)})/;
terminal ACC_TITLE: /[\t ]*accTitle[\t ]*:(?:[^\n\r]*?(?=%%)|[^\n\r]*)/;
terminal TITLE: /[\t ]*title(?:[\t ][^\n\r]*?(?=%%)|[\t ][^\n\r]*|)/;
hidden terminal WHITESPACE: /[\t ]+/;
hidden terminal YAML: /---[\t ]*\r?\n(?:[\S\s]*?\r?\n)?---(?:\r?\n|(?!\S))/;
hidden terminal DIRECTIVE: /[\t ]*%%{[\S\s]*?}%%(?:\r?\n|(?!\S))/;
hidden terminal SINGLE_LINE_COMMENT: /[\t ]*%%[^\n\r]*/;
import "../common/common";
import "reference";
entry GitGraph:
NEWLINE*
('gitGraph' | 'gitGraph' ':' | 'gitGraph:' | ('gitGraph' Direction ':'))
NEWLINE*
(
NEWLINE*
(TitleAndAccessibilities |
statements+=Statement |
NEWLINE)*
)
NEWLINE
| TitleAndAccessibilities
| statements+=Statement
)*
;
Statement
@@ -56,12 +32,12 @@ Commit:
|'type:' type=('NORMAL' | 'REVERSE' | 'HIGHLIGHT')
)* EOL;
Branch:
'branch' name=(ID|STRING)
'branch' name=(REFERENCE|STRING)
('order:' order=INT)?
EOL;
Merge:
'merge' branch=(ID|STRING)
'merge' branch=(REFERENCE|STRING)
(
'id:' id=STRING
|'tag:' tags+=STRING
@@ -69,7 +45,7 @@ Merge:
)* EOL;
Checkout:
('checkout'|'switch') branch=(ID|STRING) EOL;
('checkout'|'switch') branch=(REFERENCE|STRING) EOL;
CherryPicking:
'cherry-pick'
@@ -78,10 +54,3 @@ CherryPicking:
|'tag:' tags+=STRING
|'parent:' parent=STRING
)* EOL;
terminal INT returns number: /[0-9]+(?=\s)/;
terminal ID returns string: /\w([-\./\w]*[-\w])?/;
terminal STRING: /"[^"]*"|'[^']*'/;

View File

@@ -0,0 +1,4 @@
// Alphanumerics with underscores, dashes, slashes, and dots
// Must start with an alphanumeric or an underscore
// Cant end with a dash, slash, or dot
terminal REFERENCE returns string: /\w([-\./\w]*[-\w])?/;

View File

@@ -12,7 +12,6 @@ export {
Commit,
Merge,
Statement,
isCommon,
isInfo,
isPacket,
isPacketBlock,

View File

@@ -5,15 +5,12 @@ entry Packet:
NEWLINE*
"packet-beta"
(
NEWLINE* TitleAndAccessibilities blocks+=PacketBlock*
| NEWLINE+ blocks+=PacketBlock+
| NEWLINE*
)
TitleAndAccessibilities
| blocks+=PacketBlock
| NEWLINE
)*
;
PacketBlock:
start=INT('-' end=INT)? ':' label=STRING EOL
;
terminal INT returns number: /0|[1-9][0-9]*/;
terminal STRING: /"[^"]*"|'[^']*'/;
;

View File

@@ -5,15 +5,12 @@ entry Pie:
NEWLINE*
"pie" showData?="showData"?
(
NEWLINE* TitleAndAccessibilities sections+=PieSection*
| NEWLINE+ sections+=PieSection+
| NEWLINE*
)
TitleAndAccessibilities
| sections+=PieSection
| NEWLINE
)*
;
PieSection:
label=PIE_SECTION_LABEL ":" value=PIE_SECTION_VALUE EOL
label=STRING ":" value=NUMBER EOL
;
terminal PIE_SECTION_LABEL: /"[^"]+"/;
terminal PIE_SECTION_VALUE returns number: /(0|[1-9][0-9]*)(\.[0-9]+)?/;

View File

@@ -1,31 +1,5 @@
grammar Radar
// import "../common/common";
// Note: The import statement breaks TitleAndAccessibilities probably because of terminal order definition
// TODO: May need to change the common.langium to fix this
interface Common {
accDescr?: string;
accTitle?: string;
title?: string;
}
fragment TitleAndAccessibilities:
((accDescr=ACC_DESCR | accTitle=ACC_TITLE | title=TITLE) EOL)+
;
fragment EOL returns string:
NEWLINE+ | EOF
;
terminal NEWLINE: /\r?\n/;
terminal ACC_DESCR: /[\t ]*accDescr(?:[\t ]*:([^\n\r]*?(?=%%)|[^\n\r]*)|\s*{([^}]*)})/;
terminal ACC_TITLE: /[\t ]*accTitle[\t ]*:(?:[^\n\r]*?(?=%%)|[^\n\r]*)/;
terminal TITLE: /[\t ]*title(?:[\t ][^\n\r]*?(?=%%)|[\t ][^\n\r]*|)/;
hidden terminal WHITESPACE: /[\t ]+/;
hidden terminal YAML: /---[\t ]*\r?\n(?:[\S\s]*?\r?\n)?---(?:\r?\n|(?!\S))/;
hidden terminal DIRECTIVE: /[\t ]*%%{[\S\s]*?}%%(?:\r?\n|(?!\S))/;
hidden terminal SINGLE_LINE_COMMENT: /[\t ]*%%[^\n\r]*/;
import "../common/common";
entry Radar:
NEWLINE*
@@ -76,14 +50,6 @@ Option:
| name='min' value=NUMBER
| name='graticule' value=GRATICULE
)
;
;
terminal NUMBER returns number: /(0|[1-9][0-9]*)(\.[0-9]+)?/;
terminal BOOLEAN returns boolean: 'true' | 'false';
terminal GRATICULE returns string: 'circle' | 'polygon';
terminal ID returns string: /[a-zA-Z_][a-zA-Z0-9\-_]*/;
terminal STRING: /"[^"]*"|'[^']*'/;
terminal GRATICULE returns string: 'circle' | 'polygon';

View File

@@ -0,0 +1,88 @@
import { describe, expect, it } from 'vitest';
import { Architecture } from '../src/language/index.js';
import { expectNoErrorsOrAlternatives, architectureParse as parse } from './test-util.js';
describe('architecture', () => {
describe('should handle architecture definition', () => {
it.each([
`architecture-beta`,
` architecture-beta `,
`\tarchitecture-beta\t`,
`
\tarchitecture-beta
`,
])('should handle regular architecture', (context: string) => {
const result = parse(context);
expectNoErrorsOrAlternatives(result);
expect(result.value.$type).toBe(Architecture);
});
});
describe('should handle TitleAndAccessibilities', () => {
it.each([
`architecture-beta title sample title`,
` architecture-beta title sample title `,
`\tarchitecture-beta\ttitle sample title\t`,
`architecture-beta
\ttitle sample title
`,
])('should handle regular architecture + title in same line', (context: string) => {
const result = parse(context);
expectNoErrorsOrAlternatives(result);
expect(result.value.$type).toBe(Architecture);
const { title } = result.value;
expect(title).toBe('sample title');
});
it.each([
`architecture-beta
title sample title`,
`architecture-beta
title sample title
`,
])('should handle regular architecture + title in next line', (context: string) => {
const result = parse(context);
expectNoErrorsOrAlternatives(result);
expect(result.value.$type).toBe(Architecture);
const { title } = result.value;
expect(title).toBe('sample title');
});
it('should handle regular architecture + title + accTitle + accDescr', () => {
const context = `architecture-beta
title sample title
accTitle: sample accTitle
accDescr: sample accDescr
`;
const result = parse(context);
expectNoErrorsOrAlternatives(result);
expect(result.value.$type).toBe(Architecture);
const { title, accTitle, accDescr } = result.value;
expect(title).toBe('sample title');
expect(accTitle).toBe('sample accTitle');
expect(accDescr).toBe('sample accDescr');
});
it('should handle regular architecture + title + accTitle + multi-line accDescr', () => {
const context = `architecture-beta
title sample title
accTitle: sample accTitle
accDescr {
sample accDescr
}
`;
const result = parse(context);
expectNoErrorsOrAlternatives(result);
expect(result.value.$type).toBe(Architecture);
const { title, accTitle, accDescr } = result.value;
expect(title).toBe('sample title');
expect(accTitle).toBe('sample accTitle');
expect(accDescr).toBe('sample accDescr');
});
});
});

View File

@@ -63,6 +63,12 @@ describe('Parsing Branch Statements', () => {
expect(branch.name).toBe('master');
});
it('should parse a branch name starting with numbers', () => {
const result = parse(`gitGraph\n commit\n branch 1.0.1\n`);
const branch = result.value.statements[1] as Branch;
expect(branch.name).toBe('1.0.1');
});
it('should parse a branch with an order property', () => {
const result = parse(`gitGraph\n commit\n branch feature order:1\n`);
const branch = result.value.statements[1] as Branch;

View File

@@ -4,226 +4,247 @@ import { Pie } from '../src/language/index.js';
import { expectNoErrorsOrAlternatives, pieParse as parse } from './test-util.js';
describe('pie', () => {
it.each([
`pie`,
` pie `,
`\tpie\t`,
`
describe('should handle pie definition with or without showData', () => {
it.each([
`pie`,
` pie `,
`\tpie\t`,
`
\tpie
`,
])('should handle regular pie', (context: string) => {
const result = parse(context);
expectNoErrorsOrAlternatives(result);
expect(result.value.$type).toBe(Pie);
});
])('should handle regular pie', (context: string) => {
const result = parse(context);
expectNoErrorsOrAlternatives(result);
expect(result.value.$type).toBe(Pie);
});
it.each([
`pie showData`,
` pie showData `,
`\tpie\tshowData\t`,
`
it.each([
`pie showData`,
` pie showData `,
`\tpie\tshowData\t`,
`
pie\tshowData
`,
])('should handle regular showData', (context: string) => {
const result = parse(context);
expectNoErrorsOrAlternatives(result);
expect(result.value.$type).toBe(Pie);
])('should handle regular showData', (context: string) => {
const result = parse(context);
expectNoErrorsOrAlternatives(result);
expect(result.value.$type).toBe(Pie);
const { showData } = result.value;
expect(showData).toBeTruthy();
const { showData } = result.value;
expect(showData).toBeTruthy();
});
});
describe('should handle TitleAndAccessibilities', () => {
describe('should handle TitleAndAccessibilities without showData', () => {
it.each([
`pie title sample title`,
` pie title sample title `,
`\tpie\ttitle sample title\t`,
`pie
\ttitle sample title
`,
])('should handle regular pie + title in same line', (context: string) => {
const result = parse(context);
expectNoErrorsOrAlternatives(result);
expect(result.value.$type).toBe(Pie);
it.each([
`pie title sample title`,
` pie title sample title `,
`\tpie\ttitle sample title\t`,
`pie
\ttitle sample title
`,
])('should handle regular pie + title in same line', (context: string) => {
const result = parse(context);
expectNoErrorsOrAlternatives(result);
expect(result.value.$type).toBe(Pie);
const { title } = result.value;
expect(title).toBe('sample title');
});
const { title } = result.value;
expect(title).toBe('sample title');
});
it.each([
`pie
title sample title`,
`pie
title sample title
`,
`pie
title sample title`,
`pie
title sample title
`,
])('should handle regular pie + title in different line', (context: string) => {
const result = parse(context);
expectNoErrorsOrAlternatives(result);
expect(result.value.$type).toBe(Pie);
const { title } = result.value;
expect(title).toBe('sample title');
});
it.each([
`pie showData title sample title`,
`pie showData title sample title
`,
])('should handle regular pie + showData + title', (context: string) => {
const result = parse(context);
expectNoErrorsOrAlternatives(result);
expect(result.value.$type).toBe(Pie);
const { showData, title } = result.value;
expect(showData).toBeTruthy();
expect(title).toBe('sample title');
});
it.each([
`pie showData
title sample title`,
`pie showData
title sample title
`,
`pie showData
title sample title`,
`pie showData
title sample title
`,
])('should handle regular showData + title in different line', (context: string) => {
const result = parse(context);
expectNoErrorsOrAlternatives(result);
expect(result.value.$type).toBe(Pie);
const { showData, title } = result.value;
expect(showData).toBeTruthy();
expect(title).toBe('sample title');
});
describe('sections', () => {
describe('normal', () => {
it.each([
`pie
title sample title`,
`pie
title sample title
`,
`pie
title sample title`,
`pie
title sample title
`,
])('should handle regular pie + title in different line', (context: string) => {
const result = parse(context);
expectNoErrorsOrAlternatives(result);
expect(result.value.$type).toBe(Pie);
const { title } = result.value;
expect(title).toBe('sample title');
});
});
describe('should handle TitleAndAccessibilities with showData', () => {
it.each([
`pie showData title sample title`,
`pie showData title sample title
`,
])('should handle regular pie + showData + title', (context: string) => {
const result = parse(context);
expectNoErrorsOrAlternatives(result);
expect(result.value.$type).toBe(Pie);
const { showData, title } = result.value;
expect(showData).toBeTruthy();
expect(title).toBe('sample title');
});
it.each([
`pie showData
title sample title`,
`pie showData
title sample title
`,
`pie showData
title sample title`,
`pie showData
title sample title
`,
])('should handle regular showData + title in different line', (context: string) => {
const result = parse(context);
expectNoErrorsOrAlternatives(result);
expect(result.value.$type).toBe(Pie);
const { showData, title } = result.value;
expect(showData).toBeTruthy();
expect(title).toBe('sample title');
});
});
});
describe('should handle sections', () => {
it.each([
`pie
"GitHub":100
"GitLab":50`,
`pie
`pie
"GitHub" : 100
"GitLab" : 50`,
`pie
`pie
"GitHub"\t:\t100
"GitLab"\t:\t50`,
`pie
`pie
\t"GitHub" \t : \t 100
\t"GitLab" \t : \t 50
`,
])('should handle regular sections', (context: string) => {
const result = parse(context);
expectNoErrorsOrAlternatives(result);
expect(result.value.$type).toBe(Pie);
])('should handle regular sections', (context: string) => {
const result = parse(context);
expectNoErrorsOrAlternatives(result);
expect(result.value.$type).toBe(Pie);
const { sections } = result.value;
expect(sections[0].label).toBe('GitHub');
expect(sections[0].value).toBe(100);
const { sections } = result.value;
expect(sections[0].label).toBe('GitHub');
expect(sections[0].value).toBe(100);
expect(sections[1].label).toBe('GitLab');
expect(sections[1].value).toBe(50);
});
expect(sections[1].label).toBe('GitLab');
expect(sections[1].value).toBe(50);
});
it('should handle sections with showData', () => {
const context = `pie showData
it('should handle sections with showData', () => {
const context = `pie showData
"GitHub": 100
"GitLab": 50`;
const result = parse(context);
expectNoErrorsOrAlternatives(result);
expect(result.value.$type).toBe(Pie);
const result = parse(context);
expectNoErrorsOrAlternatives(result);
expect(result.value.$type).toBe(Pie);
const { showData, sections } = result.value;
expect(showData).toBeTruthy();
const { showData, sections } = result.value;
expect(showData).toBeTruthy();
expect(sections[0].label).toBe('GitHub');
expect(sections[0].value).toBe(100);
expect(sections[0].label).toBe('GitHub');
expect(sections[0].value).toBe(100);
expect(sections[1].label).toBe('GitLab');
expect(sections[1].value).toBe(50);
});
expect(sections[1].label).toBe('GitLab');
expect(sections[1].value).toBe(50);
});
it('should handle sections with title', () => {
const context = `pie title sample wow
it('should handle sections with title', () => {
const context = `pie title sample wow
"GitHub": 100
"GitLab": 50`;
const result = parse(context);
expectNoErrorsOrAlternatives(result);
expect(result.value.$type).toBe(Pie);
const result = parse(context);
expectNoErrorsOrAlternatives(result);
expect(result.value.$type).toBe(Pie);
const { title, sections } = result.value;
expect(title).toBe('sample wow');
const { title, sections } = result.value;
expect(title).toBe('sample wow');
expect(sections[0].label).toBe('GitHub');
expect(sections[0].value).toBe(100);
expect(sections[0].label).toBe('GitHub');
expect(sections[0].value).toBe(100);
expect(sections[1].label).toBe('GitLab');
expect(sections[1].value).toBe(50);
});
expect(sections[1].label).toBe('GitLab');
expect(sections[1].value).toBe(50);
});
it('should handle sections with accTitle', () => {
const context = `pie accTitle: sample wow
it('should handle value with positive decimal', () => {
const context = `pie
"ash": 60.67
"bat": 40`;
const result = parse(context);
expectNoErrorsOrAlternatives(result);
expect(result.value.$type).toBe(Pie);
const { sections } = result.value;
expect(sections[0].label).toBe('ash');
expect(sections[0].value).toBe(60.67);
expect(sections[1].label).toBe('bat');
expect(sections[1].value).toBe(40);
});
it('should handle sections with accTitle', () => {
const context = `pie accTitle: sample wow
"GitHub": 100
"GitLab": 50`;
const result = parse(context);
expectNoErrorsOrAlternatives(result);
expect(result.value.$type).toBe(Pie);
const result = parse(context);
expectNoErrorsOrAlternatives(result);
expect(result.value.$type).toBe(Pie);
const { accTitle, sections } = result.value;
expect(accTitle).toBe('sample wow');
const { accTitle, sections } = result.value;
expect(accTitle).toBe('sample wow');
expect(sections[0].label).toBe('GitHub');
expect(sections[0].value).toBe(100);
expect(sections[0].label).toBe('GitHub');
expect(sections[0].value).toBe(100);
expect(sections[1].label).toBe('GitLab');
expect(sections[1].value).toBe(50);
});
expect(sections[1].label).toBe('GitLab');
expect(sections[1].value).toBe(50);
});
it('should handle sections with single line accDescr', () => {
const context = `pie accDescr: sample wow
it('should handle sections with single line accDescr', () => {
const context = `pie accDescr: sample wow
"GitHub": 100
"GitLab": 50`;
const result = parse(context);
expectNoErrorsOrAlternatives(result);
expect(result.value.$type).toBe(Pie);
const result = parse(context);
expectNoErrorsOrAlternatives(result);
expect(result.value.$type).toBe(Pie);
const { accDescr, sections } = result.value;
expect(accDescr).toBe('sample wow');
const { accDescr, sections } = result.value;
expect(accDescr).toBe('sample wow');
expect(sections[0].label).toBe('GitHub');
expect(sections[0].value).toBe(100);
expect(sections[0].label).toBe('GitHub');
expect(sections[0].value).toBe(100);
expect(sections[1].label).toBe('GitLab');
expect(sections[1].value).toBe(50);
});
expect(sections[1].label).toBe('GitLab');
expect(sections[1].value).toBe(50);
});
it('should handle sections with multi line accDescr', () => {
const context = `pie accDescr {
it('should handle sections with multi line accDescr', () => {
const context = `pie accDescr {
sample wow
}
"GitHub": 100
"GitLab": 50`;
const result = parse(context);
expectNoErrorsOrAlternatives(result);
expect(result.value.$type).toBe(Pie);
const result = parse(context);
expectNoErrorsOrAlternatives(result);
expect(result.value.$type).toBe(Pie);
const { accDescr, sections } = result.value;
expect(accDescr).toBe('sample wow');
const { accDescr, sections } = result.value;
expect(accDescr).toBe('sample wow');
expect(sections[0].label).toBe('GitHub');
expect(sections[0].value).toBe(100);
expect(sections[0].label).toBe('GitHub');
expect(sections[0].value).toBe(100);
expect(sections[1].label).toBe('GitLab');
expect(sections[1].value).toBe(50);
});
expect(sections[1].label).toBe('GitLab');
expect(sections[1].value).toBe(50);
});
});
});

View File

@@ -1,6 +1,8 @@
import type { LangiumParser, ParseResult } from 'langium';
import { expect, vi } from 'vitest';
import type {
Architecture,
ArchitectureServices,
Info,
InfoServices,
Pie,
@@ -13,6 +15,7 @@ import type {
GitGraphServices,
} from '../src/language/index.js';
import {
createArchitectureServices,
createInfoServices,
createPieServices,
createRadarServices,
@@ -47,6 +50,17 @@ export function createInfoTestServices() {
}
export const infoParse = createInfoTestServices().parse;
const architectureServices: ArchitectureServices = createArchitectureServices().Architecture;
const architectureParser: LangiumParser = architectureServices.parser.LangiumParser;
export function createArchitectureTestServices() {
const parse = (input: string) => {
return architectureParser.parse<Architecture>(input);
};
return { services: architectureServices, parse };
}
export const architectureParse = createArchitectureTestServices().parse;
const pieServices: PieServices = createPieServices().Pie;
const pieParser: LangiumParser = pieServices.parser.LangiumParser;
export function createPieTestServices() {