Merge pull request #1879 from harshilparmar/enhancement/standardized_naming

Enhancement/standardized naming
This commit is contained in:
Knut Sveidqvist 2021-02-07 10:07:59 +01:00 committed by GitHub
commit 1f523ee843
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
41 changed files with 278 additions and 277 deletions

View File

@ -1,5 +1,5 @@
import { assignWithDepth } from './utils'; import { assignWithDepth } from './utils';
import { logger } from './logger'; import { log } from './logger';
import theme from './themes'; import theme from './themes';
import config from './defaultConfig'; import config from './defaultConfig';
@ -139,7 +139,7 @@ export const sanitize = options => {
if (typeof options[siteConfig.secure[key]] !== 'undefined') { if (typeof options[siteConfig.secure[key]] !== 'undefined') {
// DO NOT attempt to print options[siteConfig.secure[key]] within `${}` as a malicious script // DO NOT attempt to print options[siteConfig.secure[key]] within `${}` as a malicious script
// can exploit the logger's attempt to stringify the value and execute arbitrary code // can exploit the logger's attempt to stringify the value and execute arbitrary code
logger.debug( log.debug(
`Denied attempt to modify a secure key ${siteConfig.secure[key]}`, `Denied attempt to modify a secure key ${siteConfig.secure[key]}`,
options[siteConfig.secure[key]] options[siteConfig.secure[key]]
); );

View File

@ -1,5 +1,5 @@
import { assignWithDepth } from './utils'; import { assignWithDepth } from './utils';
import { logger } from './logger'; // eslint-disable-line import { log } from './logger'; // eslint-disable-line
import theme from './themes'; import theme from './themes';
import config from './defaultConfig'; import config from './defaultConfig';
@ -115,7 +115,7 @@ export const sanitize = options => {
if (typeof options[siteConfig.secure[key]] !== 'undefined') { if (typeof options[siteConfig.secure[key]] !== 'undefined') {
// DO NOT attempt to print options[siteConfig.secure[key]] within `${}` as a malicious script // DO NOT attempt to print options[siteConfig.secure[key]] within `${}` as a malicious script
// can exploit the logger's attempt to stringify the value and execute arbitrary code // can exploit the logger's attempt to stringify the value and execute arbitrary code
logger.trace( log.trace(
`Denied attempt to modify a secure key ${siteConfig.secure[key]}`, `Denied attempt to modify a secure key ${siteConfig.secure[key]}`,
options[siteConfig.secure[key]] options[siteConfig.secure[key]]
); );

View File

@ -1,5 +1,5 @@
import intersectRect from './intersect/intersect-rect'; import intersectRect from './intersect/intersect-rect';
import { logger as log } from '../logger'; // eslint-disable-line import { log } from '../logger';
import createLabel from './createLabel'; import createLabel from './createLabel';
import { select } from 'd3'; import { select } from 'd3';
import { getConfig } from '../config'; import { getConfig } from '../config';

View File

@ -1,5 +1,5 @@
import { select } from 'd3'; import { select } from 'd3';
import { logger } from '../logger'; // eslint-disable-line import { log } from '../logger'; // eslint-disable-line
// let vertexNode; // let vertexNode;
// if (getConfig().flowchart.htmlLabels) { // if (getConfig().flowchart.htmlLabels) {
// // TODO: addHtmlLabel accepts a labelStyle. Do we possibly have that? // // TODO: addHtmlLabel accepts a labelStyle. Do we possibly have that?
@ -88,7 +88,7 @@ const createLabel = (_vertexText, style, isTitle, isNode) => {
if (getConfig().flowchart.htmlLabels) { if (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 />');
logger.info('vertexText' + vertexText); log.info('vertexText' + vertexText);
const node = { const node = {
isNode, isNode,
label: vertexText.replace( label: vertexText.replace(

View File

@ -1,4 +1,4 @@
import { logger } from '../logger'; // eslint-disable-line import { log } from '../logger'; // eslint-disable-line
import createLabel from './createLabel'; import createLabel from './createLabel';
import { line, curveBasis, select } from 'd3'; import { line, curveBasis, select } from 'd3';
import { getConfig } from '../config'; import { getConfig } from '../config';
@ -104,7 +104,7 @@ export const insertEdgeLabel = (elem, edge) => {
}; };
export const positionEdgeLabel = (edge, paths) => { export const positionEdgeLabel = (edge, paths) => {
logger.info('Moving label', edge.id, edge.label, edgeLabels[edge.id]); log.info('Moving label', edge.id, edge.label, edgeLabels[edge.id]);
let path = paths.updatedPath ? paths.updatedPath : paths.originalPath; let path = paths.updatedPath ? paths.updatedPath : paths.originalPath;
if (edge.label) { if (edge.label) {
const el = edgeLabels[edge.id]; const el = edgeLabels[edge.id];
@ -113,7 +113,7 @@ export const positionEdgeLabel = (edge, paths) => {
if (path) { if (path) {
// // debugger; // // debugger;
const pos = utils.calcLabelPosition(path); const pos = utils.calcLabelPosition(path);
logger.info('Moving label from (', x, ',', y, ') to (', pos.x, ',', pos.y, ')'); log.info('Moving label from (', x, ',', y, ') to (', pos.x, ',', pos.y, ')');
// x = pos.x; // x = pos.x;
// y = pos.y; // y = pos.y;
} }
@ -185,7 +185,7 @@ export const positionEdgeLabel = (edge, paths) => {
// }; // };
const outsideNode = (node, point) => { const outsideNode = (node, point) => {
// logger.warn('Checking bounds ', node, point); // log.warn('Checking bounds ', node, point);
const x = node.x; const x = node.x;
const y = node.y; const y = node.y;
const dx = Math.abs(point.x - x); const dx = Math.abs(point.x - x);
@ -199,7 +199,7 @@ const outsideNode = (node, point) => {
}; };
export const intersection = (node, outsidePoint, insidePoint) => { export const intersection = (node, outsidePoint, insidePoint) => {
logger.warn('intersection calc o:', outsidePoint, ' i:', insidePoint, node); log.warn('intersection calc o:', outsidePoint, ' i:', insidePoint, node);
const x = node.x; const x = node.x;
const y = node.y; const y = node.y;
@ -221,7 +221,7 @@ export const intersection = (node, outsidePoint, insidePoint) => {
outsidePoint.y === edges.y1 || outsidePoint.y === edges.y1 ||
outsidePoint.y === edges.y2 outsidePoint.y === edges.y2
) { ) {
logger.warn('calc equals on edge'); log.warn('calc equals on edge');
return outsidePoint; return outsidePoint;
} }
@ -237,7 +237,7 @@ export const intersection = (node, outsidePoint, insidePoint) => {
x: insidePoint.x < outsidePoint.x ? insidePoint.x + R - r : insidePoint.x - r, x: insidePoint.x < outsidePoint.x ? insidePoint.x + R - r : insidePoint.x - r,
y: insidePoint.y < outsidePoint.y ? insidePoint.y + Q - q : insidePoint.y - q y: insidePoint.y < outsidePoint.y ? insidePoint.y + Q - q : insidePoint.y - q
}; };
logger.warn(`topp/bott calc, Q ${Q}, q ${q}, R ${R}, r ${r}`, res); log.warn(`topp/bott calc, Q ${Q}, q ${q}, R ${R}, r ${r}`, res);
return res; return res;
} else { } else {
@ -252,7 +252,7 @@ export const intersection = (node, outsidePoint, insidePoint) => {
r = x - w - outsidePoint.x; r = x - w - outsidePoint.x;
} }
let q = (q = (Q * r) / R); let q = (q = (Q * r) / R);
logger.warn(`sides calc, Q ${Q}, q ${q}, R ${R}, r ${r}`, { log.warn(`sides calc, Q ${Q}, q ${q}, R ${R}, r ${r}`, {
x: insidePoint.x < outsidePoint.x ? insidePoint.x + R - r : insidePoint.x + dx - w, x: insidePoint.x < outsidePoint.x ? insidePoint.x + R - r : insidePoint.x + dx - w,
y: insidePoint.y < outsidePoint.y ? insidePoint.y + q : insidePoint.y - q y: insidePoint.y < outsidePoint.y ? insidePoint.y + q : insidePoint.y - q
}); });
@ -274,7 +274,7 @@ export const insertEdge = function(elem, e, edge, clusterDb, diagramType, graph)
if (head.intersect && tail.intersect) { if (head.intersect && tail.intersect) {
points = points.slice(1, edge.points.length - 1); points = points.slice(1, edge.points.length - 1);
points.unshift(tail.intersect(points[0])); points.unshift(tail.intersect(points[0]));
logger.info( log.info(
'Last point', 'Last point',
points[points.length - 1], points[points.length - 1],
head, head,
@ -283,8 +283,8 @@ export const insertEdge = function(elem, e, edge, clusterDb, diagramType, graph)
points.push(head.intersect(points[points.length - 1])); points.push(head.intersect(points[points.length - 1]));
} }
if (edge.toCluster) { if (edge.toCluster) {
logger.trace('edge', edge); log.trace('edge', edge);
logger.trace('to cluster', clusterDb[edge.toCluster]); log.trace('to cluster', clusterDb[edge.toCluster]);
points = []; points = [];
let lastPointOutside; let lastPointOutside;
let isInside = false; let isInside = false;
@ -292,7 +292,7 @@ export const insertEdge = function(elem, e, edge, clusterDb, diagramType, graph)
const node = clusterDb[edge.toCluster].node; const node = clusterDb[edge.toCluster].node;
if (!outsideNode(node, point) && !isInside) { if (!outsideNode(node, point) && !isInside) {
logger.trace('inside', edge.toCluster, point, lastPointOutside); log.trace('inside', edge.toCluster, point, lastPointOutside);
// First point inside the rect // First point inside the rect
const inter = intersection(node, lastPointOutside, point); const inter = intersection(node, lastPointOutside, point);
@ -305,7 +305,7 @@ export const insertEdge = function(elem, e, edge, clusterDb, diagramType, graph)
if (!points.find(e => e.x === inter.x && e.y === inter.y)) { if (!points.find(e => e.x === inter.x && e.y === inter.y)) {
points.push(inter); points.push(inter);
} else { } else {
logger.warn('no intersect', inter, points); log.warn('no intersect', inter, points);
} }
isInside = true; isInside = true;
} else { } else {
@ -317,8 +317,8 @@ export const insertEdge = function(elem, e, edge, clusterDb, diagramType, graph)
} }
if (edge.fromCluster) { if (edge.fromCluster) {
logger.trace('edge', edge); log.trace('edge', edge);
logger.warn('from cluster', clusterDb[edge.fromCluster]); log.warn('from cluster', clusterDb[edge.fromCluster]);
const updatedPoints = []; const updatedPoints = [];
let lastPointOutside; let lastPointOutside;
let isInside = false; let isInside = false;
@ -327,17 +327,17 @@ export const insertEdge = function(elem, e, edge, clusterDb, diagramType, graph)
const node = clusterDb[edge.fromCluster].node; const node = clusterDb[edge.fromCluster].node;
if (!outsideNode(node, point) && !isInside) { if (!outsideNode(node, point) && !isInside) {
logger.warn('inside', edge.fromCluster, point, node); log.warn('inside', edge.fromCluster, point, node);
// First point inside the rect // First point inside the rect
const insterection = intersection(node, lastPointOutside, point); const insterection = intersection(node, lastPointOutside, point);
// logger.trace('intersect', intersection(node, lastPointOutside, point)); // log.trace('intersect', intersection(node, lastPointOutside, point));
updatedPoints.unshift(insterection); updatedPoints.unshift(insterection);
// points.push(insterection); // points.push(insterection);
isInside = true; isInside = true;
} else { } else {
// at the outside // at the outside
logger.trace('Outside point', point); log.trace('Outside point', point);
if (!isInside) updatedPoints.unshift(point); if (!isInside) updatedPoints.unshift(point);
} }
lastPointOutside = point; lastPointOutside = point;
@ -412,8 +412,8 @@ export const insertEdge = function(elem, e, edge, clusterDb, diagramType, graph)
url = url.replace(/\(/g, '\\('); url = url.replace(/\(/g, '\\(');
url = url.replace(/\)/g, '\\)'); url = url.replace(/\)/g, '\\)');
} }
logger.info('arrowTypeStart', edge.arrowTypeStart); log.info('arrowTypeStart', edge.arrowTypeStart);
logger.info('arrowTypeEnd', edge.arrowTypeEnd); log.info('arrowTypeEnd', edge.arrowTypeEnd);
switch (edge.arrowTypeStart) { switch (edge.arrowTypeStart) {
case 'arrow_cross': case 'arrow_cross':

View File

@ -1,5 +1,5 @@
import { intersection } from './edges'; import { intersection } from './edges';
import { setLogLevel, logger } from '../logger'; import { setLogLevel, log } from '../logger';
describe('Graphlib decorations', () => { describe('Graphlib decorations', () => {
let node; let node;

View File

@ -12,7 +12,7 @@ import {
import { insertNode, positionNode, clear as clearNodes, setNodeElem } from './nodes'; import { insertNode, positionNode, clear as clearNodes, setNodeElem } from './nodes';
import { insertCluster, clear as clearClusters } from './clusters'; import { insertCluster, clear as clearClusters } from './clusters';
import { insertEdgeLabel, positionEdgeLabel, insertEdge, clear as clearEdges } from './edges'; import { insertEdgeLabel, positionEdgeLabel, insertEdge, clear as clearEdges } from './edges';
import { logger as log } from '../logger'; import { log } from '../logger';
const recursiveRender = (_elem, graph, diagramtype, parentCluster) => { const recursiveRender = (_elem, graph, diagramtype, parentCluster) => {
log.info('Graph in recursive render: XXX', graphlib.json.write(graph), parentCluster); log.info('Graph in recursive render: XXX', graphlib.json.write(graph), parentCluster);

View File

@ -2,7 +2,7 @@
* Setup arrow head and define the marker. The result is appended to the svg. * Setup arrow head and define the marker. The result is appended to the svg.
*/ */
import { logger } from '../logger'; import { log } from '../logger';
// Only add the number of markers that the diagram needs // Only add the number of markers that the diagram needs
const insertMarkers = (elem, markerArray, type, id) => { const insertMarkers = (elem, markerArray, type, id) => {
@ -12,7 +12,7 @@ const insertMarkers = (elem, markerArray, type, id) => {
}; };
const extension = (elem, type, id) => { const extension = (elem, type, id) => {
logger.trace('Making markers for ', id); log.trace('Making markers for ', id);
elem elem
.append('defs') .append('defs')
.append('marker') .append('marker')

View File

@ -1,7 +1,7 @@
/** /**
* Decorates with functions required by mermaids dagre-wrapper. * Decorates with functions required by mermaids dagre-wrapper.
*/ */
import { logger as log } from '../logger'; import { log } from '../logger';
import graphlib from 'graphlib'; import graphlib from 'graphlib';
export let clusterDb = {}; export let clusterDb = {};

View File

@ -1,7 +1,7 @@
import graphlib from 'graphlib'; import graphlib from 'graphlib';
import dagre from 'dagre'; import dagre from 'dagre';
import { validate, adjustClustersAndEdges, extractDecendants, sortNodesByHierarchy } from './mermaid-graphlib'; import { validate, adjustClustersAndEdges, extractDecendants, sortNodesByHierarchy } from './mermaid-graphlib';
import { setLogLevel, logger } from '../logger'; import { setLogLevel, log } from '../logger';
describe('Graphlib decorations', () => { describe('Graphlib decorations', () => {
let g; let g;
@ -65,7 +65,7 @@ describe('Graphlib decorations', () => {
g.setEdge('C1', 'C2'); g.setEdge('C1', 'C2');
adjustClustersAndEdges(g); adjustClustersAndEdges(g);
logger.info(g.edges()) log.info(g.edges())
expect(validate(g)).toBe(true); expect(validate(g)).toBe(true);
}); });
@ -92,7 +92,7 @@ describe('Graphlib decorations', () => {
g.setEdge('C1', 'c', { name: 'C1-external-link' }); g.setEdge('C1', 'c', { name: 'C1-external-link' });
adjustClustersAndEdges(g); adjustClustersAndEdges(g);
logger.info(g.nodes()) log.info(g.nodes())
expect(g.nodes().length).toBe(2); expect(g.nodes().length).toBe(2);
expect(validate(g)).toBe(true); expect(validate(g)).toBe(true);
}); });
@ -114,9 +114,9 @@ describe('Graphlib decorations', () => {
// g.setEdge('a', 'b', { name: 'C1-internal-link' }); // g.setEdge('a', 'b', { name: 'C1-internal-link' });
g.setEdge('C1', 'C2', { name: 'C1-external-link' }); g.setEdge('C1', 'C2', { name: 'C1-external-link' });
logger.info(g.nodes()) log.info(g.nodes())
adjustClustersAndEdges(g); adjustClustersAndEdges(g);
logger.info(g.nodes()) log.info(g.nodes())
expect(g.nodes().length).toBe(2); expect(g.nodes().length).toBe(2);
expect(validate(g)).toBe(true); expect(validate(g)).toBe(true);
}); });
@ -133,9 +133,9 @@ describe('Graphlib decorations', () => {
g.setParent('a', 'C1'); g.setParent('a', 'C1');
g.setEdge('C1', 'b', { data: 'link1' }, '1'); g.setEdge('C1', 'b', { data: 'link1' }, '1');
// logger.info(g.edges()) // log.info(g.edges())
adjustClustersAndEdges(g); adjustClustersAndEdges(g);
logger.info(g.edges()) log.info(g.edges())
expect(g.nodes()).toEqual(['b', 'C1']); expect(g.nodes()).toEqual(['b', 'C1']);
expect(g.edges().length).toBe(1); expect(g.edges().length).toBe(1);
expect(validate(g)).toBe(true); expect(validate(g)).toBe(true);
@ -160,9 +160,9 @@ describe('Graphlib decorations', () => {
g.setEdge('C1', 'b', { data: 'link1' }, '1'); g.setEdge('C1', 'b', { data: 'link1' }, '1');
g.setEdge('C1', 'c', { data: 'link2' }, '2'); g.setEdge('C1', 'c', { data: 'link2' }, '2');
logger.info(g.node('C1')) log.info(g.node('C1'))
adjustClustersAndEdges(g); adjustClustersAndEdges(g);
logger.info(g.edges()) log.info(g.edges())
expect(g.nodes()).toEqual(['b', 'c', 'C1']); expect(g.nodes()).toEqual(['b', 'c', 'C1']);
expect(g.nodes().length).toBe(3); expect(g.nodes().length).toBe(3);
expect(g.edges().length).toBe(2); expect(g.edges().length).toBe(2);
@ -198,7 +198,7 @@ describe('Graphlib decorations', () => {
g.setEdge('A', 'B', { data: 'link1' }, '1'); g.setEdge('A', 'B', { data: 'link1' }, '1');
g.setEdge('A', 'C', { data: 'link2' }, '2'); g.setEdge('A', 'C', { data: 'link2' }, '2');
// logger.info(g.edges()) // log.info(g.edges())
adjustClustersAndEdges(g); adjustClustersAndEdges(g);
expect(g.nodes()).toEqual(['A', 'B', 'C']); expect(g.nodes()).toEqual(['A', 'B', 'C']);
expect(g.edges().length).toBe(2); expect(g.edges().length).toBe(2);
@ -228,10 +228,10 @@ describe('Graphlib decorations', () => {
g.setParent('d', 'D'); g.setParent('d', 'D');
g.setParent('D', 'C'); g.setParent('D', 'C');
// logger.info('Graph before', g.node('D')) // log.info('Graph before', g.node('D'))
// logger.info('Graph before', graphlib.json.write(g)) // log.info('Graph before', graphlib.json.write(g))
adjustClustersAndEdges(g); adjustClustersAndEdges(g);
// logger.info('Graph after', graphlib.json.write(g), g.node('C').graph) // log.info('Graph after', graphlib.json.write(g), g.node('C').graph)
const CGraph = g.node('C').graph; const CGraph = g.node('C').graph;
const DGraph = CGraph.node('D').graph; const DGraph = CGraph.node('D').graph;
@ -274,10 +274,10 @@ describe('Graphlib decorations', () => {
g.setEdge('A', 'B', { data: 'link1' }, '1'); g.setEdge('A', 'B', { data: 'link1' }, '1');
g.setEdge('A', 'C', { data: 'link2' }, '2'); g.setEdge('A', 'C', { data: 'link2' }, '2');
logger.info('Graph before', g.node('D')) log.info('Graph before', g.node('D'))
logger.info('Graph before', graphlib.json.write(g)) log.info('Graph before', graphlib.json.write(g))
adjustClustersAndEdges(g); adjustClustersAndEdges(g);
logger.trace('Graph after', graphlib.json.write(g)) log.trace('Graph after', graphlib.json.write(g))
expect(g.nodes()).toEqual(['C', 'B', 'A']); expect(g.nodes()).toEqual(['C', 'B', 'A']);
expect(g.nodes().length).toBe(3); expect(g.nodes().length).toBe(3);
expect(g.edges().length).toBe(2); expect(g.edges().length).toBe(2);
@ -285,14 +285,14 @@ describe('Graphlib decorations', () => {
const AGraph = g.node('A').graph; const AGraph = g.node('A').graph;
const BGraph = g.node('B').graph; const BGraph = g.node('B').graph;
const CGraph = g.node('C').graph; const CGraph = g.node('C').graph;
// logger.info(CGraph.nodes()); // log.info(CGraph.nodes());
const DGraph = CGraph.node('D').graph; const DGraph = CGraph.node('D').graph;
// logger.info('DG', CGraph.children('D')); // log.info('DG', CGraph.children('D'));
logger.info('A', AGraph.nodes()); log.info('A', AGraph.nodes());
expect(AGraph.nodes().length).toBe(1); expect(AGraph.nodes().length).toBe(1);
expect(AGraph.nodes()).toEqual(['a']); expect(AGraph.nodes()).toEqual(['a']);
logger.trace('Nodes', BGraph.nodes()) log.trace('Nodes', BGraph.nodes())
expect(BGraph.nodes().length).toBe(1); expect(BGraph.nodes().length).toBe(1);
expect(BGraph.nodes()).toEqual(['b']); expect(BGraph.nodes()).toEqual(['b']);
expect(CGraph.nodes()).toEqual(['D']); expect(CGraph.nodes()).toEqual(['D']);
@ -330,11 +330,11 @@ describe('Graphlib decorations', () => {
g.setEdge('c', 'd', { data: 'link2' }, '2'); g.setEdge('c', 'd', { data: 'link2' }, '2');
g.setEdge('d', 'e', { data: 'link2' }, '2'); g.setEdge('d', 'e', { data: 'link2' }, '2');
logger.info('Graph before', graphlib.json.write(g)) log.info('Graph before', graphlib.json.write(g))
adjustClustersAndEdges(g); adjustClustersAndEdges(g);
const bGraph = g.node('b').graph; const bGraph = g.node('b').graph;
// logger.trace('Graph after', graphlib.json.write(g)) // log.trace('Graph after', graphlib.json.write(g))
logger.info('Graph after', graphlib.json.write(bGraph)); log.info('Graph after', graphlib.json.write(bGraph));
expect(bGraph.nodes().length).toBe(3); expect(bGraph.nodes().length).toBe(3);
expect(bGraph.edges().length).toBe(2); expect(bGraph.edges().length).toBe(2);
}); });
@ -356,13 +356,13 @@ describe('Graphlib decorations', () => {
g.setParent('c', 'b'); g.setParent('c', 'b');
g.setParent('e', 'c'); g.setParent('e', 'c');
logger.info('Graph before', graphlib.json.write(g)) log.info('Graph before', graphlib.json.write(g))
adjustClustersAndEdges(g); adjustClustersAndEdges(g);
const aGraph = g.node('a').graph; const aGraph = g.node('a').graph;
const bGraph = aGraph.node('b').graph; const bGraph = aGraph.node('b').graph;
logger.info('Graph after', graphlib.json.write(aGraph)); log.info('Graph after', graphlib.json.write(aGraph));
const cGraph = bGraph.node('c').graph; const cGraph = bGraph.node('c').graph;
// logger.trace('Graph after', graphlib.json.write(g)) // log.trace('Graph after', graphlib.json.write(g))
expect(aGraph.nodes().length).toBe(1); expect(aGraph.nodes().length).toBe(1);
expect(bGraph.nodes().length).toBe(1); expect(bGraph.nodes().length).toBe(1);
expect(cGraph.nodes().length).toBe(1); expect(cGraph.nodes().length).toBe(1);
@ -385,12 +385,12 @@ flowchart TB
const exportedGraph = JSON.parse('{"options":{"directed":true,"multigraph":true,"compound":true},"nodes":[{"v":"A","value":{"labelStyle":"","shape":"rect","labelText":"A","rx":0,"ry":0,"class":"default","style":"","id":"A","width":500,"type":"group","padding":15}},{"v":"B","value":{"labelStyle":"","shape":"rect","labelText":"B","rx":0,"ry":0,"class":"default","style":"","id":"B","width":500,"type":"group","padding":15},"parent":"A"},{"v":"b","value":{"labelStyle":"","shape":"rect","labelText":"b","rx":0,"ry":0,"class":"default","style":"","id":"b","padding":15},"parent":"A"},{"v":"c","value":{"labelStyle":"","shape":"rect","labelText":"c","rx":0,"ry":0,"class":"default","style":"","id":"c","padding":15},"parent":"B"},{"v":"a","value":{"labelStyle":"","shape":"rect","labelText":"a","rx":0,"ry":0,"class":"default","style":"","id":"a","padding":15},"parent":"A"}],"edges":[{"v":"b","w":"B","name":"1","value":{"minlen":1,"arrowhead":"normal","arrowTypeStart":"arrow_open","arrowTypeEnd":"arrow_point","thickness":"normal","pattern":"solid","style":"fill:none","labelStyle":"","arrowheadStyle":"fill: #333","labelpos":"c","labelType":"text","label":"","id":"L-b-B","classes":"flowchart-link LS-b LE-B"}},{"v":"a","w":"c","name":"2","value":{"minlen":1,"arrowhead":"normal","arrowTypeStart":"arrow_open","arrowTypeEnd":"arrow_point","thickness":"normal","pattern":"solid","style":"fill:none","labelStyle":"","arrowheadStyle":"fill: #333","labelpos":"c","labelType":"text","label":"","id":"L-a-c","classes":"flowchart-link LS-a LE-c"}}],"value":{"rankdir":"TB","nodesep":50,"ranksep":50,"marginx":8,"marginy":8}}'); const exportedGraph = JSON.parse('{"options":{"directed":true,"multigraph":true,"compound":true},"nodes":[{"v":"A","value":{"labelStyle":"","shape":"rect","labelText":"A","rx":0,"ry":0,"class":"default","style":"","id":"A","width":500,"type":"group","padding":15}},{"v":"B","value":{"labelStyle":"","shape":"rect","labelText":"B","rx":0,"ry":0,"class":"default","style":"","id":"B","width":500,"type":"group","padding":15},"parent":"A"},{"v":"b","value":{"labelStyle":"","shape":"rect","labelText":"b","rx":0,"ry":0,"class":"default","style":"","id":"b","padding":15},"parent":"A"},{"v":"c","value":{"labelStyle":"","shape":"rect","labelText":"c","rx":0,"ry":0,"class":"default","style":"","id":"c","padding":15},"parent":"B"},{"v":"a","value":{"labelStyle":"","shape":"rect","labelText":"a","rx":0,"ry":0,"class":"default","style":"","id":"a","padding":15},"parent":"A"}],"edges":[{"v":"b","w":"B","name":"1","value":{"minlen":1,"arrowhead":"normal","arrowTypeStart":"arrow_open","arrowTypeEnd":"arrow_point","thickness":"normal","pattern":"solid","style":"fill:none","labelStyle":"","arrowheadStyle":"fill: #333","labelpos":"c","labelType":"text","label":"","id":"L-b-B","classes":"flowchart-link LS-b LE-B"}},{"v":"a","w":"c","name":"2","value":{"minlen":1,"arrowhead":"normal","arrowTypeStart":"arrow_open","arrowTypeEnd":"arrow_point","thickness":"normal","pattern":"solid","style":"fill:none","labelStyle":"","arrowheadStyle":"fill: #333","labelpos":"c","labelType":"text","label":"","id":"L-a-c","classes":"flowchart-link LS-a LE-c"}}],"value":{"rankdir":"TB","nodesep":50,"ranksep":50,"marginx":8,"marginy":8}}');
const gr = graphlib.json.read(exportedGraph) const gr = graphlib.json.read(exportedGraph)
logger.info('Graph before', graphlib.json.write(gr)) log.info('Graph before', graphlib.json.write(gr))
adjustClustersAndEdges(gr); adjustClustersAndEdges(gr);
const aGraph = gr.node('A').graph; const aGraph = gr.node('A').graph;
const bGraph = aGraph.node('B').graph; const bGraph = aGraph.node('B').graph;
logger.info('Graph after', graphlib.json.write(aGraph)); log.info('Graph after', graphlib.json.write(aGraph));
// logger.trace('Graph after', graphlib.json.write(g)) // log.trace('Graph after', graphlib.json.write(g))
expect(aGraph.parent('c')).toBe('B'); expect(aGraph.parent('c')).toBe('B');
expect(aGraph.parent('B')).toBe(undefined); expect(aGraph.parent('B')).toBe(undefined);
}); });
@ -438,7 +438,7 @@ describe('extractDecendants', function () {
g.setEdge('A', 'B', { data: 'link1' }, '1'); g.setEdge('A', 'B', { data: 'link1' }, '1');
g.setEdge('A', 'C', { data: 'link2' }, '2'); g.setEdge('A', 'C', { data: 'link2' }, '2');
// logger.info(g.edges()) // log.info(g.edges())
const d1 = extractDecendants('A',g) const d1 = extractDecendants('A',g)
const d2 = extractDecendants('B',g) const d2 = extractDecendants('B',g)
const d3 = extractDecendants('C',g) const d3 = extractDecendants('C',g)

View File

@ -1,5 +1,5 @@
import { select } from 'd3'; import { select } from 'd3';
import { logger } from '../logger'; // eslint-disable-line import { log } from '../logger'; // eslint-disable-line
import { labelHelper, updateNodeBounds, insertPolygonShape } from './shapes/util'; import { labelHelper, updateNodeBounds, insertPolygonShape } from './shapes/util';
import { getConfig } from '../config'; import { getConfig } from '../config';
import intersect from './intersect/index.js'; import intersect from './intersect/index.js';
@ -20,12 +20,14 @@ const question = (parent, node) => {
{ x: 0, y: -s / 2 } { x: 0, y: -s / 2 }
]; ];
log.info('Question main (Circle)');
const questionElem = insertPolygonShape(shapeSvg, s, s, points); const questionElem = insertPolygonShape(shapeSvg, s, s, points);
questionElem.attr('style', node.style); questionElem.attr('style', node.style);
updateNodeBounds(node, questionElem); updateNodeBounds(node, questionElem);
node.intersect = function(point) { node.intersect = function(point) {
logger.warn('Intersect called'); log.warn('Intersect called');
return intersect.polygon(node, points, point); return intersect.polygon(node, points, point);
}; };
@ -272,7 +274,7 @@ const cylinder = (parent, node) => {
const rect = (parent, node) => { const rect = (parent, node) => {
const { shapeSvg, bbox, halfPadding } = labelHelper(parent, node, 'node ' + node.classes, true); const { shapeSvg, bbox, halfPadding } = labelHelper(parent, node, 'node ' + node.classes, true);
logger.trace('Classes = ', node.classes); log.trace('Classes = ', node.classes);
// add the rect // add the rect
const rect = shapeSvg.insert('rect', ':first-child'); const rect = shapeSvg.insert('rect', ':first-child');
@ -318,7 +320,7 @@ const rectWithTitle = (parent, node) => {
const label = shapeSvg.insert('g').attr('class', 'label'); const label = shapeSvg.insert('g').attr('class', 'label');
const text2 = node.labelText.flat(); const text2 = node.labelText.flat();
logger.info('Label text', text2[0]); log.info('Label text', text2[0]);
const text = label.node().appendChild(createLabel(text2[0], node.labelStyle, true, true)); const text = label.node().appendChild(createLabel(text2[0], node.labelStyle, true, true));
let bbox; let bbox;
@ -329,7 +331,7 @@ const rectWithTitle = (parent, node) => {
dv.attr('width', bbox.width); dv.attr('width', bbox.width);
dv.attr('height', bbox.height); dv.attr('height', bbox.height);
} }
logger.info('Text 2', text2); log.info('Text 2', text2);
const textRows = text2.slice(1, text2.length); const textRows = text2.slice(1, text2.length);
let titleBox = text.getBBox(); let titleBox = text.getBBox();
const descr = label const descr = label
@ -344,7 +346,7 @@ const rectWithTitle = (parent, node) => {
dv.attr('height', bbox.height); dv.attr('height', bbox.height);
} }
// bbox = label.getBBox(); // bbox = label.getBBox();
// logger.info(descr); // log.info(descr);
const halfPadding = node.padding / 2; const halfPadding = node.padding / 2;
select(descr).attr( select(descr).attr(
'transform', 'transform',
@ -437,12 +439,12 @@ const circle = (parent, node) => {
.attr('width', bbox.width + node.padding) .attr('width', bbox.width + node.padding)
.attr('height', bbox.height + node.padding); .attr('height', bbox.height + node.padding);
logger.info('Circle main'); log.info('Circle main');
updateNodeBounds(node, circle); updateNodeBounds(node, circle);
node.intersect = function(point) { node.intersect = function(point) {
logger.info('Circle intersect', node, bbox.width / 2 + halfPadding, point); log.info('Circle intersect', node, bbox.width / 2 + halfPadding, point);
return intersect.circle(node, bbox.width / 2 + halfPadding, point); return intersect.circle(node, bbox.width / 2 + halfPadding, point);
}; };
@ -752,7 +754,7 @@ const class_box = (parent, node) => {
// } // }
// bbox = labelContainer.getBBox(); // bbox = labelContainer.getBBox();
// logger.info('Text 2', text2); // log.info('Text 2', text2);
// const textRows = text2.slice(1, text2.length); // const textRows = text2.slice(1, text2.length);
// let titleBox = text.getBBox(); // let titleBox = text.getBBox();
// const descr = label // const descr = label
@ -767,7 +769,7 @@ const class_box = (parent, node) => {
// dv.attr('height', bbox.height); // dv.attr('height', bbox.height);
// } // }
// // bbox = label.getBBox(); // // bbox = label.getBBox();
// // logger.info(descr); // // log.info(descr);
// select(descr).attr( // select(descr).attr(
// 'transform', // 'transform',
// 'translate( ' + // 'translate( ' +
@ -882,7 +884,7 @@ export const clear = () => {
export const positionNode = node => { export const positionNode = node => {
const el = nodeElems[node.id]; const el = nodeElems[node.id];
logger.trace( log.trace(
'Transforming node', 'Transforming node',
node, node,
'translate(' + (node.x - node.width / 2 - 5) + ', ' + (node.y - node.height / 2 - 5) + ')' 'translate(' + (node.x - node.width / 2 - 5) + ', ' + (node.y - node.height / 2 - 5) + ')'

View File

@ -2,7 +2,7 @@
* Setup arrow head and define the marker. The result is appended to the svg. * Setup arrow head and define the marker. The result is appended to the svg.
*/ */
// import { logger } from '../logger'; // import { log } from '../logger';
// Only add the number of markers that the diagram needs // Only add the number of markers that the diagram needs
const insertPatterns = (elem, patternArray, type, id) => { const insertPatterns = (elem, patternArray, type, id) => {

View File

@ -1,11 +1,11 @@
import { updateNodeBounds, labelHelper } from './util'; import { updateNodeBounds, labelHelper } from './util';
import { logger } from '../../logger'; // eslint-disable-line import { log } from '../../logger'; // eslint-disable-line
import intersect from '../intersect/index.js'; import intersect from '../intersect/index.js';
const note = (parent, node) => { const note = (parent, node) => {
const { shapeSvg, bbox, halfPadding } = labelHelper(parent, node, 'node ' + node.classes, true); const { shapeSvg, bbox, halfPadding } = labelHelper(parent, node, 'node ' + node.classes, true);
logger.info('Classes = ', node.classes); log.info('Classes = ', node.classes);
// add the rect // add the rect
const rect = shapeSvg.insert('rect', ':first-child'); const rect = shapeSvg.insert('rect', ':first-child');

View File

@ -1,5 +1,5 @@
import { select } from 'd3'; import { select } from 'd3';
import { logger } from '../../logger'; import { log } from '../../logger';
import * as configApi from '../../config'; import * as configApi from '../../config';
import common from '../common/common'; import common from '../common/common';
import utils from '../../utils'; import utils from '../../utils';
@ -87,7 +87,7 @@ export const getRelations = function() {
}; };
export const addRelation = function(relation) { export const addRelation = function(relation) {
logger.debug('Adding relation: ' + JSON.stringify(relation)); log.debug('Adding relation: ' + JSON.stringify(relation));
addClass(relation.id1); addClass(relation.id1);
addClass(relation.id2); addClass(relation.id2);

View File

@ -1,7 +1,7 @@
import { select } from 'd3'; import { select } from 'd3';
import dagre from 'dagre'; import dagre from 'dagre';
import graphlib from 'graphlib'; import graphlib from 'graphlib';
import { logger } from '../../logger'; import { log } from '../../logger';
import classDb, { lookUpDomId } from './classDb'; import classDb, { lookUpDomId } from './classDb';
import { parser } from './parser/classDiagram'; import { parser } from './parser/classDiagram';
import svgDraw from './svgDraw'; import svgDraw from './svgDraw';
@ -31,8 +31,8 @@ const conf = {
export const addClasses = function(classes, g) { export const addClasses = function(classes, g) {
// const svg = select(`[id="${svgId}"]`); // const svg = select(`[id="${svgId}"]`);
const keys = Object.keys(classes); const keys = Object.keys(classes);
logger.info('keys:', keys); log.info('keys:', keys);
logger.info(classes); log.info(classes);
// Iterate through each item in the vertex object (containing all the vertices found) in the graph definition // Iterate through each item in the vertex object (containing all the vertices found) in the graph definition
keys.forEach(function(id) { keys.forEach(function(id) {
@ -112,7 +112,7 @@ export const addClasses = function(classes, g) {
padding: getConfig().flowchart.padding padding: getConfig().flowchart.padding
}); });
logger.info('setNode', { log.info('setNode', {
labelStyle: styles.labelStyle, labelStyle: styles.labelStyle,
shape: _shape, shape: _shape,
labelText: vertexText, labelText: vertexText,
@ -160,7 +160,7 @@ export const addRelations = function(relations, g) {
edgeData.arrowhead = 'normal'; edgeData.arrowhead = 'normal';
} }
logger.info(edgeData, edge); log.info(edgeData, edge);
//Set edge extra labels //Set edge extra labels
//edgeData.startLabelLeft = edge.relationTitle1; //edgeData.startLabelLeft = edge.relationTitle1;
edgeData.startLabelRight = edge.relationTitle1 === 'none' ? '' : edge.relationTitle1; edgeData.startLabelRight = edge.relationTitle1 === 'none' ? '' : edge.relationTitle1;
@ -257,7 +257,7 @@ export const drawOld = function(text, id) {
parser.yy.clear(); parser.yy.clear();
parser.parse(text); parser.parse(text);
logger.info('Rendering diagram ' + text); log.info('Rendering diagram ' + text);
// Fetch the default direction, use TD if none was found // Fetch the default direction, use TD if none was found
const diagram = select(`[id='${id}']`); const diagram = select(`[id='${id}']`);
@ -279,8 +279,8 @@ export const drawOld = function(text, id) {
}); });
const classes = classDb.getClasses(); const classes = classDb.getClasses();
logger.info('classes:'); log.info('classes:');
logger.info(classes); log.info(classes);
const keys = Object.keys(classes); const keys = Object.keys(classes);
for (let i = 0; i < keys.length; i++) { for (let i = 0; i < keys.length; i++) {
const classDef = classes[keys[i]]; const classDef = classes[keys[i]];
@ -292,13 +292,13 @@ export const drawOld = function(text, id) {
// our nodes. // our nodes.
g.setNode(node.id, node); g.setNode(node.id, node);
logger.info('Org height: ' + node.height); log.info('Org height: ' + node.height);
} }
const relations = classDb.getRelations(); const relations = classDb.getRelations();
logger.info('relations:', relations); log.info('relations:', relations);
relations.forEach(function(relation) { relations.forEach(function(relation) {
logger.info( log.info(
'tjoho' + getGraphId(relation.id1) + getGraphId(relation.id2) + JSON.stringify(relation) 'tjoho' + getGraphId(relation.id1) + getGraphId(relation.id2) + JSON.stringify(relation)
); );
g.setEdge( g.setEdge(
@ -314,7 +314,7 @@ export const drawOld = function(text, id) {
dagre.layout(g); dagre.layout(g);
g.nodes().forEach(function(v) { g.nodes().forEach(function(v) {
if (typeof v !== 'undefined' && typeof g.node(v) !== 'undefined') { if (typeof v !== 'undefined' && typeof g.node(v) !== 'undefined') {
logger.debug('Node ' + v + ': ' + JSON.stringify(g.node(v))); log.debug('Node ' + v + ': ' + JSON.stringify(g.node(v)));
select('#' + lookUpDomId(v)).attr( select('#' + lookUpDomId(v)).attr(
'transform', 'transform',
'translate(' + 'translate(' +
@ -328,7 +328,7 @@ export const drawOld = function(text, id) {
g.edges().forEach(function(e) { g.edges().forEach(function(e) {
if (typeof e !== 'undefined' && typeof g.edge(e) !== 'undefined') { if (typeof e !== 'undefined' && typeof g.edge(e) !== 'undefined') {
logger.debug('Edge ' + e.v + ' -> ' + e.w + ': ' + JSON.stringify(g.edge(e))); log.debug('Edge ' + e.v + ' -> ' + e.w + ': ' + JSON.stringify(g.edge(e)));
svgDraw.drawEdge(diagram, g.edge(e), g.edge(e).relation, conf); svgDraw.drawEdge(diagram, g.edge(e), g.edge(e).relation, conf);
} }
}); });
@ -341,12 +341,12 @@ export const drawOld = function(text, id) {
// Ensure the viewBox includes the whole svgBounds area with extra space for padding // Ensure the viewBox includes the whole svgBounds area with extra space for padding
const vBox = `${svgBounds.x - padding} ${svgBounds.y - padding} ${width} ${height}`; const vBox = `${svgBounds.x - padding} ${svgBounds.y - padding} ${width} ${height}`;
logger.debug(`viewBox ${vBox}`); log.debug(`viewBox ${vBox}`);
diagram.attr('viewBox', vBox); diagram.attr('viewBox', vBox);
}; };
export const draw = function(text, id) { export const draw = function(text, id) {
logger.info('Drawing class'); log.info('Drawing class');
classDb.clear(); classDb.clear();
// const parser = classDb.parser; // const parser = classDb.parser;
// parser.yy = classDb; // parser.yy = classDb;
@ -355,14 +355,14 @@ export const draw = function(text, id) {
// try { // try {
parser.parse(text); parser.parse(text);
// } catch (err) { // } catch (err) {
// logger.debug('Parsing failed'); // log.debug('Parsing failed');
// } // }
// Fetch the default direction, use TD if none was found // Fetch the default direction, use TD if none was found
let dir = 'TD'; let dir = 'TD';
const conf = getConfig().flowchart; const conf = getConfig().flowchart;
logger.info('config:', conf); log.info('config:', conf);
const nodeSpacing = conf.nodeSpacing || 50; const nodeSpacing = conf.nodeSpacing || 50;
const rankSpacing = conf.rankSpacing || 50; const rankSpacing = conf.rankSpacing || 50;
@ -384,10 +384,10 @@ export const draw = function(text, id) {
// let subG; // let subG;
// const subGraphs = flowDb.getSubGraphs(); // const subGraphs = flowDb.getSubGraphs();
// logger.info('Subgraphs - ', subGraphs); // log.info('Subgraphs - ', subGraphs);
// for (let i = subGraphs.length - 1; i >= 0; i--) { // for (let i = subGraphs.length - 1; i >= 0; i--) {
// subG = subGraphs[i]; // subG = subGraphs[i];
// logger.info('Subgraph - ', subG); // log.info('Subgraph - ', subG);
// flowDb.addVertex(subG.id, subG.title, 'group', undefined, subG.classes); // flowDb.addVertex(subG.id, subG.title, 'group', undefined, subG.classes);
// } // }
@ -395,7 +395,7 @@ export const draw = function(text, id) {
const classes = classDb.getClasses(); const classes = classDb.getClasses();
const relations = classDb.getRelations(); const relations = classDb.getRelations();
logger.info(relations); log.info(relations);
// let i = 0; // let i = 0;
// for (i = subGraphs.length - 1; i >= 0; i--) { // for (i = subGraphs.length - 1; i >= 0; i--) {
// subG = subGraphs[i]; // subG = subGraphs[i];
@ -428,7 +428,7 @@ export const draw = function(text, id) {
const svgBounds = svg.node().getBBox(); const svgBounds = svg.node().getBBox();
const width = svgBounds.width + padding * 2; const width = svgBounds.width + padding * 2;
const height = svgBounds.height + padding * 2; const height = svgBounds.height + padding * 2;
logger.debug( log.debug(
`new ViewBox 0 0 ${width} ${height}`, `new ViewBox 0 0 ${width} ${height}`,
`translate(${padding - g._label.marginx}, ${padding - g._label.marginy})` `translate(${padding - g._label.marginx}, ${padding - g._label.marginy})`
); );

View File

@ -1,7 +1,7 @@
import { select } from 'd3'; import { select } from 'd3';
import dagre from 'dagre'; import dagre from 'dagre';
import graphlib from 'graphlib'; import graphlib from 'graphlib';
import { logger } from '../../logger'; import { log } from '../../logger';
import classDb, { lookUpDomId } from './classDb'; import classDb, { lookUpDomId } from './classDb';
import { parser } from './parser/classDiagram'; import { parser } from './parser/classDiagram';
import svgDraw from './svgDraw'; import svgDraw from './svgDraw';
@ -154,7 +154,7 @@ export const draw = function(text, id) {
parser.yy.clear(); parser.yy.clear();
parser.parse(text); parser.parse(text);
logger.info('Rendering diagram ' + text); log.info('Rendering diagram ' + text);
// Fetch the default direction, use TD if none was found // Fetch the default direction, use TD if none was found
const diagram = select(`[id='${id}']`); const diagram = select(`[id='${id}']`);
@ -189,12 +189,12 @@ export const draw = function(text, id) {
// our nodes. // our nodes.
g.setNode(node.id, node); g.setNode(node.id, node);
logger.info('Org height: ' + node.height); log.info('Org height: ' + node.height);
} }
const relations = classDb.getRelations(); const relations = classDb.getRelations();
relations.forEach(function(relation) { relations.forEach(function(relation) {
logger.info( log.info(
'tjoho' + getGraphId(relation.id1) + getGraphId(relation.id2) + JSON.stringify(relation) 'tjoho' + getGraphId(relation.id1) + getGraphId(relation.id2) + JSON.stringify(relation)
); );
g.setEdge( g.setEdge(
@ -210,7 +210,7 @@ export const draw = function(text, id) {
dagre.layout(g); dagre.layout(g);
g.nodes().forEach(function(v) { g.nodes().forEach(function(v) {
if (typeof v !== 'undefined' && typeof g.node(v) !== 'undefined') { if (typeof v !== 'undefined' && typeof g.node(v) !== 'undefined') {
logger.debug('Node ' + v + ': ' + JSON.stringify(g.node(v))); log.debug('Node ' + v + ': ' + JSON.stringify(g.node(v)));
select('#' + lookUpDomId(v)).attr( select('#' + lookUpDomId(v)).attr(
'transform', 'transform',
'translate(' + 'translate(' +
@ -224,7 +224,7 @@ export const draw = function(text, id) {
g.edges().forEach(function(e) { g.edges().forEach(function(e) {
if (typeof e !== 'undefined' && typeof g.edge(e) !== 'undefined') { if (typeof e !== 'undefined' && typeof g.edge(e) !== 'undefined') {
logger.debug('Edge ' + e.v + ' -> ' + e.w + ': ' + JSON.stringify(g.edge(e))); log.debug('Edge ' + e.v + ' -> ' + e.w + ': ' + JSON.stringify(g.edge(e)));
svgDraw.drawEdge(diagram, g.edge(e), g.edge(e).relation, conf); svgDraw.drawEdge(diagram, g.edge(e), g.edge(e).relation, conf);
} }
}); });
@ -237,7 +237,7 @@ export const draw = function(text, id) {
// Ensure the viewBox includes the whole svgBounds area with extra space for padding // Ensure the viewBox includes the whole svgBounds area with extra space for padding
const vBox = `${svgBounds.x - padding} ${svgBounds.y - padding} ${width} ${height}`; const vBox = `${svgBounds.x - padding} ${svgBounds.y - padding} ${width} ${height}`;
logger.debug(`viewBox ${vBox}`); log.debug(`viewBox ${vBox}`);
diagram.attr('viewBox', vBox); diagram.attr('viewBox', vBox);
}; };

View File

@ -1,7 +1,7 @@
import { line, curveBasis } from 'd3'; import { line, curveBasis } from 'd3';
import { lookUpDomId, relationType } from './classDb'; import { lookUpDomId, relationType } from './classDb';
import utils from '../../utils'; import utils from '../../utils';
import { logger } from '../../logger'; import { log } from '../../logger';
let edgeCount = 0; let edgeCount = 0;
export const drawEdge = function(elem, path, relation, conf) { export const drawEdge = function(elem, path, relation, conf) {
@ -88,8 +88,8 @@ export const drawEdge = function(elem, path, relation, conf) {
path.points[l - 1] path.points[l - 1]
); );
logger.debug('cardinality_1_point ' + JSON.stringify(cardinality_1_point)); log.debug('cardinality_1_point ' + JSON.stringify(cardinality_1_point));
logger.debug('cardinality_2_point ' + JSON.stringify(cardinality_2_point)); log.debug('cardinality_2_point ' + JSON.stringify(cardinality_2_point));
p1_card_x = cardinality_1_point.x; p1_card_x = cardinality_1_point.x;
p1_card_y = cardinality_1_point.y; p1_card_y = cardinality_1_point.y;
@ -119,7 +119,7 @@ export const drawEdge = function(elem, path, relation, conf) {
.attr('height', bounds.height + conf.padding); .attr('height', bounds.height + conf.padding);
} }
logger.info('Rendering relation ' + JSON.stringify(relation)); log.info('Rendering relation ' + JSON.stringify(relation));
if (typeof relation.relationTitle1 !== 'undefined' && relation.relationTitle1 !== 'none') { if (typeof relation.relationTitle1 !== 'undefined' && relation.relationTitle1 !== 'none') {
const g = elem.append('g').attr('class', 'cardinality'); const g = elem.append('g').attr('class', 'cardinality');
g.append('text') g.append('text')
@ -145,7 +145,7 @@ export const drawEdge = function(elem, path, relation, conf) {
}; };
export const drawClass = function(elem, classDef, conf) { export const drawClass = function(elem, classDef, conf) {
logger.info('Rendering class ' + classDef); log.info('Rendering class ' + classDef);
const id = classDef.id; const id = classDef.id;
const classInfo = { const classInfo = {

View File

@ -1,7 +1,7 @@
/** /**
* *
*/ */
import { logger } from '../../logger'; import { log } from '../../logger';
import mermaidAPI from '../../mermaidAPI'; import mermaidAPI from '../../mermaidAPI';
import * as configApi from '../../config'; import * as configApi from '../../config';
@ -28,7 +28,7 @@ export const parseDirective = function(statement, context, type) {
const addEntity = function(name) { const addEntity = function(name) {
if (typeof entities[name] === 'undefined') { if (typeof entities[name] === 'undefined') {
entities[name] = { attributes: [] }; entities[name] = { attributes: [] };
logger.info('Added new entity :', name); log.info('Added new entity :', name);
} }
return entities[name]; return entities[name];
@ -43,7 +43,7 @@ const addAttributes = function(entityName, attribs) {
let i; let i;
for (i = attribs.length - 1; i >= 0; i--) { for (i = attribs.length - 1; i >= 0; i--) {
entity.attributes.push(attribs[i]); entity.attributes.push(attribs[i]);
logger.debug('Added attribute ', attribs[i].attributeName); log.debug('Added attribute ', attribs[i].attributeName);
} }
}; };
@ -63,7 +63,7 @@ const addRelationship = function(entA, rolA, entB, rSpec) {
}; };
relationships.push(rel); relationships.push(rel);
logger.debug('Added new relationship :', rel); log.debug('Added new relationship :', rel);
}; };
const getRelationships = () => relationships; const getRelationships = () => relationships;

View File

@ -4,7 +4,7 @@ import erDb from './erDb';
import erParser from './parser/erDiagram'; import erParser from './parser/erDiagram';
import dagre from 'dagre'; import dagre from 'dagre';
import { getConfig } from '../../config'; import { getConfig } from '../../config';
import { logger } from '../../logger'; import { log } from '../../logger';
import erMarkers from './erMarkers'; import erMarkers from './erMarkers';
import { configureSvgSize } from '../../utils'; import { configureSvgSize } from '../../utils';
@ -414,7 +414,7 @@ const drawRelationshipFromLayout = function(svg, rel, g, insert) {
* @param id the unique id of the DOM node that contains the diagram * @param id the unique id of the DOM node that contains the diagram
*/ */
export const draw = function(text, id) { export const draw = function(text, id) {
logger.info('Drawing ER diagram'); log.info('Drawing ER diagram');
erDb.clear(); erDb.clear();
const parser = erParser.parser; const parser = erParser.parser;
parser.yy = erDb; parser.yy = erDb;
@ -423,7 +423,7 @@ export const draw = function(text, id) {
try { try {
parser.parse(text); parser.parse(text);
} catch (err) { } catch (err) {
logger.debug('Parsing failed'); log.debug('Parsing failed');
} }
// Get a reference to the svg node that contains the text // Get a reference to the svg node that contains the text

View File

@ -1,7 +1,7 @@
import erDb from '../erDb'; import erDb from '../erDb';
import erDiagram from './erDiagram'; import erDiagram from './erDiagram';
import { setConfig } from '../../../config'; import { setConfig } from '../../../config';
import logger from '../../../logger'; import log from '../../../logger';
setConfig({ setConfig({
securityLevel: 'strict' securityLevel: 'strict'

View File

@ -3,7 +3,7 @@ import utils from '../../utils';
import * as configApi from '../../config'; import * as configApi from '../../config';
import common from '../common/common'; import common from '../common/common';
import mermaidAPI from '../../mermaidAPI'; import mermaidAPI from '../../mermaidAPI';
import { logger } from '../../logger'; import { log } from '../../logger';
const MERMAID_DOM_ID_PREFIX = 'flowchart-'; const MERMAID_DOM_ID_PREFIX = 'flowchart-';
let vertexCounter = 0; let vertexCounter = 0;
@ -117,7 +117,7 @@ export const addSingleLink = function(_start, _end, type, linktext) {
let end = _end; let end = _end;
// if (start[0].match(/\d/)) start = MERMAID_DOM_ID_PREFIX + start; // if (start[0].match(/\d/)) start = MERMAID_DOM_ID_PREFIX + start;
// if (end[0].match(/\d/)) end = MERMAID_DOM_ID_PREFIX + end; // if (end[0].match(/\d/)) end = MERMAID_DOM_ID_PREFIX + end;
// logger.info('Got edge...', start, end); // log.info('Got edge...', start, end);
const edge = { start: start, end: end, type: undefined, text: '' }; const edge = { start: start, end: end, type: undefined, text: '' };
linktext = type.text; linktext = type.text;
@ -457,7 +457,7 @@ export const addSubGraph = function(_id, list, _title) {
nodeList = uniq(nodeList.concat.apply(nodeList, list)); nodeList = uniq(nodeList.concat.apply(nodeList, list));
if (version === 'gen-1') { if (version === 'gen-1') {
logger.warn('LOOKING UP'); log.warn('LOOKING UP');
for (let i = 0; i < nodeList.length; i++) { for (let i = 0; i < nodeList.length; i++) {
nodeList[i] = lookUpDomId(nodeList[i]); nodeList[i] = lookUpDomId(nodeList[i]);
} }
@ -470,7 +470,7 @@ export const addSubGraph = function(_id, list, _title) {
subCount = subCount + 1; subCount = subCount + 1;
const subGraph = { id: id, nodes: nodeList, title: title.trim(), classes: [] }; const subGraph = { id: id, nodes: nodeList, title: title.trim(), classes: [] };
logger.info('Adding', subGraph.id, subGraph.nodes); log.info('Adding', subGraph.id, subGraph.nodes);
/** /**
* Deletes an id from all subgraphs * Deletes an id from all subgraphs

View File

@ -7,7 +7,7 @@ import { getConfig } from '../../config';
import { render } from '../../dagre-wrapper/index.js'; import { render } from '../../dagre-wrapper/index.js';
import addHtmlLabel from 'dagre-d3/lib/label/add-html-label.js'; import addHtmlLabel from 'dagre-d3/lib/label/add-html-label.js';
import { logger } from '../../logger'; import { log } from '../../logger';
import common from '../common/common'; import common from '../common/common';
import { interpolateToCurve, getStylesFromArray, configureSvgSize } from '../../utils'; import { interpolateToCurve, getStylesFromArray, configureSvgSize } from '../../utils';
@ -151,7 +151,7 @@ export const addVertices = function(vert, g, svgId) {
padding: getConfig().flowchart.padding padding: getConfig().flowchart.padding
}); });
logger.info('setNode', { log.info('setNode', {
labelStyle: styles.labelStyle, labelStyle: styles.labelStyle,
shape: _shape, shape: _shape,
labelText: vertexText, labelText: vertexText,
@ -306,7 +306,7 @@ export const addEdges = function(edges, g) {
* @returns {object} classDef styles * @returns {object} classDef styles
*/ */
export const getClasses = function(text) { export const getClasses = function(text) {
logger.info('Extracting classes'); log.info('Extracting classes');
flowDb.clear(); flowDb.clear();
const parser = flow.parser; const parser = flow.parser;
parser.yy = flowDb; parser.yy = flowDb;
@ -328,7 +328,7 @@ export const getClasses = function(text) {
*/ */
export const draw = function(text, id) { export const draw = function(text, id) {
logger.info('Drawing flowchart'); log.info('Drawing flowchart');
flowDb.clear(); flowDb.clear();
flowDb.setGen('gen-2'); flowDb.setGen('gen-2');
const parser = flow.parser; const parser = flow.parser;
@ -338,7 +338,7 @@ export const draw = function(text, id) {
// try { // try {
parser.parse(text); parser.parse(text);
// } catch (err) { // } catch (err) {
// logger.debug('Parsing failed'); // log.debug('Parsing failed');
// } // }
// Fetch the default direction, use TD if none was found // Fetch the default direction, use TD if none was found
@ -369,10 +369,10 @@ export const draw = function(text, id) {
let subG; let subG;
const subGraphs = flowDb.getSubGraphs(); const subGraphs = flowDb.getSubGraphs();
logger.info('Subgraphs - ', subGraphs); log.info('Subgraphs - ', subGraphs);
for (let i = subGraphs.length - 1; i >= 0; i--) { for (let i = subGraphs.length - 1; i >= 0; i--) {
subG = subGraphs[i]; subG = subGraphs[i];
logger.info('Subgraph - ', subG); log.info('Subgraph - ', subG);
flowDb.addVertex(subG.id, subG.title, 'group', undefined, subG.classes); flowDb.addVertex(subG.id, subG.title, 'group', undefined, subG.classes);
} }
@ -381,7 +381,7 @@ export const draw = function(text, id) {
const edges = flowDb.getEdges(); const edges = flowDb.getEdges();
logger.info(edges); log.info(edges);
let i = 0; let i = 0;
for (i = subGraphs.length - 1; i >= 0; i--) { for (i = subGraphs.length - 1; i >= 0; i--) {
// for (let i = 0; i < subGraphs.length; i++) { // for (let i = 0; i < subGraphs.length; i++) {
@ -390,7 +390,7 @@ export const draw = function(text, id) {
selectAll('cluster').append('text'); selectAll('cluster').append('text');
for (let j = 0; j < subG.nodes.length; j++) { for (let j = 0; j < subG.nodes.length; j++) {
logger.info('Setting up subgraphs', subG.nodes[j], subG.id); log.info('Setting up subgraphs', subG.nodes[j], subG.id);
g.setParent(subG.nodes[j], subG.id); g.setParent(subG.nodes[j], subG.id);
} }
} }
@ -412,7 +412,7 @@ export const draw = function(text, id) {
const svgBounds = svg.node().getBBox(); const svgBounds = svg.node().getBBox();
const width = svgBounds.width + padding * 2; const width = svgBounds.width + padding * 2;
const height = svgBounds.height + padding * 2; const height = svgBounds.height + padding * 2;
logger.debug( log.debug(
`new ViewBox 0 0 ${width} ${height}`, `new ViewBox 0 0 ${width} ${height}`,
`translate(${padding - g._label.marginx}, ${padding - g._label.marginy})` `translate(${padding - g._label.marginx}, ${padding - g._label.marginy})`
); );

View File

@ -7,7 +7,7 @@ import { getConfig } from '../../config';
import dagreD3 from 'dagre-d3'; import dagreD3 from 'dagre-d3';
import addHtmlLabel from 'dagre-d3/lib/label/add-html-label.js'; import addHtmlLabel from 'dagre-d3/lib/label/add-html-label.js';
import { logger } from '../../logger'; import { log } from '../../logger';
import common from '../common/common'; import common from '../common/common';
import { interpolateToCurve, getStylesFromArray, configureSvgSize } from '../../utils'; import { interpolateToCurve, getStylesFromArray, configureSvgSize } from '../../utils';
import flowChartShapes from './flowChartShapes'; import flowChartShapes from './flowChartShapes';
@ -133,7 +133,7 @@ export const addVertices = function(vert, g, svgId) {
_shape = 'rect'; _shape = 'rect';
} }
// Add the node // Add the node
logger.warn('Adding node', vertex.id, vertex.domId); log.warn('Adding node', vertex.id, vertex.domId);
g.setNode(flowDb.lookUpDomId(vertex.id), { g.setNode(flowDb.lookUpDomId(vertex.id), {
labelType: 'svg', labelType: 'svg',
labelStyle: styles.labelStyle, labelStyle: styles.labelStyle,
@ -260,7 +260,7 @@ export const addEdges = function(edges, g) {
* @returns {object} classDef styles * @returns {object} classDef styles
*/ */
export const getClasses = function(text) { export const getClasses = function(text) {
logger.info('Extracting classes'); log.info('Extracting classes');
flowDb.clear(); flowDb.clear();
try { try {
const parser = flow.parser; const parser = flow.parser;
@ -280,7 +280,7 @@ export const getClasses = function(text) {
* @param id * @param id
*/ */
export const draw = function(text, id) { export const draw = function(text, id) {
logger.info('Drawing flowchart'); log.info('Drawing flowchart');
flowDb.clear(); flowDb.clear();
flowDb.setGen('gen-1'); flowDb.setGen('gen-1');
const parser = flow.parser; const parser = flow.parser;
@ -290,7 +290,7 @@ export const draw = function(text, id) {
// try { // try {
parser.parse(text); parser.parse(text);
// } catch (err) { // } catch (err) {
// logger.debug('Parsing failed'); // log.debug('Parsing failed');
// } // }
// Fetch the default direction, use TD if none was found // Fetch the default direction, use TD if none was found
@ -328,7 +328,7 @@ export const draw = function(text, id) {
// Fetch the verices/nodes and edges/links from the parsed graph definition // Fetch the verices/nodes and edges/links from the parsed graph definition
const vert = flowDb.getVertices(); const vert = flowDb.getVertices();
logger.warn('Get vertices', vert); log.warn('Get vertices', vert);
const edges = flowDb.getEdges(); const edges = flowDb.getEdges();
@ -339,7 +339,7 @@ export const draw = function(text, id) {
selectAll('cluster').append('text'); selectAll('cluster').append('text');
for (let j = 0; j < subG.nodes.length; j++) { for (let j = 0; j < subG.nodes.length; j++) {
logger.warn( log.warn(
'Setting subgraph', 'Setting subgraph',
subG.nodes[j], subG.nodes[j],
flowDb.lookUpDomId(subG.nodes[j]), flowDb.lookUpDomId(subG.nodes[j]),
@ -400,7 +400,7 @@ export const draw = function(text, id) {
const svg = select(`[id="${id}"]`); const svg = select(`[id="${id}"]`);
svg.attr('xmlns:xlink', 'http://www.w3.org/1999/xlink'); svg.attr('xmlns:xlink', 'http://www.w3.org/1999/xlink');
logger.warn(g); log.warn(g);
// Run the renderer. This is what draws the final graph. // Run the renderer. This is what draws the final graph.
const element = select('#' + id + ' g'); const element = select('#' + id + ' g');
@ -419,7 +419,7 @@ export const draw = function(text, id) {
// Ensure the viewBox includes the whole svgBounds area with extra space for padding // Ensure the viewBox includes the whole svgBounds area with extra space for padding
const vBox = `${svgBounds.x - padding} ${svgBounds.y - padding} ${width} ${height}`; const vBox = `${svgBounds.x - padding} ${svgBounds.y - padding} ${width} ${height}`;
logger.debug(`viewBox ${vBox}`); log.debug(`viewBox ${vBox}`);
svg.attr('viewBox', vBox); svg.attr('viewBox', vBox);
// Index nodes // Index nodes

View File

@ -1,6 +1,6 @@
import moment from 'moment-mini'; import moment from 'moment-mini';
import { sanitizeUrl } from '@braintree/sanitize-url'; import { sanitizeUrl } from '@braintree/sanitize-url';
import { logger } from '../../logger'; import { log } from '../../logger';
import * as configApi from '../../config'; import * as configApi from '../../config';
import utils from '../../utils'; import utils from '../../utils';
import mermaidAPI from '../../mermaidAPI'; import mermaidAPI from '../../mermaidAPI';
@ -186,8 +186,8 @@ const getStartDate = function(prevTime, dateFormat, str) {
if (mDate.isValid()) { if (mDate.isValid()) {
return mDate.toDate(); return mDate.toDate();
} else { } else {
logger.debug('Invalid date:' + str); log.debug('Invalid date:' + str);
logger.debug('With date format:' + dateFormat.trim()); log.debug('With date format:' + dateFormat.trim());
} }
// Default date - now // Default date - now

View File

@ -1,4 +1,4 @@
import { logger } from '../../logger'; import { log } from '../../logger';
import { random } from '../../utils'; import { random } from '../../utils';
let commits = {}; let commits = {};
let head = null; let head = null;
@ -12,12 +12,12 @@ function getId() {
} }
function isfastforwardable(currentCommit, otherCommit) { function isfastforwardable(currentCommit, otherCommit) {
logger.debug('Entering isfastforwardable:', currentCommit.id, otherCommit.id); log.debug('Entering isfastforwardable:', currentCommit.id, otherCommit.id);
while (currentCommit.seq <= otherCommit.seq && currentCommit !== otherCommit) { while (currentCommit.seq <= otherCommit.seq && currentCommit !== otherCommit) {
// only if other branch has more commits // only if other branch has more commits
if (otherCommit.parent == null) break; if (otherCommit.parent == null) break;
if (Array.isArray(otherCommit.parent)) { if (Array.isArray(otherCommit.parent)) {
logger.debug('In merge commit:', otherCommit.parent); log.debug('In merge commit:', otherCommit.parent);
return ( return (
isfastforwardable(currentCommit, commits[otherCommit.parent[0]]) || isfastforwardable(currentCommit, commits[otherCommit.parent[0]]) ||
isfastforwardable(currentCommit, commits[otherCommit.parent[1]]) isfastforwardable(currentCommit, commits[otherCommit.parent[1]])
@ -26,7 +26,7 @@ function isfastforwardable(currentCommit, otherCommit) {
otherCommit = commits[otherCommit.parent]; otherCommit = commits[otherCommit.parent];
} }
} }
logger.debug(currentCommit.id, otherCommit.id); log.debug(currentCommit.id, otherCommit.id);
return currentCommit.id === otherCommit.id; return currentCommit.id === otherCommit.id;
} }
@ -54,13 +54,13 @@ export const setDirection = function(dir) {
}; };
let options = {}; let options = {};
export const setOptions = function(rawOptString) { export const setOptions = function(rawOptString) {
logger.debug('options str', rawOptString); log.debug('options str', rawOptString);
rawOptString = rawOptString && rawOptString.trim(); rawOptString = rawOptString && rawOptString.trim();
rawOptString = rawOptString || '{}'; rawOptString = rawOptString || '{}';
try { try {
options = JSON.parse(rawOptString); options = JSON.parse(rawOptString);
} catch (e) { } catch (e) {
logger.error('error while parsing gitGraph options', e.message); log.error('error while parsing gitGraph options', e.message);
} }
}; };
@ -78,19 +78,19 @@ export const commit = function(msg) {
head = commit; head = commit;
commits[commit.id] = commit; commits[commit.id] = commit;
branches[curBranch] = commit.id; branches[curBranch] = commit.id;
logger.debug('in pushCommit ' + commit.id); log.debug('in pushCommit ' + commit.id);
}; };
export const branch = function(name) { export const branch = function(name) {
branches[name] = head != null ? head.id : null; branches[name] = head != null ? head.id : null;
logger.debug('in createBranch'); log.debug('in createBranch');
}; };
export const merge = function(otherBranch) { export const merge = function(otherBranch) {
const currentCommit = commits[branches[curBranch]]; const currentCommit = commits[branches[curBranch]];
const otherCommit = commits[branches[otherBranch]]; const otherCommit = commits[branches[otherBranch]];
if (isReachableFrom(currentCommit, otherCommit)) { if (isReachableFrom(currentCommit, otherCommit)) {
logger.debug('Already merged'); log.debug('Already merged');
return; return;
} }
if (isfastforwardable(currentCommit, otherCommit)) { if (isfastforwardable(currentCommit, otherCommit)) {
@ -108,29 +108,29 @@ export const merge = function(otherBranch) {
commits[commit.id] = commit; commits[commit.id] = commit;
branches[curBranch] = commit.id; branches[curBranch] = commit.id;
} }
logger.debug(branches); log.debug(branches);
logger.debug('in mergeBranch'); log.debug('in mergeBranch');
}; };
export const checkout = function(branch) { export const checkout = function(branch) {
logger.debug('in checkout'); log.debug('in checkout');
curBranch = branch; curBranch = branch;
const id = branches[curBranch]; const id = branches[curBranch];
head = commits[id]; head = commits[id];
}; };
export const reset = function(commitRef) { export const reset = function(commitRef) {
logger.debug('in reset', commitRef); log.debug('in reset', commitRef);
const ref = commitRef.split(':')[0]; const ref = commitRef.split(':')[0];
let parentCount = parseInt(commitRef.split(':')[1]); let parentCount = parseInt(commitRef.split(':')[1]);
let commit = ref === 'HEAD' ? head : commits[branches[ref]]; let commit = ref === 'HEAD' ? head : commits[branches[ref]];
logger.debug(commit, parentCount); log.debug(commit, parentCount);
while (parentCount > 0) { while (parentCount > 0) {
commit = commits[commit.parent]; commit = commits[commit.parent];
parentCount--; parentCount--;
if (!commit) { if (!commit) {
const err = 'Critical error - unique parent commit not found during reset'; const err = 'Critical error - unique parent commit not found during reset';
logger.error(err); log.error(err);
throw err; throw err;
} }
} }
@ -164,7 +164,7 @@ function prettyPrintCommitHistory(commitArr) {
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);
} }
logger.debug(label.join(' ')); log.debug(label.join(' '));
if (Array.isArray(commit.parent)) { if (Array.isArray(commit.parent)) {
const newCommit = commits[commit.parent[0]]; const newCommit = commits[commit.parent[0]];
upsert(commitArr, commit, newCommit); upsert(commitArr, commit, newCommit);
@ -180,7 +180,7 @@ function prettyPrintCommitHistory(commitArr) {
} }
export const prettyPrint = function() { export const prettyPrint = function() {
logger.debug(commits); log.debug(commits);
const node = getCommitsArray()[0]; const node = getCommitsArray()[0];
prettyPrintCommitHistory([node]); prettyPrintCommitHistory([node]);
}; };
@ -212,7 +212,7 @@ export const getCommitsArray = function() {
return commits[key]; return commits[key];
}); });
commitArr.forEach(function(o) { commitArr.forEach(function(o) {
logger.debug(o.id); log.debug(o.id);
}); });
commitArr.sort((a, b) => b.seq - a.seq); commitArr.sort((a, b) => b.seq - a.seq);
return commitArr; return commitArr;

View File

@ -2,7 +2,7 @@ import { curveBasis, line, select } from 'd3';
import db from './gitGraphAst'; import db from './gitGraphAst';
import gitGraphParser from './parser/gitGraph'; import gitGraphParser from './parser/gitGraph';
import { logger } from '../../logger'; import { log } from '../../logger';
import { interpolateToCurve } from '../../utils'; import { interpolateToCurve } from '../../utils';
let allCommitsDict = {}; let allCommitsDict = {};
@ -87,7 +87,7 @@ function getElementCoords(element, coords) {
} }
function svgDrawLineForCommits(svg, fromId, toId, direction, color) { function svgDrawLineForCommits(svg, fromId, toId, direction, color) {
logger.debug('svgDrawLineForCommits: ', fromId, toId); log.debug('svgDrawLineForCommits: ', fromId, toId);
const fromBbox = getElementCoords(svg.select('#node-' + fromId + ' circle')); const fromBbox = getElementCoords(svg.select('#node-' + fromId + ' circle'));
const toBbox = getElementCoords(svg.select('#node-' + toId + ' circle')); const toBbox = getElementCoords(svg.select('#node-' + toId + ' circle'));
switch (direction) { switch (direction) {
@ -203,7 +203,7 @@ function renderCommitHistory(svg, commitid, branches, direction) {
if (typeof commitid === 'string') { if (typeof commitid === 'string') {
do { do {
commit = allCommitsDict[commitid]; commit = allCommitsDict[commitid];
logger.debug('in renderCommitHistory', commit.id, commit.seq); log.debug('in renderCommitHistory', commit.id, commit.seq);
if (svg.select('#node-' + commitid).size() > 0) { if (svg.select('#node-' + commitid).size() > 0) {
return; return;
} }
@ -247,7 +247,7 @@ function renderCommitHistory(svg, commitid, branches, direction) {
} }
} }
if (branch) { if (branch) {
logger.debug('found branch ', branch.name); log.debug('found branch ', branch.name);
svg svg
.select('#node-' + commit.id + ' p') .select('#node-' + commit.id + ' p')
.append('xhtml:span') .append('xhtml:span')
@ -271,7 +271,7 @@ function renderCommitHistory(svg, commitid, branches, direction) {
} }
if (Array.isArray(commitid)) { if (Array.isArray(commitid)) {
logger.debug('found merge commmit', commitid); log.debug('found merge commmit', commitid);
renderCommitHistory(svg, commitid[0], branches, direction); renderCommitHistory(svg, commitid[0], branches, direction);
branchNum++; branchNum++;
renderCommitHistory(svg, commitid[1], branches, direction); renderCommitHistory(svg, commitid[1], branches, direction);
@ -302,12 +302,12 @@ export const draw = function(txt, id, ver) {
parser.yy = db; parser.yy = db;
parser.yy.clear(); parser.yy.clear();
logger.debug('in gitgraph renderer', txt + '\n', 'id:', id, ver); log.debug('in gitgraph renderer', txt + '\n', 'id:', id, ver);
// Parse the graph definition // Parse the graph definition
parser.parse(txt + '\n'); parser.parse(txt + '\n');
config = Object.assign(config, apiConfig, db.getOptions()); config = Object.assign(config, apiConfig, db.getOptions());
logger.debug('effective options', config); log.debug('effective options', config);
const direction = db.getDirection(); const direction = db.getDirection();
allCommitsDict = db.getCommits(); allCommitsDict = db.getCommits();
const branches = db.getBranchesAsObjArray(); const branches = db.getBranchesAsObjArray();
@ -330,8 +330,8 @@ export const draw = function(txt, id, ver) {
return (branches.length + 1) * config.branchOffset; return (branches.length + 1) * config.branchOffset;
}); });
} catch (e) { } catch (e) {
logger.error('Error while rendering gitgraph'); log.error('Error while rendering gitgraph');
logger.error(e.message); log.error(e.message);
} }
}; };

View File

@ -1,13 +1,13 @@
/** /**
* Created by knut on 15-01-14. * Created by knut on 15-01-14.
*/ */
import { logger } from '../../logger'; import { log } from '../../logger';
var message = ''; var message = '';
var info = false; var info = false;
export const setMessage = txt => { export const setMessage = txt => {
logger.debug('Setting message to: ' + txt); log.debug('Setting message to: ' + txt);
message = txt; message = txt;
}; };

View File

@ -4,7 +4,7 @@
import { select } from 'd3'; import { select } from 'd3';
import db from './infoDb'; import db from './infoDb';
import infoParser from './parser/info'; import infoParser from './parser/info';
import { logger } from '../../logger'; import { log } from '../../logger';
const conf = {}; const conf = {};
export const setConf = function(cnf) { export const setConf = function(cnf) {
@ -24,10 +24,10 @@ export const draw = (txt, id, ver) => {
try { try {
const parser = infoParser.parser; const parser = infoParser.parser;
parser.yy = db; parser.yy = db;
logger.debug('Renering info diagram\n' + txt); log.debug('Renering info diagram\n' + txt);
// Parse the graph definition // Parse the graph definition
parser.parse(txt); parser.parse(txt);
logger.debug('Parsed info diagram'); log.debug('Parsed info diagram');
// Fetch the default direction, use TD if none was found // Fetch the default direction, use TD if none was found
const svg = select('#' + id); const svg = select('#' + id);
@ -45,8 +45,8 @@ export const draw = (txt, id, ver) => {
svg.attr('width', 400); svg.attr('width', 400);
// svg.attr('viewBox', '0 0 300 150'); // svg.attr('viewBox', '0 0 300 150');
} catch (e) { } catch (e) {
logger.error('Error while rendering info diagram'); log.error('Error while rendering info diagram');
logger.error(e.message); log.error(e.message);
} }
}; };

View File

@ -1,7 +1,7 @@
/** /**
* *
*/ */
import { logger } from '../../logger'; import { log } from '../../logger';
import mermaidAPI from '../../mermaidAPI'; import mermaidAPI from '../../mermaidAPI';
import * as configApi from '../../config'; import * as configApi from '../../config';
@ -15,7 +15,7 @@ export const parseDirective = function(statement, context, type) {
const addSection = function(id, value) { const addSection = function(id, value) {
if (typeof sections[id] === 'undefined') { if (typeof sections[id] === 'undefined') {
sections[id] = value; sections[id] = value;
logger.debug('Added new section :', id); log.debug('Added new section :', id);
} }
}; };
const getSections = () => sections; const getSections = () => sections;

View File

@ -4,7 +4,7 @@
import { select, scaleOrdinal, schemeSet2, pie as d3pie, entries, arc } from 'd3'; import { select, scaleOrdinal, schemeSet2, pie as d3pie, entries, arc } from 'd3';
import pieData from './pieDb'; import pieData from './pieDb';
import pieParser from './parser/pie'; import pieParser from './parser/pie';
import { logger } from '../../logger'; import { log } from '../../logger';
import { configureSvgSize } from '../../utils'; import { configureSvgSize } from '../../utils';
const conf = {}; const conf = {};
@ -27,11 +27,11 @@ export const draw = (txt, id) => {
try { try {
const parser = pieParser.parser; const parser = pieParser.parser;
parser.yy = pieData; parser.yy = pieData;
logger.debug('Rendering info diagram\n' + txt); log.debug('Rendering info diagram\n' + txt);
// Parse the Pie Chart definition // Parse the Pie Chart definition
parser.yy.clear(); parser.yy.clear();
parser.parse(txt); parser.parse(txt);
logger.debug('Parsed info diagram'); log.debug('Parsed info diagram');
const elem = document.getElementById(id); const elem = document.getElementById(id);
width = elem.parentElement.offsetWidth; width = elem.parentElement.offsetWidth;
@ -150,8 +150,8 @@ export const draw = (txt, id) => {
return d; return d;
}); });
} catch (e) { } catch (e) {
logger.error('Error while rendering info diagram'); log.error('Error while rendering info diagram');
logger.error(e); log.error(e);
} }
}; };

View File

@ -1,6 +1,6 @@
import mermaidAPI from '../../mermaidAPI'; import mermaidAPI from '../../mermaidAPI';
import * as configApi from '../../config'; import * as configApi from '../../config';
import { logger } from '../../logger'; import { log } from '../../logger';
let prevActor = undefined; let prevActor = undefined;
let actors = {}; let actors = {};
@ -143,7 +143,7 @@ export const parseMessage = function(str) {
? false ? false
: undefined : undefined
}; };
logger.debug('parseMessage:', message); log.debug('parseMessage:', message);
return message; return message;
}; };

View File

@ -1,6 +1,6 @@
import { select, selectAll } from 'd3'; import { select, selectAll } from 'd3';
import svgDraw, { drawText } from './svgDraw'; import svgDraw, { drawText } from './svgDraw';
import { logger } from '../../logger'; import { log } from '../../logger';
import { parser } from './parser/sequenceDiagram'; import { parser } from './parser/sequenceDiagram';
import common from '../common/common'; import common from '../common/common';
import sequenceDb from './sequenceDb'; import sequenceDb from './sequenceDb';
@ -491,7 +491,7 @@ function adjustLoopHeightForWrap(loopWidths, msg, preMargin, postMargin, addLoop
const textDims = utils.calculateTextDimensions(msg.message, textConf); const textDims = utils.calculateTextDimensions(msg.message, textConf);
const totalOffset = Math.max(textDims.height, conf.labelBoxHeight); const totalOffset = Math.max(textDims.height, conf.labelBoxHeight);
heightAdjust = postMargin + totalOffset; heightAdjust = postMargin + totalOffset;
logger.debug(`${totalOffset} - ${msg.message}`); log.debug(`${totalOffset} - ${msg.message}`);
} }
addLoopFn(msg); addLoopFn(msg);
bounds.bumpVerticalPos(heightAdjust); bounds.bumpVerticalPos(heightAdjust);
@ -508,7 +508,7 @@ export const draw = function(text, id) {
parser.yy.setWrap(conf.wrap); parser.yy.setWrap(conf.wrap);
parser.parse(text + '\n'); parser.parse(text + '\n');
bounds.init(); bounds.init();
logger.debug(`C:${JSON.stringify(conf, null, 2)}`); log.debug(`C:${JSON.stringify(conf, null, 2)}`);
const diagram = select(`[id="${id}"]`); const diagram = select(`[id="${id}"]`);
@ -661,7 +661,7 @@ export const draw = function(text, id) {
drawMessage(diagram, msgModel); drawMessage(diagram, msgModel);
bounds.models.addMessage(msgModel); bounds.models.addMessage(msgModel);
} catch (e) { } catch (e) {
logger.error('error while drawing message', e); log.error('error while drawing message', e);
} }
} }
// Increment sequence counter if msg.type is a line (and not another event like activation or note, etc) // Increment sequence counter if msg.type is a line (and not another event like activation or note, etc)
@ -690,7 +690,7 @@ export const draw = function(text, id) {
const { bounds: box } = bounds.getBounds(); const { bounds: box } = bounds.getBounds();
// Adjust line height of actor lines now that the height of the diagram is known // Adjust line height of actor lines now that the height of the diagram is known
logger.debug('For line height fix Querying: #' + id + ' .actor-line'); log.debug('For line height fix Querying: #' + id + ' .actor-line');
const actorLines = selectAll('#' + id + ' .actor-line'); const actorLines = selectAll('#' + id + ' .actor-line');
actorLines.attr('y2', box.stopy); actorLines.attr('y2', box.stopy);
@ -723,7 +723,7 @@ export const draw = function(text, id) {
' ' + ' ' +
(height + extraVertForTitle) (height + extraVertForTitle)
); );
logger.debug(`models:`, bounds.models); log.debug(`models:`, bounds.models);
}; };
/** /**
@ -827,7 +827,7 @@ const getMaxMessageWidthPerActor = function(actors, messages) {
} }
}); });
logger.debug('maxMessageWidthPerActor:', maxMessageWidthPerActor); log.debug('maxMessageWidthPerActor:', maxMessageWidthPerActor);
return maxMessageWidthPerActor; return maxMessageWidthPerActor;
}; };
@ -947,7 +947,7 @@ const buildNoteModel = function(msg, actors) {
noteFont(conf) noteFont(conf)
); );
} }
logger.debug( log.debug(
`NM:[${noteModel.startx},${noteModel.stopx},${noteModel.starty},${noteModel.stopy}:${noteModel.width},${noteModel.height}=${msg.message}]` `NM:[${noteModel.startx},${noteModel.stopx},${noteModel.starty},${noteModel.stopy}:${noteModel.width},${noteModel.height}=${msg.message}]`
); );
return noteModel; return noteModel;
@ -1104,7 +1104,7 @@ const calculateLoopBounds = function(messages, actors) {
} }
}); });
bounds.activations = []; bounds.activations = [];
logger.debug('Loop type widths:', loops); log.debug('Loop type widths:', loops);
return loops; return loops;
}; };

View File

@ -4,7 +4,7 @@ import stateDb from './stateDb';
import utils from '../../utils'; import utils from '../../utils';
import common from '../common/common'; import common from '../common/common';
import { getConfig } from '../../config'; import { getConfig } from '../../config';
import { logger } from '../../logger'; import { log } from '../../logger';
// let conf; // let conf;
@ -471,12 +471,12 @@ export const drawEdge = function(elem, path, relation) {
maxWidth = Math.max(maxWidth, boundstmp.width); maxWidth = Math.max(maxWidth, boundstmp.width);
minX = Math.min(minX, boundstmp.x); minX = Math.min(minX, boundstmp.x);
logger.info(boundstmp.x, x, y + titleHeight); log.info(boundstmp.x, x, y + titleHeight);
if (titleHeight === 0) { if (titleHeight === 0) {
const titleBox = title.node().getBBox(); const titleBox = title.node().getBBox();
titleHeight = titleBox.height; titleHeight = titleBox.height;
logger.info('Title height', titleHeight, y); log.info('Title height', titleHeight, y);
} }
titleRows.push(title); titleRows.push(title);
} }
@ -499,7 +499,7 @@ export const drawEdge = function(elem, path, relation) {
.attr('width', maxWidth + getConfig().state.padding) .attr('width', maxWidth + getConfig().state.padding)
.attr('height', boxHeight + getConfig().state.padding); .attr('height', boxHeight + getConfig().state.padding);
logger.info(bounds); log.info(bounds);
//label.attr('transform', '0 -' + (bounds.y / 2)); //label.attr('transform', '0 -' + (bounds.y / 2));

View File

@ -1,4 +1,4 @@
import { logger } from '../../logger'; import { log } from '../../logger';
import { generateId } from '../../utils'; import { generateId } from '../../utils';
import mermaidAPI from '../../mermaidAPI'; import mermaidAPI from '../../mermaidAPI';
import * as configApi from '../../config'; import * as configApi from '../../config';
@ -12,7 +12,7 @@ export const parseDirective = function(statement, context, type) {
}; };
const setRootDoc = o => { const setRootDoc = o => {
logger.info('Setting root doc', o); log.info('Setting root doc', o);
// rootDoc = { id: 'root', doc: o }; // rootDoc = { id: 'root', doc: o };
rootDoc = o; rootDoc = o;
}; };
@ -81,10 +81,10 @@ const extract = _doc => {
// if (!doc) { // if (!doc) {
// doc = root; // doc = root;
// } // }
logger.info(doc); log.info(doc);
clear(); clear();
logger.info('Extract', doc); log.info('Extract', doc);
doc.forEach(item => { doc.forEach(item => {
if (item.stmt === 'state') { if (item.stmt === 'state') {
@ -139,7 +139,7 @@ export const addState = function(id, type, doc, descr, note) {
} }
} }
if (descr) { if (descr) {
logger.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') {
@ -171,7 +171,7 @@ export const getStates = function() {
return currentDocument.states; return currentDocument.states;
}; };
export const logDocuments = function() { export const logDocuments = function() {
logger.info('Documents = ', documents); log.info('Documents = ', documents);
}; };
export const getRelations = function() { export const getRelations = function() {
return currentDocument.relations; return currentDocument.relations;

View File

@ -5,7 +5,7 @@ import state from './parser/stateDiagram';
import { getConfig } from '../../config'; import { getConfig } from '../../config';
import { render } from '../../dagre-wrapper/index.js'; import { render } from '../../dagre-wrapper/index.js';
import { logger } from '../../logger'; import { log } from '../../logger';
import { configureSvgSize } from '../../utils'; import { configureSvgSize } from '../../utils';
const conf = {}; const conf = {};
@ -23,7 +23,7 @@ let nodeDb = {};
* @returns {object} classDef styles * @returns {object} classDef styles
*/ */
export const getClasses = function(text) { export const getClasses = function(text) {
logger.trace('Extracting classes'); log.trace('Extracting classes');
stateDb.clear(); stateDb.clear();
const parser = state.parser; const parser = state.parser;
parser.yy = stateDb; parser.yy = stateDb;
@ -84,7 +84,7 @@ const setupNode = (g, parent, node, altFlag) => {
// group // group
if (!nodeDb[node.id].type && node.doc) { if (!nodeDb[node.id].type && node.doc) {
logger.info('Setting cluser for ', node.id); log.info('Setting cluser for ', node.id);
nodeDb[node.id].type = 'group'; nodeDb[node.id].type = 'group';
nodeDb[node.id].shape = node.type === 'divider' ? 'divider' : 'roundedWithTitle'; nodeDb[node.id].shape = node.type === 'divider' ? 'divider' : 'roundedWithTitle';
nodeDb[node.id].classes = nodeDb[node.id].classes =
@ -164,19 +164,19 @@ const setupNode = (g, parent, node, altFlag) => {
if (parent) { if (parent) {
if (parent.id !== 'root') { if (parent.id !== 'root') {
logger.info('Setting node ', node.id, ' to be child of its parent ', parent.id); log.info('Setting node ', node.id, ' to be child of its parent ', parent.id);
g.setParent(node.id, parent.id); g.setParent(node.id, parent.id);
} }
} }
if (node.doc) { if (node.doc) {
logger.info('Adding nodes children '); log.info('Adding nodes children ');
setupDoc(g, node, node.doc, !altFlag); setupDoc(g, node, node.doc, !altFlag);
} }
}; };
let cnt = 0; let cnt = 0;
const setupDoc = (g, parent, doc, altFlag) => { const setupDoc = (g, parent, doc, altFlag) => {
cnt = 0; cnt = 0;
logger.trace('items', doc); log.trace('items', doc);
doc.forEach(item => { doc.forEach(item => {
if (item.stmt === 'state' || item.stmt === 'default') { if (item.stmt === 'state' || item.stmt === 'default') {
setupNode(g, parent, item, altFlag); setupNode(g, parent, item, altFlag);
@ -211,7 +211,7 @@ const setupDoc = (g, parent, doc, altFlag) => {
* @param id * @param id
*/ */
export const draw = function(text, id) { export const draw = function(text, id) {
logger.info('Drawing state diagram (v2)', id); log.info('Drawing state diagram (v2)', id);
stateDb.clear(); stateDb.clear();
nodeDb = {}; nodeDb = {};
const parser = state.parser; const parser = state.parser;
@ -246,9 +246,9 @@ export const draw = function(text, id) {
return {}; return {};
}); });
logger.info(stateDb.getRootDocV2()); log.info(stateDb.getRootDocV2());
stateDb.extract(stateDb.getRootDocV2()); stateDb.extract(stateDb.getRootDocV2());
logger.info(stateDb.getRootDocV2()); log.info(stateDb.getRootDocV2());
setupNode(g, undefined, stateDb.getRootDocV2(), true); setupNode(g, undefined, stateDb.getRootDocV2(), true);
// Set up an SVG group so that we can translate the final graph. // Set up an SVG group so that we can translate the final graph.
@ -274,7 +274,7 @@ export const draw = function(text, id) {
// Ensure the viewBox includes the whole svgBounds area with extra space for padding // Ensure the viewBox includes the whole svgBounds area with extra space for padding
const vBox = `${svgBounds.x - padding} ${svgBounds.y - padding} ${width} ${height}`; const vBox = `${svgBounds.x - padding} ${svgBounds.y - padding} ${width} ${height}`;
logger.debug(`viewBox ${vBox}`); log.debug(`viewBox ${vBox}`);
svg.attr('viewBox', vBox); svg.attr('viewBox', vBox);
// Add label rects for non html labels // Add label rects for non html labels

View File

@ -1,7 +1,7 @@
import { select } from 'd3'; import { select } from 'd3';
import dagre from 'dagre'; import dagre from 'dagre';
import graphlib from 'graphlib'; import graphlib from 'graphlib';
import { logger } from '../../logger'; import { log } from '../../logger';
import stateDb from './stateDb'; import stateDb from './stateDb';
import common from '../common/common'; import common from '../common/common';
import { parser } from './parser/stateDiagram'; import { parser } from './parser/stateDiagram';
@ -47,7 +47,7 @@ export const draw = function(text, id) {
conf = getConfig().state; conf = getConfig().state;
parser.yy.clear(); parser.yy.clear();
parser.parse(text); parser.parse(text);
logger.debug('Rendering diagram ' + text); log.debug('Rendering diagram ' + text);
// Fetch the default direction, use TD if none was found // Fetch the default direction, use TD if none was found
const diagram = select(`[id='${id}']`); const diagram = select(`[id='${id}']`);
@ -210,11 +210,11 @@ const renderDoc = (doc, diagram, parentId, altBkg) => {
} }
} }
logger.debug('Count=', graph.nodeCount(), graph); log.debug('Count=', graph.nodeCount(), graph);
let cnt = 0; let cnt = 0;
relations.forEach(function(relation) { relations.forEach(function(relation) {
cnt++; cnt++;
logger.debug('Setting edge', relation); log.debug('Setting edge', relation);
graph.setEdge( graph.setEdge(
relation.id1, relation.id1,
relation.id2, relation.id2,
@ -230,12 +230,12 @@ const renderDoc = (doc, diagram, parentId, altBkg) => {
dagre.layout(graph); dagre.layout(graph);
logger.debug('Graph after layout', graph.nodes()); log.debug('Graph after layout', graph.nodes());
const svgElem = diagram.node(); const svgElem = diagram.node();
graph.nodes().forEach(function(v) { graph.nodes().forEach(function(v) {
if (typeof v !== 'undefined' && typeof graph.node(v) !== 'undefined') { if (typeof v !== 'undefined' && typeof graph.node(v) !== 'undefined') {
logger.warn('Node ' + v + ': ' + JSON.stringify(graph.node(v))); log.warn('Node ' + v + ': ' + JSON.stringify(graph.node(v)));
select('#' + svgElem.id + ' #' + v).attr( select('#' + svgElem.id + ' #' + v).attr(
'transform', 'transform',
'translate(' + 'translate(' +
@ -266,7 +266,7 @@ const renderDoc = (doc, diagram, parentId, altBkg) => {
divider.setAttribute('x2', pWidth - pShift - 8); divider.setAttribute('x2', pWidth - pShift - 8);
}); });
} else { } else {
logger.debug('No Node ' + v + ': ' + JSON.stringify(graph.node(v))); log.debug('No Node ' + v + ': ' + JSON.stringify(graph.node(v)));
} }
}); });
@ -274,7 +274,7 @@ const renderDoc = (doc, diagram, parentId, altBkg) => {
graph.edges().forEach(function(e) { graph.edges().forEach(function(e) {
if (typeof e !== 'undefined' && typeof graph.edge(e) !== 'undefined') { if (typeof e !== 'undefined' && typeof graph.edge(e) !== 'undefined') {
logger.debug('Edge ' + e.v + ' -> ' + e.w + ': ' + JSON.stringify(graph.edge(e))); log.debug('Edge ' + e.v + ' -> ' + e.w + ': ' + JSON.stringify(graph.edge(e)));
drawEdge(diagram, graph.edge(e), graph.edge(e).relation); drawEdge(diagram, graph.edge(e), graph.edge(e).relation);
} }
}); });
@ -291,7 +291,7 @@ const renderDoc = (doc, diagram, parentId, altBkg) => {
stateInfo.width = stateBox.width + 2 * conf.padding; stateInfo.width = stateBox.width + 2 * conf.padding;
stateInfo.height = stateBox.height + 2 * conf.padding; stateInfo.height = stateBox.height + 2 * conf.padding;
logger.debug('Doc rendered', stateInfo, graph); log.debug('Doc rendered', stateInfo, graph);
return stateInfo; return stateInfo;
}; };

View File

@ -2,7 +2,7 @@
* Created by knut on 14-12-11. * Created by knut on 14-12-11.
*/ */
import { select } from 'd3'; import { select } from 'd3';
import { logger } from './logger'; import { log } from './logger';
const conf = {}; const conf = {};
export const setConf = function(cnf) { export const setConf = function(cnf) {
@ -20,7 +20,7 @@ export const setConf = function(cnf) {
*/ */
export const draw = (id, ver) => { export const draw = (id, ver) => {
try { try {
logger.debug('Renering svg for syntax error\n'); log.debug('Renering svg for syntax error\n');
const svg = select('#' + id); const svg = select('#' + id);
@ -87,8 +87,8 @@ export const draw = (id, ver) => {
svg.attr('width', 400); svg.attr('width', 400);
svg.attr('viewBox', '768 0 512 512'); svg.attr('viewBox', '768 0 512 512');
} catch (e) { } catch (e) {
logger.error('Error while rendering info diagram'); log.error('Error while rendering info diagram');
logger.error(e.message); log.error(e.message);
} }
}; };

View File

@ -1,5 +1,5 @@
import moment from 'moment-mini'; import moment from 'moment-mini';
//
export const LEVELS = { export const LEVELS = {
debug: 1, debug: 1,
info: 2, info: 2,
@ -8,7 +8,7 @@ export const LEVELS = {
fatal: 5 fatal: 5
}; };
export const logger = { export const log = {
debug: () => {}, debug: () => {},
info: () => {}, info: () => {},
warn: () => {}, warn: () => {},
@ -23,35 +23,34 @@ export const setLogLevel = function(level = 'fatal') {
level = LEVELS[level]; level = LEVELS[level];
} }
} }
logger.trace = () => {}; log.trace = () => {};
logger.debug = () => {}; log.debug = () => {};
logger.info = () => {}; log.info = () => {};
logger.warn = () => {}; log.warn = () => {};
logger.error = () => {}; log.error = () => {};
logger.fatal = () => {}; log.fatal = () => {};
if (level <= LEVELS.fatal) { if (level <= LEVELS.fatal) {
logger.fatal = console.error log.fatal = console.error
? console.error.bind(console, format('FATAL'), 'color: orange') ? console.error.bind(console, format('FATAL'), 'color: orange')
: console.log.bind(console, '\x1b[35m', format('FATAL')); : console.log.bind(console, '\x1b[35m', format('FATAL'));
} }
if (level <= LEVELS.error) { if (level <= LEVELS.error) {
logger.error = console.error log.error = console.error
? console.error.bind(console, format('ERROR'), 'color: orange') ? console.error.bind(console, format('ERROR'), 'color: orange')
: console.log.bind(console, '\x1b[31m', format('ERROR')); : console.log.bind(console, '\x1b[31m', format('ERROR'));
} }
if (level <= LEVELS.warn) { if (level <= LEVELS.warn) {
logger.warn = console.warn log.warn = console.warn
? console.warn.bind(console, format('WARN'), 'color: orange') ? console.warn.bind(console, format('WARN'), 'color: orange')
: console.log.bind(console, `\x1b[33m`, format('WARN')); : console.log.bind(console, `\x1b[33m`, format('WARN'));
} }
if (level <= LEVELS.info) { if (level <= LEVELS.info) {
logger.info = console.info log.info = console.info // ? console.info.bind(console, '\x1b[34m', format('INFO'), 'color: blue')
? // ? console.info.bind(console, '\x1b[34m', format('INFO'), 'color: blue') ? console.info.bind(console, format('INFO'), 'color: lightblue')
console.info.bind(console, format('INFO'), 'color: lightblue')
: console.log.bind(console, '\x1b[34m', format('INFO')); : console.log.bind(console, '\x1b[34m', format('INFO'));
} }
if (level <= LEVELS.debug) { if (level <= LEVELS.debug) {
logger.debug = console.debug log.debug = console.debug
? console.debug.bind(console, format('DEBUG'), 'color: lightgreen') ? console.debug.bind(console, format('DEBUG'), 'color: lightgreen')
: console.log.bind(console, '\x1b[32m', format('DEBUG')); : console.log.bind(console, '\x1b[32m', format('DEBUG'));
} }

View File

@ -4,7 +4,7 @@
*/ */
// import { decode } from 'he'; // import { decode } from 'he';
import decode from 'entity-decode/browser'; import decode from 'entity-decode/browser';
import { logger } from './logger'; import { log } from './logger';
import mermaidAPI from './mermaidAPI'; import mermaidAPI from './mermaidAPI';
import utils from './utils'; import utils from './utils';
@ -48,14 +48,14 @@ const init = function() {
let callback; let callback;
if (typeof arguments[arguments.length - 1] === 'function') { if (typeof arguments[arguments.length - 1] === 'function') {
callback = arguments[arguments.length - 1]; callback = arguments[arguments.length - 1];
logger.debug('Callback function found'); log.debug('Callback function found');
} else { } else {
if (typeof conf.mermaid !== 'undefined') { if (typeof conf.mermaid !== 'undefined') {
if (typeof conf.mermaid.callback === 'function') { if (typeof conf.mermaid.callback === 'function') {
callback = conf.mermaid.callback; callback = conf.mermaid.callback;
logger.debug('Callback function found'); log.debug('Callback function found');
} else { } else {
logger.debug('No Callback function found'); log.debug('No Callback function found');
} }
} }
} }
@ -68,9 +68,9 @@ const init = function() {
? [nodes] ? [nodes]
: nodes; // Last case - sequence config was passed pick next : nodes; // Last case - sequence config was passed pick next
logger.debug('Start On Load before: ' + mermaid.startOnLoad); log.debug('Start On Load before: ' + mermaid.startOnLoad);
if (typeof mermaid.startOnLoad !== 'undefined') { if (typeof mermaid.startOnLoad !== 'undefined') {
logger.debug('Start On Load inner: ' + mermaid.startOnLoad); log.debug('Start On Load inner: ' + mermaid.startOnLoad);
mermaidAPI.updateSiteConfig({ startOnLoad: mermaid.startOnLoad }); mermaidAPI.updateSiteConfig({ startOnLoad: mermaid.startOnLoad });
} }
@ -104,7 +104,7 @@ const init = function() {
const init = utils.detectInit(txt); const init = utils.detectInit(txt);
if (init) { if (init) {
logger.debug('Detected early reinit: ', init); log.debug('Detected early reinit: ', init);
} }
try { try {
@ -121,8 +121,8 @@ const init = function() {
element element
); );
} catch (e) { } catch (e) {
logger.warn('Syntax Error rendering'); log.warn('Syntax Error rendering');
logger.warn(e); log.warn(e);
if (this.parseError) { if (this.parseError) {
this.parseError(e); this.parseError(e);
} }
@ -160,7 +160,7 @@ const contentLoaded = function() {
} }
} else { } else {
if (typeof mermaid.startOnLoad === 'undefined') { if (typeof mermaid.startOnLoad === 'undefined') {
logger.debug('In start, no config'); log.debug('In start, no config');
config = mermaidAPI.getConfig(); config = mermaidAPI.getConfig();
if (config.startOnLoad) { if (config.startOnLoad) {
mermaid.init(); mermaid.init();

View File

@ -25,7 +25,7 @@ import pkg from '../package.json';
// // configApi.getSiteConfig, // // configApi.getSiteConfig,
// // configApi.defaultConfig // // configApi.defaultConfig
// // } // // }
import { logger, setLogLevel } from './logger'; import { log, setLogLevel } from './logger';
import utils, { assignWithDepth } from './utils'; import utils, { assignWithDepth } from './utils';
import flowRenderer from './diagrams/flowchart/flowRenderer'; import flowRenderer from './diagrams/flowchart/flowRenderer';
import flowRendererV2 from './diagrams/flowchart/flowRenderer-v2'; import flowRendererV2 from './diagrams/flowchart/flowRenderer-v2';
@ -69,12 +69,12 @@ function parse(text) {
const graphInit = utils.detectInit(text); const graphInit = utils.detectInit(text);
if (graphInit) { if (graphInit) {
reinitialize(graphInit); reinitialize(graphInit);
logger.debug('reinit ', graphInit); log.debug('reinit ', graphInit);
} }
const graphType = utils.detectType(text); const graphType = utils.detectType(text);
let parser; let parser;
logger.debug('Type ' + graphType); log.debug('Type ' + graphType);
switch (graphType) { switch (graphType) {
case 'git': case 'git':
parser = gitGraphParser; parser = gitGraphParser;
@ -115,22 +115,22 @@ function parse(text) {
parser.parser.yy = stateDb; parser.parser.yy = stateDb;
break; break;
case 'info': case 'info':
logger.debug('info info info'); log.debug('info info info');
parser = infoParser; parser = infoParser;
parser.parser.yy = infoDb; parser.parser.yy = infoDb;
break; break;
case 'pie': case 'pie':
logger.debug('pie'); log.debug('pie');
parser = pieParser; parser = pieParser;
parser.parser.yy = pieDb; parser.parser.yy = pieDb;
break; break;
case 'er': case 'er':
logger.debug('er'); log.debug('er');
parser = erParser; parser = erParser;
parser.parser.yy = erDb; parser.parser.yy = erDb;
break; break;
case 'journey': case 'journey':
logger.debug('Journey'); log.debug('Journey');
parser = journeyParser; parser = journeyParser;
parser.parser.yy = journeyDb; parser.parser.yy = journeyDb;
break; break;
@ -299,7 +299,7 @@ const render = function(id, _txt, cb, container) {
} }
} }
// logger.warn(cnf.themeVariables); // log.warn(cnf.themeVariables);
const stylis = new Stylis(); const stylis = new Stylis();
const rules = stylis(`#${id}`, getStyles(graphType, userStyles, cnf.themeVariables)); const rules = stylis(`#${id}`, getStyles(graphType, userStyles, cnf.themeVariables));
@ -417,7 +417,7 @@ const render = function(id, _txt, cb, container) {
// Fix for when the base tag is used // Fix for when the base tag is used
let svgCode = select('#d' + id).node().innerHTML; let svgCode = select('#d' + id).node().innerHTML;
logger.debug('cnf.arrowMarkerAbsolute', cnf.arrowMarkerAbsolute); log.debug('cnf.arrowMarkerAbsolute', cnf.arrowMarkerAbsolute);
if (!cnf.arrowMarkerAbsolute || cnf.arrowMarkerAbsolute === 'false') { if (!cnf.arrowMarkerAbsolute || cnf.arrowMarkerAbsolute === 'false') {
svgCode = svgCode.replace(/marker-end="url\(.*?#/g, 'marker-end="url(#', 'g'); svgCode = svgCode.replace(/marker-end="url\(.*?#/g, 'marker-end="url(#', 'g');
} }
@ -444,7 +444,7 @@ const render = function(id, _txt, cb, container) {
cb(svgCode); cb(svgCode);
} }
} else { } else {
logger.debug('CB = undefined!'); log.debug('CB = undefined!');
} }
const node = select('#d' + id).node(); const node = select('#d' + id).node();
@ -480,15 +480,15 @@ const parseDirective = function(p, statement, context, type) {
} }
} }
} catch (error) { } catch (error) {
logger.error( log.error(
`Error while rendering sequenceDiagram directive: ${statement} jison context: ${context}` `Error while rendering sequenceDiagram directive: ${statement} jison context: ${context}`
); );
logger.error(error.message); log.error(error.message);
} }
}; };
const handleDirective = function(p, directive, type) { const handleDirective = function(p, directive, type) {
logger.debug(`Directive type=${directive.type} with args:`, directive.args); log.debug(`Directive type=${directive.type} with args:`, directive.args);
switch (directive.type) { switch (directive.type) {
case 'init': case 'init':
case 'initialize': { case 'initialize': {
@ -513,7 +513,7 @@ const handleDirective = function(p, directive, type) {
} }
break; break;
default: default:
logger.warn( log.warn(
`Unhandled directive: source: '%%{${directive.type}: ${JSON.stringify( `Unhandled directive: source: '%%{${directive.type}: ${JSON.stringify(
directive.args ? directive.args : {} directive.args ? directive.args : {}
)}}%%`, )}}%%`,
@ -554,7 +554,7 @@ function reinitialize() {
// typeof options === 'object' ? configApi.setConfig(options) : configApi.getSiteConfig(); // typeof options === 'object' ? configApi.setConfig(options) : configApi.getSiteConfig();
// updateRendererConfigs(config); // updateRendererConfigs(config);
// setLogLevel(config.logLevel); // setLogLevel(config.logLevel);
// logger.debug('mermaidAPI.reinitialize: ', config); // log.debug('mermaidAPI.reinitialize: ', config);
} }
function initialize(options) { function initialize(options) {
@ -585,7 +585,7 @@ function initialize(options) {
updateRendererConfigs(config); updateRendererConfigs(config);
setLogLevel(config.logLevel); setLogLevel(config.logLevel);
// logger.debug('mermaidAPI.initialize: ', config); // log.debug('mermaidAPI.initialize: ', config);
} }
const mermaidAPI = Object.freeze({ const mermaidAPI = Object.freeze({

View File

@ -14,7 +14,7 @@ import {
select select
} from 'd3'; } from 'd3';
import common from './diagrams/common/common'; import common from './diagrams/common/common';
import { logger } from './logger'; import { log } from './logger';
// import cryptoRandomString from 'crypto-random-string'; // import cryptoRandomString from 'crypto-random-string';
// Effectively an enum of the supported curve types, accessible by name // Effectively an enum of the supported curve types, accessible by name
@ -120,7 +120,7 @@ export const detectDirective = function(text, type = null) {
.trim() .trim()
.replace(commentWithoutDirectives, '') .replace(commentWithoutDirectives, '')
.replace(/'/gm, '"'); .replace(/'/gm, '"');
logger.debug( log.debug(
`Detecting diagram directive${type !== null ? ' type:' + type : ''} based on the text:${text}` `Detecting diagram directive${type !== null ? ' type:' + type : ''} based on the text:${text}`
); );
let match, let match,
@ -146,7 +146,7 @@ export const detectDirective = function(text, type = null) {
return result.length === 1 ? result[0] : result; return result.length === 1 ? result[0] : result;
} catch (error) { } catch (error) {
logger.error( log.error(
`ERROR: ${error.message} - Unable to parse directive${ `ERROR: ${error.message} - Unable to parse directive${
type !== null ? ' type:' + type : '' type !== null ? ' type:' + type : ''
} based on the text:${text}` } based on the text:${text}`
@ -176,7 +176,7 @@ export const detectDirective = function(text, type = null) {
*/ */
export const detectType = function(text) { export const detectType = function(text) {
text = text.replace(directive, '').replace(anyComment, '\n'); text = text.replace(directive, '').replace(anyComment, '\n');
logger.debug('Detecting diagram type based on the text ' + text); log.debug('Detecting diagram type based on the text ' + text);
if (text.match(/^\s*sequenceDiagram/)) { if (text.match(/^\s*sequenceDiagram/)) {
return 'sequence'; return 'sequence';
} }
@ -334,7 +334,7 @@ const calcLabelPosition = points => {
const calcCardinalityPosition = (isRelationTypePresent, points, initialPosition) => { const calcCardinalityPosition = (isRelationTypePresent, points, initialPosition) => {
let prevPoint; let prevPoint;
let totalDistance = 0; // eslint-disable-line let totalDistance = 0; // eslint-disable-line
logger.info('our points', points); log.info('our points', points);
if (points[0] !== initialPosition) { if (points[0] !== initialPosition) {
points = points.reverse(); points = points.reverse();
} }
@ -389,7 +389,7 @@ const calcTerminalLabelPosition = (terminalMarkerSize, position, _points) => {
let points = JSON.parse(JSON.stringify(_points)); let points = JSON.parse(JSON.stringify(_points));
let prevPoint; let prevPoint;
let totalDistance = 0; // eslint-disable-line let totalDistance = 0; // eslint-disable-line
logger.info('our points', points); log.info('our points', points);
if (position !== 'start_left' && position !== 'start_right') { if (position !== 'start_left' && position !== 'start_right') {
points = points.reverse(); points = points.reverse();
} }