Ran linter (npm run lint:fix)

This commit is contained in:
Jeroen Ekkelkamp 2022-10-19 20:06:54 +02:00
parent 3d140a7411
commit 0c4edd332c
35 changed files with 276 additions and 96 deletions

View File

@ -58,7 +58,9 @@ export const imgSnapshotTest = (graphStr, _options, api = false, validation) =>
const url = mermaidUrl(graphStr, options, api); const url = mermaidUrl(graphStr, options, api);
cy.visit(url); cy.visit(url);
if (validation) cy.get('svg').should(validation); if (validation) {
cy.get('svg').should(validation);
}
cy.get('svg'); cy.get('svg');
// Default name to test title // Default name to test title
@ -106,7 +108,9 @@ export const urlSnapshotTest = (url, _options, api = false, validation) => {
} }
cy.visit(url); cy.visit(url);
if (validation) cy.get('svg').should(validation); if (validation) {
cy.get('svg').should(validation);
}
cy.get('body'); cy.get('body');
// Default name to test title // Default name to test title

View File

@ -120,7 +120,9 @@ const contentLoadedApi = function () {
(svgCode, bindFunctions) => { (svgCode, bindFunctions) => {
div.innerHTML = svgCode; div.innerHTML = svgCode;
if (bindFunctions) bindFunctions(div); if (bindFunctions) {
bindFunctions(div);
}
}, },
div div
); );

View File

@ -44,7 +44,9 @@ function addHtmlLabel(node) {
const createLabel = (_vertexText, style, isTitle, isNode) => { const createLabel = (_vertexText, style, isTitle, isNode) => {
let vertexText = _vertexText || ''; let vertexText = _vertexText || '';
if (typeof vertexText === 'object') vertexText = vertexText[0]; if (typeof vertexText === 'object') {
vertexText = vertexText[0];
}
if (evaluate(getConfig().flowchart.htmlLabels)) { if (evaluate(getConfig().flowchart.htmlLabels)) {
// TODO: addHtmlLabel accepts a labelStyle. Do we possibly have that? // TODO: addHtmlLabel accepts a labelStyle. Do we possibly have that?
vertexText = vertexText.replace(/\\n|\n/g, '<br />'); vertexText = vertexText.replace(/\\n|\n/g, '<br />');

View File

@ -336,7 +336,9 @@ const cutPathAtIntersect = (_points, boundryNode) => {
log.warn('abc88 outside', point, lastPointOutside); log.warn('abc88 outside', point, lastPointOutside);
lastPointOutside = point; lastPointOutside = point;
// points.push(point); // points.push(point);
if (!isInside) points.push(point); if (!isInside) {
points.push(point);
}
} }
}); });
log.warn('abc88 returning points', points); log.warn('abc88 returning points', points);

View File

@ -23,7 +23,9 @@ const isDecendant = (id, ancenstorId) => {
' = ', ' = ',
decendants[ancenstorId].indexOf(id) >= 0 decendants[ancenstorId].indexOf(id) >= 0
); );
if (decendants[ancenstorId].indexOf(id) >= 0) return true; if (decendants[ancenstorId].indexOf(id) >= 0) {
return true;
}
return false; return false;
}; };
@ -32,17 +34,29 @@ const edgeInCluster = (edge, clusterId) => {
log.info('Decendants of ', clusterId, ' is ', decendants[clusterId]); log.info('Decendants of ', clusterId, ' is ', decendants[clusterId]);
log.info('Edge is ', edge); log.info('Edge is ', edge);
// Edges to/from the cluster is not in the cluster, they are in the parent // Edges to/from the cluster is not in the cluster, they are in the parent
if (edge.v === clusterId) return false; if (edge.v === clusterId) {
if (edge.w === clusterId) return false; return false;
}
if (edge.w === clusterId) {
return false;
}
if (!decendants[clusterId]) { if (!decendants[clusterId]) {
log.debug('Tilt, ', clusterId, ',not in decendants'); log.debug('Tilt, ', clusterId, ',not in decendants');
return false; return false;
} }
if (decendants[clusterId].indexOf(edge.v) >= 0) return true; if (decendants[clusterId].indexOf(edge.v) >= 0) {
if (isDecendant(edge.v, clusterId)) return true; return true;
if (isDecendant(edge.w, clusterId)) return true; }
if (decendants[clusterId].indexOf(edge.w) >= 0) return true; if (isDecendant(edge.v, clusterId)) {
return true;
}
if (isDecendant(edge.w, clusterId)) {
return true;
}
if (decendants[clusterId].indexOf(edge.w) >= 0) {
return true;
}
return false; return false;
}; };
@ -306,8 +320,12 @@ export const adjustClustersAndEdges = (graph, depth) => {
v = getAnchorId(e.v); v = getAnchorId(e.v);
w = getAnchorId(e.w); w = getAnchorId(e.w);
graph.removeEdge(e.v, e.w, e.name); graph.removeEdge(e.v, e.w, e.name);
if (v !== e.v) edge.fromCluster = e.v; if (v !== e.v) {
if (w !== e.w) edge.toCluster = e.w; edge.fromCluster = e.v;
}
if (w !== e.w) {
edge.toCluster = e.w;
}
log.warn('Fix Replacing with XXX', v, w, e.name); log.warn('Fix Replacing with XXX', v, w, e.name);
graph.setEdge(v, w, edge, e.name); graph.setEdge(v, w, edge, e.name);
} }
@ -446,7 +464,9 @@ export const extractor = (graph, depth) => {
}; };
const sorter = (graph, nodes) => { const sorter = (graph, nodes) => {
if (nodes.length === 0) return []; if (nodes.length === 0) {
return [];
}
let result = Object.assign(nodes); let result = Object.assign(nodes);
nodes.forEach((node) => { nodes.forEach((node) => {
const children = graph.children(node); const children = graph.children(node);

View File

@ -293,9 +293,13 @@ const cylinder = (parent, node) => {
// ellipsis equation: x*x / a*a + y*y / b*b = 1 // ellipsis equation: x*x / a*a + y*y / b*b = 1
// solve for y to get adjusted value for pos.y // solve for y to get adjusted value for pos.y
let y = ry * ry * (1 - (x * x) / (rx * rx)); let y = ry * ry * (1 - (x * x) / (rx * rx));
if (y != 0) y = Math.sqrt(y); if (y != 0) {
y = Math.sqrt(y);
}
y = ry - y; y = ry - y;
if (point.y - node.y > 0) y = -y; if (point.y - node.y > 0) {
y = -y;
}
pos.y += y; pos.y += y;
} }

View File

@ -1833,8 +1833,12 @@ const config: Partial<MermaidConfig> = {
fontSize: 16, fontSize: 16,
}; };
if (config.class) config.class.arrowMarkerAbsolute = config.arrowMarkerAbsolute; if (config.class) {
if (config.gitGraph) config.gitGraph.arrowMarkerAbsolute = config.arrowMarkerAbsolute; config.class.arrowMarkerAbsolute = config.arrowMarkerAbsolute;
}
if (config.gitGraph) {
config.gitGraph.arrowMarkerAbsolute = config.arrowMarkerAbsolute;
}
const keyify = (obj: any, prefix = ''): string[] => const keyify = (obj: any, prefix = ''): string[] =>
Object.keys(obj).reduce((res: string[], el): string[] => { Object.keys(obj).reduce((res: string[], el): string[] => {

View File

@ -49,8 +49,9 @@ export const addRel = function (type, from, to, label, techn, descr, sprite, tag
to === null || to === null ||
label === undefined || label === undefined ||
label === null label === null
) ) {
return; return;
}
let rel = {}; let rel = {};
const old = rels.find((rel) => rel.from === from && rel.to === to); const old = rels.find((rel) => rel.from === from && rel.to === to);
@ -111,7 +112,9 @@ export const addRel = function (type, from, to, label, techn, descr, sprite, tag
//type, alias, label, ?descr, ?sprite, ?tags, $link //type, alias, label, ?descr, ?sprite, ?tags, $link
export const addPersonOrSystem = function (typeC4Shape, alias, label, descr, sprite, tags, link) { export const addPersonOrSystem = function (typeC4Shape, alias, label, descr, sprite, tags, link) {
// Don't allow label nulling // Don't allow label nulling
if (alias === null || label === null) return; if (alias === null || label === null) {
return;
}
let personOrSystem = {}; let personOrSystem = {};
const old = c4ShapeArray.find((personOrSystem) => personOrSystem.alias === alias); const old = c4ShapeArray.find((personOrSystem) => personOrSystem.alias === alias);
@ -166,7 +169,9 @@ export const addPersonOrSystem = function (typeC4Shape, alias, label, descr, spr
//type, alias, label, ?techn, ?descr ?sprite, ?tags, $link //type, alias, label, ?techn, ?descr ?sprite, ?tags, $link
export const addContainer = function (typeC4Shape, alias, label, techn, descr, sprite, tags, link) { export const addContainer = function (typeC4Shape, alias, label, techn, descr, sprite, tags, link) {
// Don't allow label nulling // Don't allow label nulling
if (alias === null || label === null) return; if (alias === null || label === null) {
return;
}
let container = {}; let container = {};
const old = c4ShapeArray.find((container) => container.alias === alias); const old = c4ShapeArray.find((container) => container.alias === alias);
@ -232,7 +237,9 @@ export const addContainer = function (typeC4Shape, alias, label, techn, descr, s
//type, alias, label, ?techn, ?descr ?sprite, ?tags, $link //type, alias, label, ?techn, ?descr ?sprite, ?tags, $link
export const addComponent = function (typeC4Shape, alias, label, techn, descr, sprite, tags, link) { export const addComponent = function (typeC4Shape, alias, label, techn, descr, sprite, tags, link) {
// Don't allow label nulling // Don't allow label nulling
if (alias === null || label === null) return; if (alias === null || label === null) {
return;
}
let component = {}; let component = {};
const old = c4ShapeArray.find((component) => component.alias === alias); const old = c4ShapeArray.find((component) => component.alias === alias);
@ -300,7 +307,9 @@ export const addPersonOrSystemBoundary = function (alias, label, type, tags, lin
// if (parentBoundary === null) return; // if (parentBoundary === null) return;
// Don't allow label nulling // Don't allow label nulling
if (alias === null || label === null) return; if (alias === null || label === null) {
return;
}
let boundary = {}; let boundary = {};
const old = boundarys.find((boundary) => boundary.alias === alias); const old = boundarys.find((boundary) => boundary.alias === alias);
@ -354,7 +363,9 @@ export const addContainerBoundary = function (alias, label, type, tags, link) {
// if (parentBoundary === null) return; // if (parentBoundary === null) return;
// Don't allow label nulling // Don't allow label nulling
if (alias === null || label === null) return; if (alias === null || label === null) {
return;
}
let boundary = {}; let boundary = {};
const old = boundarys.find((boundary) => boundary.alias === alias); const old = boundarys.find((boundary) => boundary.alias === alias);
@ -417,7 +428,9 @@ export const addDeploymentNode = function (
// if (parentBoundary === null) return; // if (parentBoundary === null) return;
// Don't allow label nulling // Don't allow label nulling
if (alias === null || label === null) return; if (alias === null || label === null) {
return;
}
let boundary = {}; let boundary = {};
const old = boundarys.find((boundary) => boundary.alias === alias); const old = boundarys.find((boundary) => boundary.alias === alias);
@ -646,8 +659,12 @@ export const updateLayoutConfig = function (typeC4Shape, c4ShapeInRowParam, c4Bo
c4BoundaryInRowValue = parseInt(c4BoundaryInRowParam); c4BoundaryInRowValue = parseInt(c4BoundaryInRowParam);
} }
if (c4ShapeInRowValue >= 1) c4ShapeInRow = c4ShapeInRowValue; if (c4ShapeInRowValue >= 1) {
if (c4BoundaryInRowValue >= 1) c4BoundaryInRow = c4BoundaryInRowValue; c4ShapeInRow = c4ShapeInRowValue;
}
if (c4BoundaryInRowValue >= 1) {
c4BoundaryInRow = c4BoundaryInRowValue;
}
}; };
export const getC4ShapeInRow = function () { export const getC4ShapeInRow = function () {
@ -665,11 +682,13 @@ export const getParentBoundaryParse = function () {
}; };
export const getC4ShapeArray = function (parentBoundary) { export const getC4ShapeArray = function (parentBoundary) {
if (parentBoundary === undefined || parentBoundary === null) return c4ShapeArray; if (parentBoundary === undefined || parentBoundary === null) {
else return c4ShapeArray;
} else {
return c4ShapeArray.filter((personOrSystem) => { return c4ShapeArray.filter((personOrSystem) => {
return personOrSystem.parentBoundary === parentBoundary; return personOrSystem.parentBoundary === parentBoundary;
}); });
}
}; };
export const getC4Shape = function (alias) { export const getC4Shape = function (alias) {
return c4ShapeArray.find((personOrSystem) => personOrSystem.alias === alias); return c4ShapeArray.find((personOrSystem) => personOrSystem.alias === alias);
@ -679,8 +698,11 @@ export const getC4ShapeKeys = function (parentBoundary) {
}; };
export const getBoundarys = function (parentBoundary) { export const getBoundarys = function (parentBoundary) {
if (parentBoundary === undefined || parentBoundary === null) return boundarys; if (parentBoundary === undefined || parentBoundary === null) {
else return boundarys.filter((boundary) => boundary.parentBoundary === parentBoundary); return boundarys;
} else {
return boundarys.filter((boundary) => boundary.parentBoundary === parentBoundary);
}
}; };
export const getRels = function () { export const getRels = function () {

View File

@ -414,7 +414,9 @@ export const drawRels = function (diagram, rels, getC4ShapeObj, diagObj) {
let relTextWrap = rel.wrap && conf.wrap; let relTextWrap = rel.wrap && conf.wrap;
let relConf = messageFont(conf); let relConf = messageFont(conf);
let diagramType = diagObj.db.getC4Type(); let diagramType = diagObj.db.getC4Type();
if (diagramType === 'C4Dynamic') rel.label.text = i + ': ' + rel.label.text; if (diagramType === 'C4Dynamic') {
rel.label.text = i + ': ' + rel.label.text;
}
let textLimitWidth = calculateTextWidth(rel.label.text, relConf); let textLimitWidth = calculateTextWidth(rel.label.text, relConf);
calcC4ShapeTextWH('label', rel, relTextWrap, relConf, textLimitWidth); calcC4ShapeTextWH('label', rel, relTextWrap, relConf, textLimitWidth);
@ -555,7 +557,9 @@ function drawInsideBoundary(
); );
} }
// draw boundary // draw boundary
if (currentBoundary.alias !== 'global') drawBoundary(diagram, currentBoundary, currentBounds); if (currentBoundary.alias !== 'global') {
drawBoundary(diagram, currentBoundary, currentBounds);
}
parentBounds.data.stopy = Math.max( parentBounds.data.stopy = Math.max(
currentBounds.data.stopy + conf.c4ShapeMargin, currentBounds.data.stopy + conf.c4ShapeMargin,
parentBounds.data.stopy parentBounds.data.stopy

View File

@ -13,7 +13,9 @@ export const drawRect = function (elem, rectData) {
rectElem.attr('ry', rectData.ry); rectElem.attr('ry', rectData.ry);
if (rectData.attrs !== 'undefined' && rectData.attrs !== null) { if (rectData.attrs !== 'undefined' && rectData.attrs !== null) {
for (let attrKey in rectData.attrs) rectElem.attr(attrKey, rectData.attrs[attrKey]); for (let attrKey in rectData.attrs) {
rectElem.attr(attrKey, rectData.attrs[attrKey]);
}
} }
if (rectData.class !== 'undefined') { if (rectData.class !== 'undefined') {
@ -231,9 +233,12 @@ export const drawRels = (elem, rels, conf) => {
line.attr('stroke-width', '1'); line.attr('stroke-width', '1');
line.attr('stroke', strokeColor); line.attr('stroke', strokeColor);
line.style('fill', 'none'); line.style('fill', 'none');
if (rel.type !== 'rel_b') line.attr('marker-end', 'url(' + url + '#arrowhead)'); if (rel.type !== 'rel_b') {
if (rel.type === 'birel' || rel.type === 'rel_b') line.attr('marker-end', 'url(' + url + '#arrowhead)');
}
if (rel.type === 'birel' || rel.type === 'rel_b') {
line.attr('marker-start', 'url(' + url + '#arrowend)'); line.attr('marker-start', 'url(' + url + '#arrowend)');
}
i = -1; i = -1;
} else { } else {
let line = relsElem.append('path'); let line = relsElem.append('path');
@ -256,9 +261,12 @@ export const drawRels = (elem, rels, conf) => {
.replaceAll('stopx', rel.endPoint.x) .replaceAll('stopx', rel.endPoint.x)
.replaceAll('stopy', rel.endPoint.y) .replaceAll('stopy', rel.endPoint.y)
); );
if (rel.type !== 'rel_b') line.attr('marker-end', 'url(' + url + '#arrowhead)'); if (rel.type !== 'rel_b') {
if (rel.type === 'birel' || rel.type === 'rel_b') line.attr('marker-end', 'url(' + url + '#arrowhead)');
}
if (rel.type === 'birel' || rel.type === 'rel_b') {
line.attr('marker-start', 'url(' + url + '#arrowend)'); line.attr('marker-start', 'url(' + url + '#arrowend)');
}
} }
let messageConf = conf.messageFont(); let messageConf = conf.messageFont();
@ -314,7 +322,9 @@ const drawBoundary = function (elem, boundary, conf) {
let fontColor = boundary.fontColor ? boundary.fontColor : 'black'; let fontColor = boundary.fontColor ? boundary.fontColor : 'black';
let attrsValue = { 'stroke-width': 1.0, 'stroke-dasharray': '7.0,7.0' }; let attrsValue = { 'stroke-width': 1.0, 'stroke-dasharray': '7.0,7.0' };
if (boundary.nodeType) attrsValue = { 'stroke-width': 1.0 }; if (boundary.nodeType) {
attrsValue = { 'stroke-width': 1.0 };
}
let rectData = { let rectData = {
x: boundary.x, x: boundary.x,
y: boundary.y, y: boundary.y,

View File

@ -49,7 +49,9 @@ const splitClassNameAndType = function (id) {
export const addClass = function (id) { export const addClass = function (id) {
let classId = splitClassNameAndType(id); let classId = splitClassNameAndType(id);
// Only add class if not exists // Only add class if not exists
if (typeof classes[classId.className] !== 'undefined') return; if (typeof classes[classId.className] !== 'undefined') {
return;
}
classes[classId.className] = { classes[classId.className] = {
id: classId.className, id: classId.className,
@ -185,7 +187,9 @@ export const cleanupLabel = function (label) {
export const setCssClass = function (ids, className) { export const setCssClass = function (ids, className) {
ids.split(',').forEach(function (_id) { ids.split(',').forEach(function (_id) {
let id = _id; let id = _id;
if (_id[0].match(/\d/)) id = MERMAID_DOM_ID_PREFIX + id; if (_id[0].match(/\d/)) {
id = MERMAID_DOM_ID_PREFIX + id;
}
if (typeof classes[id] !== 'undefined') { if (typeof classes[id] !== 'undefined') {
classes[id].cssClasses.push(className); classes[id].cssClasses.push(className);
} }
@ -220,7 +224,9 @@ export const setLink = function (ids, linkStr, target) {
const config = configApi.getConfig(); const config = configApi.getConfig();
ids.split(',').forEach(function (_id) { ids.split(',').forEach(function (_id) {
let id = _id; let id = _id;
if (_id[0].match(/\d/)) id = MERMAID_DOM_ID_PREFIX + id; if (_id[0].match(/\d/)) {
id = MERMAID_DOM_ID_PREFIX + id;
}
if (typeof classes[id] !== 'undefined') { if (typeof classes[id] !== 'undefined') {
classes[id].link = utils.formatUrl(linkStr, config); classes[id].link = utils.formatUrl(linkStr, config);
if (config.securityLevel === 'sandbox') { if (config.securityLevel === 'sandbox') {

View File

@ -2,8 +2,12 @@ import type { DiagramDetector } from '../../diagram-api/types';
export const classDetectorV2: DiagramDetector = (txt, config) => { export const classDetectorV2: DiagramDetector = (txt, config) => {
// If we have configured to use dagre-wrapper then we should return true in this function for classDiagram code thus making it use the new class diagram // If we have configured to use dagre-wrapper then we should return true in this function for classDiagram code thus making it use the new class diagram
if (txt.match(/^\s*classDiagram/) !== null && config?.class?.defaultRenderer === 'dagre-wrapper') if (
txt.match(/^\s*classDiagram/) !== null &&
config?.class?.defaultRenderer === 'dagre-wrapper'
) {
return true; return true;
}
// We have not opted to use the new renderer so we should return true if we detect a class diagram // We have not opted to use the new renderer so we should return true if we detect a class diagram
return txt.match(/^\s*classDiagram-v2/) !== null; return txt.match(/^\s*classDiagram-v2/) !== null;
}; };

View File

@ -2,7 +2,9 @@ import type { DiagramDetector } from '../../diagram-api/types';
export const classDetector: DiagramDetector = (txt, config) => { export const classDetector: DiagramDetector = (txt, config) => {
// If we have configured to use dagre-wrapper then we should never return true in this function // If we have configured to use dagre-wrapper then we should never return true in this function
if (config?.class?.defaultRenderer === 'dagre-wrapper') return false; if (config?.class?.defaultRenderer === 'dagre-wrapper') {
return false;
}
// We have not opted to use the new renderer so we should return true if we detect a class diagram // We have not opted to use the new renderer so we should return true if we detect a class diagram
return txt.match(/^\s*classDiagram/) !== null; return txt.match(/^\s*classDiagram/) !== null;
}; };

View File

@ -190,7 +190,9 @@ export const drawClass = function (elem, classDef, conf, diagObj) {
let isFirst = true; let isFirst = true;
classDef.annotations.forEach(function (member) { classDef.annotations.forEach(function (member) {
const titleText2 = title.append('tspan').text('«' + member + '»'); const titleText2 = title.append('tspan').text('«' + member + '»');
if (!isFirst) titleText2.attr('dy', conf.textHeight); if (!isFirst) {
titleText2.attr('dy', conf.textHeight);
}
isFirst = false; isFirst = false;
}); });
@ -203,7 +205,9 @@ export const drawClass = function (elem, classDef, conf, diagObj) {
const classTitle = title.append('tspan').text(classTitleString).attr('class', 'title'); const classTitle = title.append('tspan').text(classTitleString).attr('class', 'title');
// If class has annotations the title needs to have an offset of the text height // If class has annotations the title needs to have an offset of the text height
if (!isFirst) classTitle.attr('dy', conf.textHeight); if (!isFirst) {
classTitle.attr('dy', conf.textHeight);
}
const titleHeight = title.node().getBBox().height; const titleHeight = title.node().getBBox().height;

View File

@ -8,7 +8,9 @@ import { MermaidConfig } from '../../config.type';
* @returns {string[]} The rows in that string * @returns {string[]} The rows in that string
*/ */
export const getRows = (s?: string): string[] => { export const getRows = (s?: string): string[] => {
if (!s) return ['']; if (!s) {
return [''];
}
const str = breakToPlaceholder(s).replace(/\\n/g, '#br#'); const str = breakToPlaceholder(s).replace(/\\n/g, '#br#');
return str.split('#br#'); return str.split('#br#');
}; };
@ -39,7 +41,9 @@ const sanitizeMore = (text: string, config: MermaidConfig) => {
}; };
export const sanitizeText = (text: string, config: MermaidConfig): string => { export const sanitizeText = (text: string, config: MermaidConfig): string => {
if (!text) return text; if (!text) {
return text;
}
if (config.dompurifyConfig) { if (config.dompurifyConfig) {
text = DOMPurify.sanitize(sanitizeMore(text, config), config.dompurifyConfig).toString(); text = DOMPurify.sanitize(sanitizeMore(text, config), config.dompurifyConfig).toString();
} else { } else {
@ -52,7 +56,9 @@ export const sanitizeTextOrArray = (
a: string | string[] | string[][], a: string | string[] | string[][],
config: MermaidConfig config: MermaidConfig
): string | string[] => { ): string | string[] => {
if (typeof a === 'string') return sanitizeText(a, config); if (typeof a === 'string') {
return sanitizeText(a, config);
}
// TODO: Refactor to avoid flat. // TODO: Refactor to avoid flat.
return a.flat().map((x: string) => sanitizeText(x, config)); return a.flat().map((x: string) => sanitizeText(x, config));
}; };

View File

@ -281,9 +281,13 @@ function cylinder(parent, bbox, node) {
// ellipsis equation: x*x / a*a + y*y / b*b = 1 // ellipsis equation: x*x / a*a + y*y / b*b = 1
// solve for y to get adjusted value for pos.y // solve for y to get adjusted value for pos.y
let y = ry * ry * (1 - (x * x) / (rx * rx)); let y = ry * ry * (1 - (x * x) / (rx * rx));
if (y != 0) y = Math.sqrt(y); if (y != 0) {
y = Math.sqrt(y);
}
y = ry - y; y = ry - y;
if (point.y - node.y > 0) y = -y; if (point.y - node.y > 0) {
y = -y;
}
pos.y += y; pos.y += y;
} }

View File

@ -699,7 +699,9 @@ const destructLink = (_str, _startStr) => {
startInfo.type = info.type; startInfo.type = info.type;
} else { } else {
// x-- xyz --> - not supported // x-- xyz --> - not supported
if (startInfo.type !== info.type) return { type: 'INVALID', stroke: 'INVALID' }; if (startInfo.type !== info.type) {
return { type: 'INVALID', stroke: 'INVALID' };
}
startInfo.type = 'double_' + startInfo.type; startInfo.type = 'double_' + startInfo.type;
} }

View File

@ -2,7 +2,8 @@ import type { DiagramDetector } from '../../diagram-api/types';
export const flowDetectorV2: DiagramDetector = (txt, config) => { export const flowDetectorV2: DiagramDetector = (txt, config) => {
// If we have configured to use dagre-wrapper then we should return true in this function for graph code thus making it use the new flowchart diagram // If we have configured to use dagre-wrapper then we should return true in this function for graph code thus making it use the new flowchart diagram
if (config?.flowchart?.defaultRenderer === 'dagre-wrapper' && txt.match(/^\s*graph/) !== null) if (config?.flowchart?.defaultRenderer === 'dagre-wrapper' && txt.match(/^\s*graph/) !== null) {
return true; return true;
}
return txt.match(/^\s*flowchart/) !== null; return txt.match(/^\s*flowchart/) !== null;
}; };

View File

@ -3,6 +3,8 @@ import type { DiagramDetector } from '../../diagram-api/types';
export const flowDetector: DiagramDetector = (txt, config) => { export const flowDetector: DiagramDetector = (txt, config) => {
// If we have conferred to only use new flow charts this function should always return false // If we have conferred to only use new flow charts this function should always return false
// as in not signalling true for a legacy flowchart // as in not signalling true for a legacy flowchart
if (config?.flowchart?.defaultRenderer === 'dagre-wrapper') return false; if (config?.flowchart?.defaultRenderer === 'dagre-wrapper') {
return false;
}
return txt.match(/^\s*graph/) !== null; return txt.match(/^\s*graph/) !== null;
}; };

View File

@ -153,7 +153,9 @@ export const isInvalidDate = function (date, dateFormat, excludes, includes) {
}; };
const checkTaskDates = function (task, dateFormat, excludes, includes) { const checkTaskDates = function (task, dateFormat, excludes, includes) {
if (!excludes.length || task.manualEndTime) return; if (!excludes.length || task.manualEndTime) {
return;
}
let startTime = moment(task.startTime, dateFormat, true); let startTime = moment(task.startTime, dateFormat, true);
startTime.add(1, 'd'); startTime.add(1, 'd');
let endTime = moment(task.endTime, dateFormat, true); let endTime = moment(task.endTime, dateFormat, true);

View File

@ -427,7 +427,9 @@ export const draw = function (text, id, version, diagObj) {
); );
const maxTime = tasks.reduce((max, { endTime }) => (max ? Math.max(max, endTime) : endTime), 0); const maxTime = tasks.reduce((max, { endTime }) => (max ? Math.max(max, endTime) : endTime), 0);
const dateFormat = diagObj.db.getDateFormat(); const dateFormat = diagObj.db.getDateFormat();
if (!minTime || !maxTime) return; if (!minTime || !maxTime) {
return;
}
const excludeRanges = []; const excludeRanges = [];
let range = null; let range = null;
@ -552,7 +554,9 @@ export const draw = function (text, id, version, diagObj) {
const tspan = doc.createElementNS('http://www.w3.org/2000/svg', 'tspan'); const tspan = doc.createElementNS('http://www.w3.org/2000/svg', 'tspan');
tspan.setAttribute('alignment-baseline', 'central'); tspan.setAttribute('alignment-baseline', 'central');
tspan.setAttribute('x', '10'); tspan.setAttribute('x', '10');
if (j > 0) tspan.setAttribute('dy', '1em'); if (j > 0) {
tspan.setAttribute('dy', '1em');
}
tspan.textContent = rows[j]; tspan.textContent = rows[j];
svgLabel.appendChild(tspan); svgLabel.appendChild(tspan);
} }

View File

@ -399,7 +399,9 @@ function upsert(arr, key, newVal) {
/** @param commitArr */ /** @param commitArr */
function prettyPrintCommitHistory(commitArr) { function prettyPrintCommitHistory(commitArr) {
const commit = commitArr.reduce((out, commit) => { const commit = commitArr.reduce((out, commit) => {
if (out.seq > commit.seq) return out; if (out.seq > commit.seq) {
return out;
}
return commit; return commit;
}, commitArr[0]); }, commitArr[0]);
let line = ''; let line = '';
@ -412,7 +414,9 @@ function prettyPrintCommitHistory(commitArr) {
}); });
const label = [line, commit.id, commit.seq]; const label = [line, commit.id, commit.seq];
for (let branch in branches) { for (let branch in branches) {
if (branches[branch] === commit.id) label.push(branch); if (branches[branch] === commit.id) {
label.push(branch);
}
} }
log.debug(label.join(' ')); log.debug(label.join(' '));
if (commit.parents && commit.parents.length == 2) { if (commit.parents && commit.parents.length == 2) {
@ -452,7 +456,9 @@ export const clear = function () {
export const getBranchesAsObjArray = function () { export const getBranchesAsObjArray = function () {
const branchesArray = Object.values(branchesConfig) const branchesArray = Object.values(branchesConfig)
.map((branchConfig, i) => { .map((branchConfig, i) => {
if (branchConfig.order !== null) return branchConfig; if (branchConfig.order !== null) {
return branchConfig;
}
return { return {
...branchConfig, ...branchConfig,
order: parseFloat(`0.${i}`, 10), order: parseFloat(`0.${i}`, 10),

View File

@ -357,7 +357,9 @@ export const draw = function (txt, id, ver) {
branchNum++; branchNum++;
} }
svg.attr('height', function () { svg.attr('height', function () {
if (direction === 'BT') return Object.keys(allCommitsDict).length * config.nodeSpacing; if (direction === 'BT') {
return Object.keys(allCommitsDict).length * config.nodeSpacing;
}
return (branches.length + 1) * config.branchOffset; return (branches.length + 1) * config.branchOffset;
}); });
} catch (e) { } catch (e) {

View File

@ -26,7 +26,9 @@ export const parseDirective = function (statement, context, type) {
export const addActor = function (id, name, description, type) { export const addActor = function (id, name, description, type) {
// Don't allow description nulling // Don't allow description nulling
const old = actors[id]; const old = actors[id];
if (old && name === old.name && description == null) return; if (old && name === old.name && description == null) {
return;
}
// Don't allow null descriptions, either // Don't allow null descriptions, either
if (description == null || description.text == null) { if (description == null || description.text == null) {

View File

@ -762,8 +762,11 @@ export const draw = function (_text, id, _version, diagObj) {
case diagObj.db.LINETYPE.AUTONUMBER: case diagObj.db.LINETYPE.AUTONUMBER:
sequenceIndex = msg.message.start || sequenceIndex; sequenceIndex = msg.message.start || sequenceIndex;
sequenceIndexStep = msg.message.step || sequenceIndexStep; sequenceIndexStep = msg.message.step || sequenceIndexStep;
if (msg.message.visible) diagObj.db.enableSequenceNumbers(); if (msg.message.visible) {
else diagObj.db.disableSequenceNumbers(); diagObj.db.enableSequenceNumbers();
} else {
diagObj.db.disableSequenceNumbers();
}
break; break;
case diagObj.db.LINETYPE.CRITICAL_START: case diagObj.db.LINETYPE.CRITICAL_START:
adjustLoopHeightForWrap( adjustLoopHeightForWrap(

View File

@ -31,7 +31,9 @@ const addPopupInteraction = (id, actorCnt) => {
addFunction(() => { addFunction(() => {
const arr = document.querySelectorAll(id); const arr = document.querySelectorAll(id);
// This will be the case when running in sandboxed mode // This will be the case when running in sandboxed mode
if (arr.length === 0) return; if (arr.length === 0) {
return;
}
arr[0].addEventListener('mouseover', function () { arr[0].addEventListener('mouseover', function () {
popupMenuUpFunc('actor' + actorCnt + '_popup'); popupMenuUpFunc('actor' + actorCnt + '_popup');
}); });
@ -322,7 +324,9 @@ export const drawLabel = function (elem, txtObject) {
let actorCnt = -1; let actorCnt = -1;
export const fixLifeLineHeights = (diagram, bounds) => { export const fixLifeLineHeights = (diagram, bounds) => {
if (!diagram.selectAll) return; if (!diagram.selectAll) {
return;
}
diagram diagram
.selectAll('.actor-line') .selectAll('.actor-line')
.attr('class', '200') .attr('class', '200')

View File

@ -217,7 +217,9 @@ export const addTitleAndBox = (g, stateDef, altBkg) => {
.attr('rx', '0'); .attr('rx', '0');
title.attr('x', startX + pad); title.attr('x', startX + pad);
if (titleWidth <= orgWidth) title.attr('x', orgX + (width - dblPad) / 2 - titleWidth / 2 + pad); if (titleWidth <= orgWidth) {
title.attr('x', orgX + (width - dblPad) / 2 - titleWidth / 2 + pad);
}
// Title background // Title background
g.insert('rect', ':first-child') g.insert('rect', ':first-child')
@ -379,14 +381,27 @@ export const drawState = function (elem, stateDef) {
const g = elem.append('g').attr('id', id).attr('class', 'stateGroup'); const g = elem.append('g').attr('id', id).attr('class', 'stateGroup');
if (stateDef.type === 'start') drawStartState(g); if (stateDef.type === 'start') {
if (stateDef.type === 'end') drawEndState(g); drawStartState(g);
if (stateDef.type === 'fork' || stateDef.type === 'join') drawForkJoinState(g, stateDef); }
if (stateDef.type === 'note') drawNote(stateDef.note.text, g); if (stateDef.type === 'end') {
if (stateDef.type === 'divider') drawDivider(g); drawEndState(g);
if (stateDef.type === 'default' && stateDef.descriptions.length === 0) }
if (stateDef.type === 'fork' || stateDef.type === 'join') {
drawForkJoinState(g, stateDef);
}
if (stateDef.type === 'note') {
drawNote(stateDef.note.text, g);
}
if (stateDef.type === 'divider') {
drawDivider(g);
}
if (stateDef.type === 'default' && stateDef.descriptions.length === 0) {
drawSimpleState(g, stateDef); drawSimpleState(g, stateDef);
if (stateDef.type === 'default' && stateDef.descriptions.length > 0) drawDescrState(g, stateDef); }
if (stateDef.type === 'default' && stateDef.descriptions.length > 0) {
drawDescrState(g, stateDef);
}
const stateBox = g.node().getBBox(); const stateBox = g.node().getBBox();
stateInfo.width = stateBox.width + 2 * getConfig().state.padding; stateInfo.width = stateBox.width + 2 * getConfig().state.padding;

View File

@ -148,7 +148,9 @@ export const addState = function (id, type, doc, descr, note) {
} }
if (descr) { if (descr) {
log.info('Adding state ', id, descr); log.info('Adding state ', id, descr);
if (typeof descr === 'string') addDescription(id, descr.trim()); if (typeof descr === 'string') {
addDescription(id, descr.trim());
}
if (typeof descr === 'object') { if (typeof descr === 'object') {
descr.forEach((des) => addDescription(id, des.trim())); descr.forEach((des) => addDescription(id, des.trim()));

View File

@ -1,8 +1,11 @@
import type { DiagramDetector } from '../../diagram-api/types'; import type { DiagramDetector } from '../../diagram-api/types';
export const stateDetectorV2: DiagramDetector = (text, config) => { export const stateDetectorV2: DiagramDetector = (text, config) => {
if (text.match(/^\s*stateDiagram-v2/) !== null) return true; if (text.match(/^\s*stateDiagram-v2/) !== null) {
if (text.match(/^\s*stateDiagram/) && config?.state?.defaultRenderer === 'dagre-wrapper')
return true; return true;
}
if (text.match(/^\s*stateDiagram/) && config?.state?.defaultRenderer === 'dagre-wrapper') {
return true;
}
return false; return false;
}; };

View File

@ -3,6 +3,8 @@ import type { DiagramDetector } from '../../diagram-api/types';
export const stateDetector: DiagramDetector = (txt, config) => { export const stateDetector: DiagramDetector = (txt, config) => {
// If we have confirmed to only use new state diagrams this function should always return false // If we have confirmed to only use new state diagrams this function should always return false
// as in not signalling true for a legacy state diagram // as in not signalling true for a legacy state diagram
if (config?.state?.defaultRenderer === 'dagre-wrapper') return false; if (config?.state?.defaultRenderer === 'dagre-wrapper') {
return false;
}
return txt.match(/^\s*stateDiagram/) !== null; return txt.match(/^\s*stateDiagram/) !== null;
}; };

View File

@ -120,7 +120,7 @@ const renderDoc = (doc, diagram, parentId, altBkg, root, domDocument, diagObj) =
} }
// Set an object for the graph label // Set an object for the graph label
if (parentId) if (parentId) {
graph.setGraph({ graph.setGraph({
rankdir: 'LR', rankdir: 'LR',
multigraph: true, multigraph: true,
@ -133,7 +133,7 @@ const renderDoc = (doc, diagram, parentId, altBkg, root, domDocument, diagObj) =
// ranksep: 5, // ranksep: 5,
// nodesep: 1 // nodesep: 1
}); });
else { } else {
graph.setGraph({ graph.setGraph({
rankdir: 'TB', rankdir: 'TB',
multigraph: true, multigraph: true,
@ -268,7 +268,9 @@ const renderDoc = (doc, diagram, parentId, altBkg, root, domDocument, diagObj) =
let pWidth = 0; let pWidth = 0;
let pShift = 0; let pShift = 0;
if (parent) { if (parent) {
if (parent.parentElement) pWidth = parent.parentElement.getBBox().width; if (parent.parentElement) {
pWidth = parent.parentElement.getBBox().width;
}
pShift = parseInt(parent.getAttribute('data-x-shift'), 10); pShift = parseInt(parent.getAttribute('data-x-shift'), 10);
if (Number.isNaN(pShift)) { if (Number.isNaN(pShift)) {
pShift = 0; pShift = 0;

View File

@ -74,7 +74,9 @@ export const draw = function (text, id, version, diagObj) {
const title = diagObj.db.getDiagramTitle(); const title = diagObj.db.getDiagramTitle();
const actorNames = diagObj.db.getActors(); const actorNames = diagObj.db.getActors();
for (const member in actors) delete actors[member]; for (const member in actors) {
delete actors[member];
}
let actorPos = 0; let actorPos = 0;
actorNames.forEach((actorName) => { actorNames.forEach((actorName) => {
actors[actorName] = { actors[actorName] = {

View File

@ -143,7 +143,9 @@ const initThrowsErrors = async function (
if (typeof callback !== 'undefined') { if (typeof callback !== 'undefined') {
callback(id); callback(id);
} }
if (bindFunctions) bindFunctions(element); if (bindFunctions) {
bindFunctions(element);
}
}, },
element element
); );

View File

@ -389,11 +389,15 @@ const parseDirective = function (p: any, statement: string, context: string, typ
currentDirective = {}; currentDirective = {};
break; break;
case 'type_directive': case 'type_directive':
if (!currentDirective) throw new Error('currentDirective is undefined'); if (!currentDirective) {
throw new Error('currentDirective is undefined');
}
currentDirective.type = statement.toLowerCase(); currentDirective.type = statement.toLowerCase();
break; break;
case 'arg_directive': case 'arg_directive':
if (!currentDirective) throw new Error('currentDirective is undefined'); if (!currentDirective) {
throw new Error('currentDirective is undefined');
}
currentDirective.args = JSON.parse(statement); currentDirective.args = JSON.parse(statement);
break; break;
case 'close_directive': case 'close_directive':

View File

@ -173,7 +173,9 @@ export const detectDirective = function (text, type = null) {
*/ */
export const isSubstringInArray = function (str, arr) { export const isSubstringInArray = function (str, arr) {
for (let i = 0; i < arr.length; i++) { for (let i = 0; i < arr.length; i++) {
if (arr[i].match(str)) return i; if (arr[i].match(str)) {
return i;
}
} }
return -1; return -1;
}; };
@ -227,7 +229,9 @@ export const runFunc = (functionName, ...params) => {
let obj = window; let obj = window;
for (let i = 0; i < len; i++) { for (let i = 0; i < len; i++) {
obj = obj[arrPaths[i]]; obj = obj[arrPaths[i]];
if (!obj) return; if (!obj) {
return;
}
} }
obj[fnName](...params); obj[fnName](...params);
@ -276,8 +280,12 @@ const traverseEdge = (points) => {
// The point is remainingDistance from prevPoint in the vector between prevPoint and point // The point is remainingDistance from prevPoint in the vector between prevPoint and point
// Calculate the coordinates // Calculate the coordinates
const distanceRatio = remainingDistance / vectorDistance; const distanceRatio = remainingDistance / vectorDistance;
if (distanceRatio <= 0) center = prevPoint; if (distanceRatio <= 0) {
if (distanceRatio >= 1) center = { x: point.x, y: point.y }; center = prevPoint;
}
if (distanceRatio >= 1) {
center = { x: point.x, y: point.y };
}
if (distanceRatio > 0 && distanceRatio < 1) { if (distanceRatio > 0 && distanceRatio < 1) {
center = { center = {
x: (1 - distanceRatio) * prevPoint.x + distanceRatio * point.x, x: (1 - distanceRatio) * prevPoint.x + distanceRatio * point.x,
@ -330,8 +338,12 @@ const calcCardinalityPosition = (isRelationTypePresent, points, initialPosition)
// The point is remainingDistance from prevPoint in the vector between prevPoint and point // The point is remainingDistance from prevPoint in the vector between prevPoint and point
// Calculate the coordinates // Calculate the coordinates
const distanceRatio = remainingDistance / vectorDistance; const distanceRatio = remainingDistance / vectorDistance;
if (distanceRatio <= 0) center = prevPoint; if (distanceRatio <= 0) {
if (distanceRatio >= 1) center = { x: point.x, y: point.y }; center = prevPoint;
}
if (distanceRatio >= 1) {
center = { x: point.x, y: point.y };
}
if (distanceRatio > 0 && distanceRatio < 1) { if (distanceRatio > 0 && distanceRatio < 1) {
center = { center = {
x: (1 - distanceRatio) * prevPoint.x + distanceRatio * point.x, x: (1 - distanceRatio) * prevPoint.x + distanceRatio * point.x,
@ -389,8 +401,12 @@ const calcTerminalLabelPosition = (terminalMarkerSize, position, _points) => {
// The point is remainingDistance from prevPoint in the vector between prevPoint and point // The point is remainingDistance from prevPoint in the vector between prevPoint and point
// Calculate the coordinates // Calculate the coordinates
const distanceRatio = remainingDistance / vectorDistance; const distanceRatio = remainingDistance / vectorDistance;
if (distanceRatio <= 0) center = prevPoint; if (distanceRatio <= 0) {
if (distanceRatio >= 1) center = { x: point.x, y: point.y }; center = prevPoint;
}
if (distanceRatio >= 1) {
center = { x: point.x, y: point.y };
}
if (distanceRatio > 0 && distanceRatio < 1) { if (distanceRatio > 0 && distanceRatio < 1) {
center = { center = {
x: (1 - distanceRatio) * prevPoint.x + distanceRatio * point.x, x: (1 - distanceRatio) * prevPoint.x + distanceRatio * point.x,
@ -712,7 +728,9 @@ export const initIdGenerator = class iterator {
} }
next() { next() {
if (!this.deterministic) return Date.now(); if (!this.deterministic) {
return Date.now();
}
return this.count++; return this.count++;
} }
@ -834,7 +852,9 @@ export function isDetailedError(error: unknown): error is DetailedError {
/** @param error */ /** @param error */
export function getErrorMessage(error: unknown): string { export function getErrorMessage(error: unknown): string {
if (error instanceof Error) return error.message; if (error instanceof Error) {
return error.message;
}
return String(error); return String(error);
} }