Compare commits

..

3 Commits

Author SHA1 Message Date
Knut Sveidqvist
25c9e499b3 Merge branch 'develop' into layout-v3 2022-09-14 10:32:25 +02:00
Knut Sveidqvist
be5d9bd623 Pausing POC 2022-09-14 10:27:30 +02:00
Knut Sveidqvist
d851cc63bf Renderer for flowcharts using cytoscape, WIP 2022-09-13 17:41:43 +02:00
45 changed files with 953 additions and 219 deletions

View File

@@ -63,13 +63,6 @@
"rules": { "rules": {
"no-console": "off" "no-console": "off"
} }
},
{
"files": ["./**/*.spec.{ts,js}", "./cypress/**", "./demos/**", "./**/docs/**"],
"rules": {
"jsdoc/require-jsdoc": "off",
"@typescript-eslint/no-unused-vars": "off"
}
} }
] ]
} }

View File

@@ -0,0 +1,92 @@
<html>
<head>
<link href="https://fonts.googleapis.com/css?family=Montserrat&display=swap" rel="stylesheet" />
<link href="https://unpkg.com/tailwindcss@^1.0/dist/tailwind.min.css" rel="stylesheet" />
<link
rel="stylesheet"
href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css"
/>
<link
href="https://fonts.googleapis.com/css?family=Noto+Sans+SC&display=swap"
rel="stylesheet"
/>
<style>
body {
/* background: rgb(221, 208, 208); */
/* background:#333; */
font-family: 'Arial';
/* font-size: 18px !important; */
width: 100%;
/* display: flex; */
/* flex-direction: column; */
margin-left: 20px;
}
h1 {
color: grey;
}
.mermaid2,
.mermaid3 {
display: none;
}
.mermaid {
}
.mermaid svg {
border: 1px solid purple;
/* font-size: 18px !important; */
/* fontfamily: 'courier'; */
}
#cy {
width: 300px;
height: 300px;
display: block;
}
</style>
</head>
<body>
<div id="cy"></div>
<pre class="mermaid" style="width: 50%">
flowchart TD
id1 --> id2--> id3[I am number 3 and I<br/>am a gigantic node<br/>am a gigantic node<br/>am a gigantic node<br/>am a gigantic node<br/>am a gigantic node]--> id4--> id5 --> id1
id5 --> id4
id5 --> id4
</pre>
<pre class="mermaid2" style="width: 50%">
flowchart TD
id1 --> id2--> id3
id2 --> id1
</pre>
<script src="./mermaid.js"></script>
<script>
mermaid.parseError = function (err, hash) {
// console.error('Mermaid error: ', err);
};
mermaid.initialize({
maxTextSize: 900000,
startOnLoad: true,
securityLevel: 'loose',
logLevel: 0,
fontFamily: 'courier',
flowchart: {
// curve: 'curveLinear',
useMaxWidth: true,
htmlLabels: false,
fontFamily: 'courier',
defaultRenderer: 'cytoscape',
// defaultRenderer: 'dagre-wrapper',
},
});
function callback() {
alert('It worked');
}
function clickByFlow(elemName) {
const div = document.createElement('div');
div.className = 'created-by-click';
div.style = 'padding: 20px; background: green; color: white;';
div.innerText = 'Clicked By Flow';
document.getElementsByTagName('body')[0].appendChild(div);
}
</script>
</body>
</html>

View File

@@ -39,14 +39,6 @@
</head> </head>
<body> <body>
<pre class="mermaid2" style="width: 50%"> <pre class="mermaid2" style="width: 50%">
flowchart LR
a ---
</pre>
<pre class="mermaid" style="width: 50%">
flowchart LR
a2 ---
</pre>
<pre class="mermaid2" style="width: 50%">
flowchart LR flowchart LR
classDef aPID stroke:#4e4403,fill:#fdde29,color:#4e4403,rx:5px,ry:5px; classDef aPID stroke:#4e4403,fill:#fdde29,color:#4e4403,rx:5px,ry:5px;
classDef crm stroke:#333333,fill:#DCDCDC,color:#333333,rx:5px,ry:5px; classDef crm stroke:#333333,fill:#DCDCDC,color:#333333,rx:5px,ry:5px;
@@ -79,34 +71,12 @@ flowchart TD
end end
end end
</pre> </pre>
--> id2 --> id3(I have a long text) --> id4 --> id5 --> id1
<pre class="mermaid" style="width: 50%"> <pre class="mermaid" style="width: 50%">
flowchart TD flowchart TD
id1
release-branch[Create Release Branch]:::relClass
develop-branch[Update Develop Branch]:::relClass
github-release-draft[GitHub Release Draft]:::relClass
trigger-pipeline[Trigger Jenkins pipeline]:::fixClass
github-release[GitHub Release]:::postClass
build-ready --> release-branch
build-ready --> develop-branch
release-branch --> jenkins-release-build
jenkins-release-build --> github-release-draft
jenkins-release-build --> install-release
install-release --> verify-release
jenkins-release-build --> announce
github-release-draft --> github-release
verify-release --> verify-check
verify-check -- Yes --> github-release
verify-check -- No --> release-fix
release-fix --> release-branch-pr
verify-check -- No --> delete-artifacts
release-branch-pr --> trigger-pipeline
delete-artifacts --> trigger-pipeline
trigger-pipeline --> jenkins-release-build
</pre> </pre>
<pre id="cy" style="width: 50%"></pre>
<pre class="mermaid2" style="width: 50%"> <pre class="mermaid2" style="width: 50%">
flowchart LR flowchart LR
a["<strong>Haiya</strong>"]===>b a["<strong>Haiya</strong>"]===>b
@@ -131,7 +101,7 @@ flowchart TD
class A someclass; class A someclass;
class C someclass; class C someclass;
</pre> </pre>
<pre class="mermaid" style="width: 50%"> <pre class="mermaid2" style="width: 50%">
sequenceDiagram sequenceDiagram
title: My Sequence Diagram Title title: My Sequence Diagram Title
accTitle: My Acc Sequence Diagram accTitle: My Acc Sequence Diagram
@@ -141,14 +111,14 @@ flowchart TD
John-->>Alice: Great! John-->>Alice: Great!
Alice-)John: See you later! Alice-)John: See you later!
</pre> </pre>
<pre class="mermaid" style="width: 50%"> <pre class="mermaid2" style="width: 50%">
graph TD graph TD
A -->|000| B A -->|000| B
B -->|111| C B -->|111| C
linkStyle 1 stroke:#ff3,stroke-width:4px,color:red; linkStyle 1 stroke:#ff3,stroke-width:4px,color:red;
</pre> </pre>
<pre class="mermaid" style="width: 100%"> <pre class="mermaid2" style="width: 100%">
journey journey
accTitle: My User Journey Diagram accTitle: My User Journey Diagram
accDescr: My User Journey Diagram Description accDescr: My User Journey Diagram Description
@@ -162,10 +132,10 @@ graph TD
Go downstairs: 5: Me Go downstairs: 5: Me
Sit down: 5: Me Sit down: 5: Me
</pre> </pre>
<pre class="mermaid" style="width: 100%"> <pre class="mermaid2" style="width: 100%">
info info
</pre> </pre>
<pre class="mermaid" style="width: 100%"> <pre class="mermaid2" style="width: 100%">
requirementDiagram requirementDiagram
accTitle: My req Diagram accTitle: My req Diagram
accDescr: My req Diagram Description accDescr: My req Diagram Description
@@ -206,7 +176,7 @@ requirementDiagram
test_req - contains -> test_req3 test_req - contains -> test_req3
test_req <- copies - test_entity2 test_req <- copies - test_entity2
</pre> </pre>
<pre class="mermaid" style="width: 100%"> <pre class="mermaid2" style="width: 100%">
gantt gantt
dateFormat YYYY-MM-DD dateFormat YYYY-MM-DD
title Adding GANTT diagram functionality to mermaid title Adding GANTT diagram functionality to mermaid
@@ -238,7 +208,7 @@ gantt
Add gantt diagram to demo page :20h Add gantt diagram to demo page :20h
Add another diagram to demo page :48h Add another diagram to demo page :48h
</pre> </pre>
<pre class="mermaid" style="width: 100%"> <pre class="mermaid2" style="width: 100%">
stateDiagram stateDiagram
state Active { state Active {
Idle Idle
@@ -266,7 +236,7 @@ stateDiagram
end end
B ->> A: Return B ->> A: Return
</pre> </pre>
<pre class="mermaid" style="width: 100%"> <pre class="mermaid2" style="width: 100%">
classDiagram classDiagram
accTitle: My class diagram accTitle: My class diagram
accDescr: My class diagram Description accDescr: My class diagram Description
@@ -291,7 +261,7 @@ class Class10 {
A->>Bob: Hola A->>Bob: Hola
Bob-->A: Pasten ! Bob-->A: Pasten !
</pre> </pre>
<pre class="mermaid" style="width: 100%"> <pre class="mermaid2" style="width: 100%">
gitGraph gitGraph
commit id: "ZERO" commit id: "ZERO"
branch develop branch develop
@@ -320,7 +290,7 @@ flowchart TD
C -->|Two| E[iPhone] C -->|Two| E[iPhone]
C -->|Three| F[fa:fa-car Car] C -->|Three| F[fa:fa-car Car]
</pre> </pre>
<pre class="mermaid" style="width: 100%"> <pre class="mermaid2" style="width: 100%">
classDiagram classDiagram
Animal "1" <|-- Duck Animal "1" <|-- Duck
Animal <|-- Fish Animal <|-- Fish
@@ -343,7 +313,7 @@ flowchart TD
+run() +run()
} }
</pre> </pre>
<pre class="mermaid" style="width: 100%"> <pre class="mermaid2" style="width: 100%">
erDiagram erDiagram
CAR ||--o{ NAMED-DRIVER : allows CAR ||--o{ NAMED-DRIVER : allows
CAR { CAR {
@@ -375,6 +345,8 @@ flowchart TD
useMaxWidth: true, useMaxWidth: true,
htmlLabels: false, htmlLabels: false,
fontFamily: 'courier', fontFamily: 'courier',
defaultRenderer: 'cytoscape',
// defaultRenderer: 'dagre-wrapper',
}, },
}); });
function callback() { function callback() {
@@ -389,11 +361,6 @@ flowchart TD
document.getElementsByTagName('body')[0].appendChild(div); document.getElementsByTagName('body')[0].appendChild(div);
} }
mermaid.parseError = function (err, hash) {
console.error('In parse error:');
console.error(err);
};
</script> </script>
</body> </body>
</html> </html>

View File

@@ -47,17 +47,9 @@
<div>Security check</div> <div>Security check</div>
<div class="flex"> <div class="flex">
<pre id="diagram" class="mermaid"> <pre id="diagram" class="mermaid">
flowchart TD sequenceDiagram
A[myClass1] --> B[default] & C[default] Nothing:Valid;
B[default] & C[default] --> D[myClass2] </pre>
classDef default stroke-width:2px,fill:none,stroke:silver
classDef node color:red
classDef myClass1 color:#0000ff
classDef myClass2 stroke:#0000ff,fill:#ccccff
class A myClass1
class D myClass2
</pre
>
<div id="res" class=""></div> <div id="res" class=""></div>
</div> </div>
<script src="./mermaid.js"></script> <script src="./mermaid.js"></script>
@@ -67,7 +59,6 @@
}; };
mermaid.initialize({ mermaid.initialize({
startOnLoad: false, startOnLoad: false,
logLevel: 0,
// themeVariables: {relationLabelColor: 'red'} // themeVariables: {relationLabelColor: 'red'}
}); });
function callback() { function callback() {

View File

@@ -21,13 +21,22 @@
rel="stylesheet" rel="stylesheet"
href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.9.0/css/all.min.css" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.9.0/css/all.min.css"
/> />
<script src="//cdn.jsdelivr.net/npm/mermaid@9.1.7/dist/mermaid.min.js"></script> <script src="//cdn.jsdelivr.net/npm/mermaid@9.1.6/dist/mermaid.min.js"></script>
<!-- <script src="http://localhost:9000/mermaid.js"></script> --> <!-- <script src="http://localhost:9000/mermaid.js"></script> -->
<script <script>
defer // prettier-ignore
data-domain="mermaid-js.github.io" (function (i, s, o, g, r, a, m) {
src="https://plausible.io/js/plausible.js" i['GoogleAnalyticsObject'] = r; i[r] = i[r] || function () {
></script> (i[r].q = i[r].q || []).push(arguments)
}, i[r].l = 1 * new Date(); a = s.createElement(o),
m = s.getElementsByTagName(o)[0]; a.async = 1; a.src = g; m.parentNode.insertBefore(a, m)
})(window, document, 'script', 'https://www.google-analytics.com/analytics.js', 'ga');
ga('create', 'UA-153180559-1', 'auto');
if (location) {
ga('send', 'pageview', location.hash);
}
</script>
<script> <script>
var require = { var require = {
paths: { vs: 'https://cdnjs.cloudflare.com/ajax/libs/monaco-editor/0.29.1/min/vs' }, paths: { vs: 'https://cdnjs.cloudflare.com/ajax/libs/monaco-editor/0.29.1/min/vs' },

View File

@@ -64,16 +64,17 @@
}, },
"dependencies": { "dependencies": {
"@braintree/sanitize-url": "^6.0.0", "@braintree/sanitize-url": "^6.0.0",
"cytoscape": "^3.23.0",
"d3": "^7.0.0", "d3": "^7.0.0",
"dagre": "^0.8.5", "dagre": "^0.8.5",
"dagre-d3": "^0.6.4", "dagre-d3": "^0.6.4",
"dompurify": "2.4.0", "dompurify": "2.3.10",
"fast-clone": "^1.5.13", "fast-clone": "^1.5.13",
"graphlib": "^2.1.8", "graphlib": "^2.1.8",
"khroma": "^2.0.0", "khroma": "^2.0.0",
"moment-mini": "^2.24.0", "moment-mini": "^2.24.0",
"non-layered-tidy-tree-layout": "^2.0.2", "non-layered-tidy-tree-layout": "^2.0.2",
"stylis": "^4.1.2" "stylis": "^4.0.10"
}, },
"devDependencies": { "devDependencies": {
"@applitools/eyes-cypress": "^3.25.7", "@applitools/eyes-cypress": "^3.25.7",
@@ -126,7 +127,7 @@
"unist-util-flatmap": "^1.0.0", "unist-util-flatmap": "^1.0.0",
"webpack": "^5.53.0", "webpack": "^5.53.0",
"webpack-cli": "^4.7.2", "webpack-cli": "^4.7.2",
"webpack-dev-server": "^4.11.0", "webpack-dev-server": "^4.10.1",
"webpack-merge": "^5.8.0", "webpack-merge": "^5.8.0",
"webpack-node-externals": "^3.0.0" "webpack-node-externals": "^3.0.0"
}, },

View File

@@ -1,9 +1,11 @@
import { select } from 'd3'; import { select } from 'd3';
import { log } from '../logger'; import { log } from '../logger';
import { getConfig } from '../config'; import { getConfig } from '../config';
import { evaluate } from '../diagrams/common/common'; import { sanitizeText, evaluate } from '../diagrams/common/common';
import { decodeEntities } from '../mermaidAPI'; import { decodeEntities } from '../mermaidAPI';
const sanitizeTxt = (txt) => sanitizeText(txt, getConfig());
/** /**
* @param dom * @param dom
* @param styleFn * @param styleFn

View File

@@ -119,7 +119,7 @@ const dependency = (elem, type) => {
.append('path') .append('path')
.attr('d', 'M 18,7 L9,13 L14,7 L9,1 Z'); .attr('d', 'M 18,7 L9,13 L14,7 L9,1 Z');
}; };
const lollipop = (elem, type) => { const lollipop = (elem, type, id) => {
elem elem
.append('defs') .append('defs')
.append('marker') .append('marker')

View File

@@ -6,7 +6,7 @@ import intersect from './intersect/index.js';
import createLabel from './createLabel'; import createLabel from './createLabel';
import note from './shapes/note'; import note from './shapes/note';
import { parseMember } from '../diagrams/class/svgDraw'; import { parseMember } from '../diagrams/class/svgDraw';
import { evaluate } from '../diagrams/common/common'; import { evaluate, sanitizeText as sanitize } from '../diagrams/common/common';
const question = (parent, node) => { const question = (parent, node) => {
const { shapeSvg, bbox } = labelHelper(parent, node, undefined, true); const { shapeSvg, bbox } = labelHelper(parent, node, undefined, true);
@@ -346,7 +346,7 @@ const rect = (parent, node) => {
}; };
const labelRect = (parent, node) => { const labelRect = (parent, node) => {
const { shapeSvg } = labelHelper(parent, node, 'label', true); const { shapeSvg, bbox, halfPadding } = labelHelper(parent, node, 'label', true);
log.trace('Classes = ', node.classes); log.trace('Classes = ', node.classes);
// add the rect // add the rect
@@ -1062,6 +1062,7 @@ export const insertNode = (elem, node, dir) => {
if (node.haveCallback) { if (node.haveCallback) {
nodeElems[node.id].attr('class', nodeElems[node.id].attr('class') + ' clickable'); nodeElems[node.id].attr('class', nodeElems[node.id].attr('class') + ' clickable');
} }
return newEl;
}; };
export const setNodeElem = (elem, node) => { export const setNodeElem = (elem, node) => {
nodeElems[node.id] = elem; nodeElems[node.id] = elem;

View File

@@ -228,9 +228,9 @@ const config: Partial<MermaidConfig> = {
* Decides which rendering engine that is to be used for the rendering. Legal values are: * Decides which rendering engine that is to be used for the rendering. Legal values are:
* dagre-d3 dagre-wrapper - wrapper for dagre implemented in mermaid * dagre-d3 dagre-wrapper - wrapper for dagre implemented in mermaid
* *
* Default value: 'dagre-wrapper' * Default value: 'dagre-d3'
*/ */
defaultRenderer: 'dagre-wrapper', defaultRenderer: 'dagre-d3',
}, },
/** The object containing configurations specific for sequence diagrams */ /** The object containing configurations specific for sequence diagrams */
@@ -387,8 +387,7 @@ const config: Partial<MermaidConfig> = {
* *
* **Notes:** * **Notes:**
* *
* This will display arrows that start and begin at the same node as right angles, rather than a * This will display arrows that start and begin at the same node as right angles, rather than a curve
* curve
* *
* Default value: false * Default value: false
*/ */
@@ -803,8 +802,7 @@ const config: Partial<MermaidConfig> = {
* *
* **Notes:** * **Notes:**
* *
* This will display arrows that start and begin at the same node as right angles, rather than a * This will display arrows that start and begin at the same node as right angles, rather than a curves
* curves
* *
* Default value: false * Default value: false
*/ */

View File

@@ -41,9 +41,11 @@ import erStyles from '../diagrams/er/styles';
import flowParser from '../diagrams/flowchart/parser/flow'; import flowParser from '../diagrams/flowchart/parser/flow';
import { flowDetector } from '../diagrams/flowchart/flowDetector'; import { flowDetector } from '../diagrams/flowchart/flowDetector';
import { flowDetectorV2 } from '../diagrams/flowchart/flowDetector-v2'; import { flowDetectorV2 } from '../diagrams/flowchart/flowDetector-v2';
import { flowDetectorV3 } from '../diagrams/flowchart/flowDetector-v3';
import flowDb from '../diagrams/flowchart/flowDb'; import flowDb from '../diagrams/flowchart/flowDb';
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';
import flowRendererV3 from '../diagrams/flowchart/flowRenderer-v3';
import flowStyles from '../diagrams/flowchart/styles'; import flowStyles from '../diagrams/flowchart/styles';
// @ts-ignore: TODO Fix ts errors // @ts-ignore: TODO Fix ts errors
@@ -97,33 +99,7 @@ import journeyDb from '../diagrams/user-journey/journeyDb';
import journeyRenderer from '../diagrams/user-journey/journeyRenderer'; import journeyRenderer from '../diagrams/user-journey/journeyRenderer';
import journeyStyles from '../diagrams/user-journey/styles'; import journeyStyles from '../diagrams/user-journey/styles';
import errorRenderer from '../diagrams/error/errorRenderer';
import errorStyles from '../diagrams/error/styles';
export const addDiagrams = () => { export const addDiagrams = () => {
registerDiagram(
'error',
// Special diagram with error messages but setup as a regular diagram
{
db: {
clear: () => {
// Quite ok, clear needs to be there for error to work as a regular diagram
},
},
styles: errorStyles,
renderer: errorRenderer,
parser: {
parser: { yy: {} },
parse: () => {
// no op
},
},
init: () => {
// no op
},
},
(text) => text.toLowerCase().trim() === 'error'
);
registerDiagram( registerDiagram(
'c4', 'c4',
{ {
@@ -331,6 +307,20 @@ export const addDiagrams = () => {
}, },
flowDetectorV2 flowDetectorV2
); );
registerDiagram(
'flowchart-v3',
{
parser: flowParser,
db: flowDb,
renderer: flowRendererV3,
styles: flowStyles,
init: () => {
flowDb.clear();
flowDb.setGen('gen-3');
},
},
flowDetectorV3
);
registerDiagram( registerDiagram(
'gitGraph', 'gitGraph',
{ parser: gitGraphParser, db: gitGraphDb, renderer: gitGraphRenderer, styles: gitGraphStyles }, { parser: gitGraphParser, db: gitGraphDb, renderer: gitGraphRenderer, styles: gitGraphStyles },

View File

@@ -1,5 +1,6 @@
import mermaidAPI from '../../mermaidAPI'; import mermaidAPI from '../../mermaidAPI';
import * as configApi from '../../config'; import * as configApi from '../../config';
import { log } from '../../logger';
import { sanitizeText } from '../common/common'; import { sanitizeText } from '../common/common';
import { setAccTitle, getAccTitle, getAccDescription, setAccDescription } from '../../commonDb'; import { setAccTitle, getAccTitle, getAccDescription, setAccDescription } from '../../commonDb';
@@ -20,6 +21,7 @@ let boundarys = [
let rels = []; let rels = [];
let title = ''; let title = '';
let wrapEnabled = false; let wrapEnabled = false;
let description = '';
let c4ShapeInRow = 4; let c4ShapeInRow = 4;
let c4BoundaryInRow = 2; let c4BoundaryInRow = 2;
var c4Type; var c4Type;
@@ -634,13 +636,13 @@ export const updateLayoutConfig = function (typeC4Shape, c4ShapeInRowParam, c4Bo
let c4BoundaryInRowValue = c4BoundaryInRow; let c4BoundaryInRowValue = c4BoundaryInRow;
if (typeof c4ShapeInRowParam === 'object') { if (typeof c4ShapeInRowParam === 'object') {
const value = Object.values(c4ShapeInRowParam)[0]; let [key, value] = Object.entries(c4ShapeInRowParam)[0];
c4ShapeInRowValue = parseInt(value); c4ShapeInRowValue = parseInt(value);
} else { } else {
c4ShapeInRowValue = parseInt(c4ShapeInRowParam); c4ShapeInRowValue = parseInt(c4ShapeInRowParam);
} }
if (typeof c4BoundaryInRowParam === 'object') { if (typeof c4BoundaryInRowParam === 'object') {
const value = Object.values(c4BoundaryInRowParam)[0]; let [key, value] = Object.entries(c4BoundaryInRowParam)[0];
c4BoundaryInRowValue = parseInt(value); c4BoundaryInRowValue = parseInt(value);
} else { } else {
c4BoundaryInRowValue = parseInt(c4BoundaryInRowParam); c4BoundaryInRowValue = parseInt(c4BoundaryInRowParam);
@@ -719,6 +721,7 @@ export const clear = function () {
boundaryParseStack = ['']; boundaryParseStack = [''];
title = ''; title = '';
wrapEnabled = false; wrapEnabled = false;
description = '';
c4ShapeInRow = 4; c4ShapeInRow = 4;
c4BoundaryInRow = 2; c4BoundaryInRow = 2;
}; };

View File

@@ -1,5 +1,5 @@
import { select } from 'd3'; import { select } from 'd3';
import svgDraw from './svgDraw'; import svgDraw, { drawText, fixLifeLineHeights } from './svgDraw';
import { log } from '../../logger'; import { log } from '../../logger';
import { parser } from './parser/c4Diagram'; import { parser } from './parser/c4Diagram';
import common from '../common/common'; import common from '../common/common';
@@ -298,7 +298,7 @@ export const drawC4ShapeArray = function (currentBounds, diagram, c4ShapeArray,
currentBounds.insert(c4Shape); currentBounds.insert(c4Shape);
svgDraw.drawC4Shape(diagram, c4Shape, conf); const height = svgDraw.drawC4Shape(diagram, c4Shape, conf);
} }
currentBounds.bumpLastMargin(conf.c4ShapeMargin); currentBounds.bumpLastMargin(conf.c4ShapeMargin);
@@ -616,6 +616,7 @@ export const draw = function (_text, id, _version, diagObj) {
globalBoundaryMaxY = conf.diagramMarginY; globalBoundaryMaxY = conf.diagramMarginY;
const title = diagObj.db.getTitle(); const title = diagObj.db.getTitle();
const c4type = diagObj.db.getC4Type();
let currentBoundarys = diagObj.db.getBoundarys(''); let currentBoundarys = diagObj.db.getBoundarys('');
// switch (c4type) { // switch (c4type) {
// case 'C4Context': // case 'C4Context':

View File

@@ -1,4 +1,5 @@
import common from '../common/common'; import common from '../common/common';
import { addFunction } from '../../interactionDb';
import { sanitizeUrl } from '@braintree/sanitize-url'; import { sanitizeUrl } from '@braintree/sanitize-url';
export const drawRect = function (elem, rectData) { export const drawRect = function (elem, rectData) {

View File

@@ -3,6 +3,7 @@ import graphlib from 'graphlib';
import { log } from '../../logger'; import { log } from '../../logger';
import { getConfig } from '../../config'; 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 { curveLinear } from 'd3'; import { curveLinear } from 'd3';
import { interpolateToCurve, getStylesFromArray } from '../../utils'; import { interpolateToCurve, getStylesFromArray } from '../../utils';
import { setupGraphViewbox } from '../../setupGraphViewbox'; import { setupGraphViewbox } from '../../setupGraphViewbox';
@@ -10,6 +11,7 @@ import common from '../common/common';
import addSVGAccessibilityFields from '../../accessibility'; import addSVGAccessibilityFields from '../../accessibility';
let idCache = {}; let idCache = {};
const padding = 20;
const sanitizeText = (txt) => common.sanitizeText(txt, getConfig()); const sanitizeText = (txt) => common.sanitizeText(txt, getConfig());
@@ -233,6 +235,20 @@ export const addRelations = function (relations, g) {
}); });
}; };
/**
* Gets the ID with the same label as in the cache
*
* @param {string} label The label to look for
* @returns {string} The resulting ID
*/
const getGraphId = function (label) {
const foundEntry = Object.entries(idCache).find((entry) => entry[1].label === label);
if (foundEntry) {
return foundEntry[0];
}
};
/** /**
* Merges the value of `conf` with the passed `cnf` * Merges the value of `conf` with the passed `cnf`
* *

View File

@@ -10,6 +10,12 @@ import addSVGAccessibilityFields from '../../accessibility';
let idCache = {}; let idCache = {};
const padding = 20; const padding = 20;
const confa = {
dividerMargin: 10,
padding: 5,
textHeight: 10,
};
/** /**
* Gets the ID with the same label as in the cache * Gets the ID with the same label as in the cache
* *
@@ -157,6 +163,7 @@ export const draw = function (text, id, _version, diagObj) {
securityLevel === 'sandbox' securityLevel === 'sandbox'
? select(sandboxElement.nodes()[0].contentDocument.body) ? select(sandboxElement.nodes()[0].contentDocument.body)
: select('body'); : select('body');
const doc = securityLevel === 'sandbox' ? sandboxElement.nodes()[0].contentDocument : document;
// Fetch the default direction, use TD if none was found // Fetch the default direction, use TD if none was found
const diagram = root.select(`[id='${id}']`); const diagram = root.select(`[id='${id}']`);

View File

@@ -1,7 +1,7 @@
import { log } from '../../logger'; import { log } from '../../logger';
import mermaidAPI from '../../mermaidAPI'; import mermaidAPI from '../../mermaidAPI';
import * as configApi from '../../config'; import * as configApi from '../../config';
import common from '../common/common';
import { import {
setAccTitle, setAccTitle,
getAccTitle, getAccTitle,
@@ -12,6 +12,8 @@ import {
let entities = {}; let entities = {};
let relationships = []; let relationships = [];
let title = '';
let description = '';
const Cardinality = { const Cardinality = {
ZERO_OR_ONE: 'ZERO_OR_ONE', ZERO_OR_ONE: 'ZERO_OR_ONE',
@@ -76,6 +78,7 @@ const getRelationships = () => relationships;
const clear = function () { const clear = function () {
entities = {}; entities = {};
relationships = []; relationships = [];
title = '';
commonClear(); commonClear();
}; };

View File

@@ -1,3 +0,0 @@
const getStyles = () => ``;
export default getStyles;

View File

@@ -1,8 +1,23 @@
import type { DiagramDetector } from '../../diagram-api/detectType'; import type { DiagramDetector } from '../../diagram-api/detectType';
import { log } from '../../diagram-api/diagramAPI';
export const flowDetectorV2: DiagramDetector = (txt, config) => { export const flowDetectorV2: DiagramDetector = (txt, config) => {
log.info('Config in flowDetector-v2 defaultRenderer: ', config?.flowchart?.defaultRenderer);
// If we have confgured to use cytoscape then we should always return false here
if (config?.flowchart?.defaultRenderer === 'cytoscape') {
log.info('flowDetector-v2 returning false');
return false;
} else {
log.info('flowDetector-v2 not cytoscape');
}
// If we have confgured to use dagre-wrapper then we should return true in this function for graph code thus making it use the new flowchart diagram // If we have confgured to use dagre-wrapper then we should return true in this function for graph code thus making it use the new flowchart diagram
if (config?.flowchart?.defaultRenderer === 'dagre-wrapper' && txt.match(/^\s*graph/) !== null) if (config?.flowchart?.defaultRenderer === 'dagre-wrapper' && txt.match(/^\s*graph/) !== null)
return true; return true;
log.info('Config in flowDetector-v2 returning', txt.match(/^\s*flowchart/) !== null);
return txt.match(/^\s*flowchart/) !== null; return txt.match(/^\s*flowchart/) !== null;
}; };
/*
if (((_a = config === null || config === void 0 ? void 0 : config.flowchart) === null || _a === void 0 ? void 0 : _a.defaultRenderer) === 'dagre-wrapper1' && txt.match(/^\s*graph/) !== null)
*/

View File

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

View File

@@ -12,7 +12,7 @@ import { interpolateToCurve, getStylesFromArray } from '../../utils';
import { setupGraphViewbox } from '../../setupGraphViewbox'; import { setupGraphViewbox } from '../../setupGraphViewbox';
import addSVGAccessibilityFields from '../../accessibility'; import addSVGAccessibilityFields from '../../accessibility';
const conf = {}; let conf = {};
export const setConf = function (cnf) { export const setConf = function (cnf) {
const keys = Object.keys(cnf); const keys = Object.keys(cnf);
for (let i = 0; i < keys.length; i++) { for (let i = 0; i < keys.length; i++) {
@@ -351,6 +351,7 @@ export const getClasses = function (text, diagObj) {
*/ */
export const draw = function (text, id, _version, diagObj) { export const draw = function (text, id, _version, diagObj) {
// const conf = config.getConfig(_version);
log.info('Drawing flowchart'); log.info('Drawing flowchart');
diagObj.db.clear(); diagObj.db.clear();
flowDb.setGen('gen-2'); flowDb.setGen('gen-2');

View File

@@ -0,0 +1,549 @@
import graphlib from 'graphlib';
import { select, curveLinear, selectAll } from 'd3';
import flowDb from './flowDb';
import { getConfig } from '../../config';
import { insertNode } from '../../dagre-wrapper/nodes.js';
import { render } from '../../dagre-wrapper/index.js';
import addHtmlLabel from 'dagre-d3/lib/label/add-html-label.js';
import { log } from '../../logger';
import common, { evaluate } from '../common/common';
import { interpolateToCurve, getStylesFromArray } from '../../utils';
import { setupGraphViewbox } from '../../setupGraphViewbox';
import addSVGAccessibilityFields from '../../accessibility';
import cytoscape from 'cytoscape';
const conf = {};
export const setConf = function (cnf) {
const keys = Object.keys(cnf);
for (let i = 0; i < keys.length; i++) {
conf[keys[i]] = cnf[keys[i]];
}
};
// /**
// * Function that adds the vertices found during parsing to the graph to be rendered.
// *
// * @param vert Object containing the vertices.
// * @param g The graph that is to be drawn.
// * @param svgId
// * @param root
// * @param doc
// * @param diagObj
// */
export const addVertices = function (vert, cy, svgId, root, doc, diagObj) {
const svg = root.select(`[id="${svgId}"]`);
const nodes = svg.insert('g').attr('class', 'nodes');
const keys = Object.keys(vert);
// Iterate through each item in the vertex object (containing all the vertices found) in the graph definition
keys.forEach(function (id) {
const vertex = vert[id];
/**
* Variable for storing the classes for the vertex
*
* @type {string}
*/
let classStr = 'default';
if (vertex.classes.length > 0) {
classStr = vertex.classes.join(' ');
}
const styles = getStylesFromArray(vertex.styles);
// Use vertex id as text in the box if no text is provided by the graph definition
let vertexText = vertex.text !== undefined ? vertex.text : vertex.id;
// We create a SVG label, either by delegating to addHtmlLabel or manually
let vertexNode;
if (evaluate(getConfig().flowchart.htmlLabels)) {
// TODO: addHtmlLabel accepts a labelStyle. Do we possibly have that?
const node = {
label: vertexText.replace(
/fa[lrsb]?:fa-[\w-]+/g,
(s) => `<i class='${s.replace(':', ' ')}'></i>`
),
};
vertexNode = addHtmlLabel(svg, node).node();
vertexNode.parentNode.removeChild(vertexNode);
} else {
const svgLabel = doc.createElementNS('http://www.w3.org/2000/svg', 'text');
svgLabel.setAttribute('style', styles.labelStyle.replace('color:', 'fill:'));
const rows = vertexText.split(common.lineBreakRegex);
for (let j = 0; j < rows.length; j++) {
const tspan = doc.createElementNS('http://www.w3.org/2000/svg', 'tspan');
tspan.setAttributeNS('http://www.w3.org/XML/1998/namespace', 'xml:space', 'preserve');
tspan.setAttribute('dy', '1em');
tspan.setAttribute('x', '1');
tspan.textContent = rows[j];
svgLabel.appendChild(tspan);
}
vertexNode = svgLabel;
}
let radious = 0;
let _shape = '';
// Set the shape based parameters
switch (vertex.type) {
case 'round':
radious = 5;
_shape = 'rect';
break;
case 'square':
_shape = 'rect';
break;
case 'diamond':
_shape = 'question';
break;
case 'hexagon':
_shape = 'hexagon';
break;
case 'odd':
_shape = 'rect_left_inv_arrow';
break;
case 'lean_right':
_shape = 'lean_right';
break;
case 'lean_left':
_shape = 'lean_left';
break;
case 'trapezoid':
_shape = 'trapezoid';
break;
case 'inv_trapezoid':
_shape = 'inv_trapezoid';
break;
case 'odd_right':
_shape = 'rect_left_inv_arrow';
break;
case 'circle':
_shape = 'circle';
break;
case 'ellipse':
_shape = 'ellipse';
break;
case 'stadium':
_shape = 'stadium';
break;
case 'subroutine':
_shape = 'subroutine';
break;
case 'cylinder':
_shape = 'cylinder';
break;
case 'group':
_shape = 'rect';
break;
case 'doublecircle':
_shape = 'doublecircle';
break;
default:
_shape = 'rect';
}
// // Add the node
const node = {
labelStyle: styles.labelStyle,
shape: _shape,
labelText: vertexText,
rx: radious,
ry: radious,
class: classStr,
style: styles.style,
id: vertex.id,
link: vertex.link,
linkTarget: vertex.linkTarget,
tooltip: diagObj.db.getTooltip(vertex.id) || '',
domId: diagObj.db.lookUpDomId(vertex.id),
haveCallback: vertex.haveCallback,
width: vertex.type === 'group' ? 500 : undefined,
dir: vertex.dir,
type: vertex.type,
props: vertex.props,
padding: getConfig().flowchart.padding,
};
const nodeEl = insertNode(nodes, node, vertex.dir);
const boundingBox = nodeEl.node().getBBox();
cy.add({
group: 'nodes',
data: {
id: vertex.id,
labelStyle: styles.labelStyle,
shape: _shape,
labelText: vertexText,
rx: radious,
ry: radious,
class: classStr,
style: styles.style,
link: vertex.link,
linkTarget: vertex.linkTarget,
tooltip: diagObj.db.getTooltip(vertex.id) || '',
domId: diagObj.db.lookUpDomId(vertex.id),
haveCallback: vertex.haveCallback,
width: vertex.type === 'group' ? 500 : undefined,
dir: vertex.dir,
type: vertex.type,
props: vertex.props,
padding: getConfig().flowchart.padding,
boundingBox,
el: nodeEl,
},
});
log.trace('setNode', {
labelStyle: styles.labelStyle,
shape: _shape,
labelText: vertexText,
rx: radious,
ry: radious,
class: classStr,
style: styles.style,
id: vertex.id,
domId: diagObj.db.lookUpDomId(vertex.id),
width: vertex.type === 'group' ? 500 : undefined,
type: vertex.type,
dir: vertex.dir,
props: vertex.props,
padding: getConfig().flowchart.padding,
});
});
};
/**
* Add edges to graph based on parsed graph definition
*
* @param {object} edges The edges to add to the graph
* @param {object} g The graph object
* @param cy
* @param diagObj
*/
export const addEdges = function (edges, cy, diagObj) {
// log.info('abc78 edges = ', edges);
let cnt = 0;
let linkIdCnt = {};
let defaultStyle;
let defaultLabelStyle;
if (typeof edges.defaultStyle !== 'undefined') {
const defaultStyles = getStylesFromArray(edges.defaultStyle);
defaultStyle = defaultStyles.style;
defaultLabelStyle = defaultStyles.labelStyle;
}
edges.forEach(function (edge) {
cnt++;
// Identify Link
var linkIdBase = 'L-' + edge.start + '-' + edge.end;
// count the links from+to the same node to give unique id
if (typeof linkIdCnt[linkIdBase] === 'undefined') {
linkIdCnt[linkIdBase] = 0;
log.info('abc78 new entry', linkIdBase, linkIdCnt[linkIdBase]);
} else {
linkIdCnt[linkIdBase]++;
log.info('abc78 new entry', linkIdBase, linkIdCnt[linkIdBase]);
}
let linkId = linkIdBase + '-' + linkIdCnt[linkIdBase];
log.info('abc78 new link id to be used is', linkIdBase, linkId, linkIdCnt[linkIdBase]);
var linkNameStart = 'LS-' + edge.start;
var linkNameEnd = 'LE-' + edge.end;
const edgeData = { style: '', labelStyle: '' };
edgeData.minlen = edge.length || 1;
//edgeData.id = 'id' + cnt;
// Set link type for rendering
if (edge.type === 'arrow_open') {
edgeData.arrowhead = 'none';
} else {
edgeData.arrowhead = 'normal';
}
// Check of arrow types, placed here in order not to break old rendering
edgeData.arrowTypeStart = 'arrow_open';
edgeData.arrowTypeEnd = 'arrow_open';
/* eslint-disable no-fallthrough */
switch (edge.type) {
case 'double_arrow_cross':
edgeData.arrowTypeStart = 'arrow_cross';
case 'arrow_cross':
edgeData.arrowTypeEnd = 'arrow_cross';
break;
case 'double_arrow_point':
edgeData.arrowTypeStart = 'arrow_point';
case 'arrow_point':
edgeData.arrowTypeEnd = 'arrow_point';
break;
case 'double_arrow_circle':
edgeData.arrowTypeStart = 'arrow_circle';
case 'arrow_circle':
edgeData.arrowTypeEnd = 'arrow_circle';
break;
}
let style = '';
let labelStyle = '';
switch (edge.stroke) {
case 'normal':
style = 'fill:none;';
if (typeof defaultStyle !== 'undefined') {
style = defaultStyle;
}
if (typeof defaultLabelStyle !== 'undefined') {
labelStyle = defaultLabelStyle;
}
edgeData.thickness = 'normal';
edgeData.pattern = 'solid';
break;
case 'dotted':
edgeData.thickness = 'normal';
edgeData.pattern = 'dotted';
edgeData.style = 'fill:none;stroke-width:2px;stroke-dasharray:3;';
break;
case 'thick':
edgeData.thickness = 'thick';
edgeData.pattern = 'solid';
edgeData.style = 'stroke-width: 3.5px;fill:none;';
break;
}
if (typeof edge.style !== 'undefined') {
const styles = getStylesFromArray(edge.style);
style = styles.style;
labelStyle = styles.labelStyle;
}
edgeData.style = edgeData.style += style;
edgeData.labelStyle = edgeData.labelStyle += labelStyle;
if (typeof edge.interpolate !== 'undefined') {
edgeData.curve = interpolateToCurve(edge.interpolate, curveLinear);
} else if (typeof edges.defaultInterpolate !== 'undefined') {
edgeData.curve = interpolateToCurve(edges.defaultInterpolate, curveLinear);
} else {
edgeData.curve = interpolateToCurve(conf.curve, curveLinear);
}
if (typeof edge.text === 'undefined') {
if (typeof edge.style !== 'undefined') {
edgeData.arrowheadStyle = 'fill: #333';
}
} else {
edgeData.arrowheadStyle = 'fill: #333';
edgeData.labelpos = 'c';
}
edgeData.labelType = 'text';
edgeData.label = edge.text.replace(common.lineBreakRegex, '\n');
if (typeof edge.style === 'undefined') {
edgeData.style = edgeData.style || 'stroke: #333; stroke-width: 1.5px;fill:none;';
}
edgeData.labelStyle = edgeData.labelStyle.replace('color:', 'fill:');
edgeData.id = linkId;
edgeData.classes = 'flowchart-link ' + linkNameStart + ' ' + linkNameEnd;
// Add the edge to the graph
cy.add({ group: 'edges', data: { source: edge.start, target: edge.end, edgeData, id: cnt } });
});
};
/**
* Returns the all the styles from classDef statements in the graph definition.
*
* @param text
* @param diagObj
* @returns {object} ClassDef styles
*/
export const getClasses = function (text, diagObj) {
log.info('Extracting classes');
diagObj.db.clear();
try {
// Parse the graph definition
diagObj.parse(text);
return diagObj.db.getClasses();
} catch (e) {
return;
}
};
/**
* Draws a flowchart in the tag with id: id based on the graph definition in text.
*
* @param text
* @param id
*/
export const draw = function (text, id, _version, diagObj) {
return new Promise(function (resolve, reject) {
const cy = cytoscape({
// styleEnabled: false,
// animate: false,
// ready: function () {
// log.info('Ready', this);
// },
container: document.getElementById('cy'), // container to render in
elements: [
// list of graph elements to start with
// { // node a
// data: { id: 'a' }
// },
// { // node b
// data: { id: 'b' }
// },
// { // edge ab
// data: { id: 'ab', source: 'a', target: 'b' }
// }
],
style: [
// the stylesheet for the graph
{
selector: 'node',
style: {
'background-color': '#666',
label: 'data(labelText)',
},
},
{
selector: 'edge',
style: {
width: 3,
'line-color': '#ccc',
'target-arrow-color': '#ccc',
'target-arrow-shape': 'triangle',
'curve-style': 'bezier',
label: 'data(id)',
},
},
],
layout: {
name: 'breadthfirst',
rows: 1,
},
});
log.info('Drawing flowchart using v3 renderer');
// Fetch the default direction, use TD if none was found
let dir = diagObj.db.getDirection();
if (typeof dir === 'undefined') {
dir = 'TD';
}
const { securityLevel, flowchart: conf } = getConfig();
// const nodeSpacing = conf.nodeSpacing || 50;
// const rankSpacing = conf.rankSpacing || 50;
// Handle root and document for when rendering in sandbox mode
let sandboxElement;
if (securityLevel === 'sandbox') {
sandboxElement = select('#i' + id);
}
const root =
securityLevel === 'sandbox'
? select(sandboxElement.nodes()[0].contentDocument.body)
: select('body');
const doc = securityLevel === 'sandbox' ? sandboxElement.nodes()[0].contentDocument : document;
const svg = root.select(`[id="${id}"]`);
const edgesEl = svg.insert('g').attr('class', 'edges edgePath');
// Fetch the vertices/nodes and edges/links from the parsed graph definition
const vert = diagObj.db.getVertices();
addVertices(vert, cy, id, root, doc, diagObj);
// c.style();
// Make cytoscape care about the dimensisions of the nodes
cy.nodes().forEach(function (n) {
n.layoutDimensions = () => {
const boundingBox = n.data().boundingBox;
return { w: boundingBox.width, h: boundingBox.height };
};
});
const edges = diagObj.db.getEdges();
addEdges(edges, cy, diagObj);
cy.layout({
// name: 'grid',
// name: 'circle',
name: 'cose',
// name: 'breadthfirst',
headless: true,
styleEnabled: false,
animate: false,
}).run();
log.info('Positions', cy.nodes().positions());
window.cy = cy;
cy.ready((e) => {
log.info('Ready', e);
setTimeout(() => {
cy.nodes().map((node, id) => {
const data = node.data();
log.info('Position: (', node.position().x, ', ', node.position().y, ')', data);
data.el.attr('transform', `translate(${node.position().x}, ${node.position().y})`);
// document
// .querySelector(`[id="${data.domId}"]`)
// .setAttribute('transform', `translate(${node.position().x}, ${node.position().y})`);
log.info('Id = ', data.domId, svg.select(`[id="${data.domId}"]`), data.el.node());
});
cy.edges().map((edge, id) => {
const data = edge.data();
if (edge[0]._private.bodyBounds) {
const bounds = edge[0]._private.rscratch;
log.info(
id,
// 'x:',
// edge.controlPoints(),
// 'y:',
edge[0]._private.rscratch
// 'w:',
// edge.boundingbox().w,
// 'h:',
// edge.boundingbox().h,
// edge.midPoint()
);
// data.el.attr('transform', `translate(${node.position().x}, ${node.position().y})`);
// edgesEl
// .insert('line')
// .attr('x1', bounds.startX)
// .attr('y1', bounds.startY)
// .attr('x2', bounds.endX)
// .attr('y2', bounds.endY)
// .attr('class', 'path');
edgesEl
.insert('path')
// Todo use regular line function
.attr(
'd',
`M ${bounds.startX},${bounds.startY} L ${bounds.midX},${bounds.midY} L${bounds.endX},${bounds.endY} `
)
.attr('class', 'path')
.attr('fill', 'none');
}
});
log.info(cy.json());
setupGraphViewbox({}, svg, conf.diagramPadding, conf.useMaxWidth);
resolve();
}, 500);
});
});
};
export default {
// setConf,
// addVertices,
// addEdges,
getClasses,
draw,
};

View File

@@ -29,6 +29,8 @@ export const setConf = function (cnf) {
* @param diagObj * @param diagObj
*/ */
export const addVertices = function (vert, g, svgId, root, _doc, diagObj) { export const addVertices = function (vert, g, svgId, root, _doc, diagObj) {
const securityLevel = getConfig().securityLevel;
const svg = !root ? select(`[id="${svgId}"]`) : root.select(`[id="${svgId}"]`); const svg = !root ? select(`[id="${svgId}"]`) : root.select(`[id="${svgId}"]`);
const doc = !_doc ? document : _doc; const doc = !_doc ? document : _doc;
const keys = Object.keys(vert); const keys = Object.keys(vert);

View File

@@ -4,7 +4,7 @@ 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';
import common from '../common/common';
import { import {
setAccTitle, setAccTitle,
getAccTitle, getAccTitle,
@@ -21,6 +21,8 @@ let todayMarker = '';
let includes = []; let includes = [];
let excludes = []; let excludes = [];
let links = {}; let links = {};
let title = '';
let accDescription = '';
let sections = []; let sections = [];
let tasks = []; let tasks = [];
let currentSection = ''; let currentSection = '';
@@ -32,6 +34,10 @@ let topAxis = false;
// The serial order of the task in the script // The serial order of the task in the script
let lastOrder = 0; let lastOrder = 0;
const sanitizeText = function (txt) {
return common.sanitizeText(txt, configApi.getConfig());
};
export const parseDirective = function (statement, context, type) { export const parseDirective = function (statement, context, type) {
mermaidAPI.parseDirective(this, statement, context, type); mermaidAPI.parseDirective(this, statement, context, type);
}; };
@@ -41,6 +47,7 @@ export const clear = function () {
tasks = []; tasks = [];
currentSection = ''; currentSection = '';
funs = []; funs = [];
title = '';
taskCnt = 0; taskCnt = 0;
lastTask = undefined; lastTask = undefined;
lastTaskID = undefined; lastTaskID = undefined;
@@ -240,8 +247,7 @@ const getStartDate = function (prevTime, dateFormat, str) {
* - `ms` for milliseconds * - `ms` for milliseconds
* *
* @param {string} str - A string representing the duration. * @param {string} str - A string representing the duration.
* @returns {moment.Duration} A moment duration, including an invalid moment for invalid input * @returns {moment.Duration} A moment duration, including an invalid moment for invalid input string.
* string.
*/ */
const parseDuration = function (str) { const parseDuration = function (str) {
const statement = /^(\d+(?:\.\d+)?)([yMwdhms]|ms)$/.exec(str.trim()); const statement = /^(\d+(?:\.\d+)?)([yMwdhms]|ms)$/.exec(str.trim());

View File

@@ -391,6 +391,7 @@ export const draw = function (text, id, version, diagObj) {
if (securityLevel === 'sandbox') { if (securityLevel === 'sandbox') {
let sandboxElement; let sandboxElement;
sandboxElement = select('#i' + id); sandboxElement = select('#i' + id);
const root = select(sandboxElement.nodes()[0].contentDocument.body);
const doc = sandboxElement.nodes()[0].contentDocument; const doc = sandboxElement.nodes()[0].contentDocument;
rectangles rectangles

View File

@@ -372,16 +372,14 @@ describe('when parsing a gitGraph', function () {
branch cherry-pick03 branch cherry-pick03
branch branch/example-branch branch branch/example-branch
branch merge/test_merge branch merge/test_merge
%% single character branch name
branch A
`; `;
parser.parse(str); parser.parse(str);
const commits = parser.yy.getCommits(); const commits = parser.yy.getCommits();
expect(Object.keys(commits).length).toBe(1); expect(Object.keys(commits).length).toBe(1);
expect(parser.yy.getCurrentBranch()).toBe('A'); expect(parser.yy.getCurrentBranch()).toBe('merge/test_merge');
expect(parser.yy.getDirection()).toBe('LR'); expect(parser.yy.getDirection()).toBe('LR');
expect(Object.keys(parser.yy.getBranches()).length).toBe(7); expect(Object.keys(parser.yy.getBranches()).length).toBe(6);
expect(Object.keys(parser.yy.getBranches())).toEqual( expect(Object.keys(parser.yy.getBranches())).toEqual(
expect.arrayContaining([ expect.arrayContaining([
'branch01', 'branch01',
@@ -389,7 +387,6 @@ describe('when parsing a gitGraph', function () {
'cherry-pick03', 'cherry-pick03',
'branch/example-branch', 'branch/example-branch',
'merge/test_merge', 'merge/test_merge',
'A',
]) ])
); );
}); });

View File

@@ -5,6 +5,7 @@ import { getConfig } from '../../config';
import addSVGAccessibilityFields from '../../accessibility'; import addSVGAccessibilityFields from '../../accessibility';
let allCommitsDict = {}; let allCommitsDict = {};
let branchNum;
const commitType = { const commitType = {
NORMAL: 0, NORMAL: 0,
@@ -82,7 +83,7 @@ const drawCommits = (svg, commits, modifyGraph) => {
const sortedKeys = keys.sort((a, b) => { const sortedKeys = keys.sort((a, b) => {
return commits[a].seq - commits[b].seq; return commits[a].seq - commits[b].seq;
}); });
sortedKeys.forEach((key) => { sortedKeys.forEach((key, index) => {
const commit = commits[key]; const commit = commits[key];
const y = branchPos[commit.branch].pos; const y = branchPos[commit.branch].pos;
@@ -91,9 +92,7 @@ const drawCommits = (svg, commits, modifyGraph) => {
if (modifyGraph) { if (modifyGraph) {
let typeClass; let typeClass;
let commitSymbolType = let commitSymbolType =
typeof commit.customType !== 'undefined' && commit.customType !== '' typeof commit.customType !== 'undefined' ? commit.customType : commit.type;
? commit.customType
: commit.type;
switch (commitSymbolType) { switch (commitSymbolType) {
case commitType.NORMAL: case commitType.NORMAL:
typeClass = 'commit-normal'; typeClass = 'commit-normal';
@@ -291,15 +290,18 @@ const drawCommits = (svg, commits, modifyGraph) => {
}; };
/** /**
* Detect if there are other commits between commit1's x-position and commit2's x-position on the * Detect if there are other commits between commit1's x-position and commit2's x-position on the same
* same branch as commit2. * branch as commit2.
* *
* @param {any} commit1 * @param {any} commit1
* @param {any} commit2 * @param {any} commit2
* @param allCommits * @param allCommits
* @returns {boolean} If there are commits between commit1's x-position and commit2's x-position * @returns {boolean} if there are commits between commit1's x-position and commit2's x-position
*/ */
const hasOverlappingCommits = (commit1, commit2, allCommits) => { const hasOverlappingCommits = (commit1, commit2, allCommits) => {
const commit1Pos = commitPos[commit2.id];
const commit2Pos = commitPos[commit1.id];
// Find commits on the same branch as commit2 // Find commits on the same branch as commit2
const keys = Object.keys(allCommits); const keys = Object.keys(allCommits);
const overlappingComits = keys.filter((key) => { const overlappingComits = keys.filter((key) => {
@@ -320,7 +322,7 @@ const hasOverlappingCommits = (commit1, commit2, allCommits) => {
* @param {any} y1 * @param {any} y1
* @param {any} y2 * @param {any} y2
* @param {any} _depth * @param {any} _depth
* @returns {number} Y value between y1 and y2 * @returns {number} y value between y1 and y2
*/ */
const findLane = (y1, y2, _depth) => { const findLane = (y1, y2, _depth) => {
const depth = _depth || 0; const depth = _depth || 0;
@@ -353,11 +355,25 @@ const findLane = (y1, y2, _depth) => {
* @param {any} allCommits * @param {any} allCommits
*/ */
const drawArrow = (svg, commit1, commit2, allCommits) => { const drawArrow = (svg, commit1, commit2, allCommits) => {
const conf = getConfig();
const p1 = commitPos[commit1.id]; const p1 = commitPos[commit1.id];
const p2 = commitPos[commit2.id]; const p2 = commitPos[commit2.id];
const overlappingCommits = hasOverlappingCommits(commit1, commit2, allCommits); const overlappingCommits = hasOverlappingCommits(commit1, commit2, allCommits);
// log.debug('drawArrow', p1, p2, overlappingCommits, commit1.id, commit2.id); // log.debug('drawArrow', p1, p2, overlappingCommits, commit1.id, commit2.id);
let url = '';
if (conf.arrowMarkerAbsolute) {
url =
window.location.protocol +
'//' +
window.location.host +
window.location.pathname +
window.location.search;
url = url.replace(/\(/g, '\\(');
url = url.replace(/\)/g, '\\)');
}
let arc = ''; let arc = '';
let arc2 = ''; let arc2 = '';
let radius = 0; let radius = 0;
@@ -415,7 +431,7 @@ const drawArrow = (svg, commit1, commit2, allCommits) => {
} ${p2.y}`; } ${p2.y}`;
} }
} }
svg const arrow = svg
.append('path') .append('path')
.attr('d', lineDef) .attr('d', lineDef)
.attr('class', 'arrow arrow' + (colorClassNum % THEME_COLOR_LIMIT)); .attr('class', 'arrow arrow' + (colorClassNum % THEME_COLOR_LIMIT));
@@ -423,7 +439,10 @@ const drawArrow = (svg, commit1, commit2, allCommits) => {
const drawArrows = (svg, commits) => { const drawArrows = (svg, commits) => {
const gArrows = svg.append('g').attr('class', 'commit-arrows'); const gArrows = svg.append('g').attr('class', 'commit-arrows');
Object.keys(commits).forEach((key) => { let pos = 0;
const k = Object.keys(commits);
k.forEach((key, index) => {
const commit = commits[key]; const commit = commits[key];
if (commit.parents && commit.parents.length > 0) { if (commit.parents && commit.parents.length > 0) {
commit.parents.forEach((parent) => { commit.parents.forEach((parent) => {

View File

@@ -61,7 +61,7 @@ checkout(?=\s|$) return 'CHECKOUT';
<string>["] this.popState(); <string>["] this.popState();
<string>[^"]* return 'STR'; <string>[^"]* return 'STR';
[0-9]+(?=\s|$) return 'NUM'; [0-9]+(?=\s|$) return 'NUM';
\w([-\./\w]*[-\w])? return 'ID'; // only a subset of https://git-scm.com/docs/git-check-ref-format \w[-\./\w]*[-\w] return 'ID'; // only a subset of https://git-scm.com/docs/git-check-ref-format
<<EOF>> return 'EOF'; <<EOF>> return 'EOF';
\s+ /* skip all whitespace */ // lowest priority so we can use lookaheads in earlier regex \s+ /* skip all whitespace */ // lowest priority so we can use lookaheads in earlier regex

View File

@@ -27,6 +27,7 @@ export const draw = (text, id, version, diagObj) => {
securityLevel === 'sandbox' securityLevel === 'sandbox'
? select(sandboxElement.nodes()[0].contentDocument.body) ? select(sandboxElement.nodes()[0].contentDocument.body)
: select('body'); : select('body');
const doc = securityLevel === 'sandbox' ? sandboxElement.nodes()[0].contentDocument : document;
// Parse the graph definition // Parse the graph definition
// parser.parse(text); // parser.parse(text);

View File

@@ -2,7 +2,7 @@
import { select } from 'd3'; import { select } from 'd3';
import { log, getConfig, setupGraphViewbox } from '../../diagram-api/diagramAPI'; import { log, getConfig, setupGraphViewbox } from '../../diagram-api/diagramAPI';
import svgDraw from './svgDraw'; import svgDraw from './svgDraw';
import { BoundingBox, Layout } from 'non-layered-tidy-tree-layout'; import { BoundingBox, Layout, Tree } from 'non-layered-tidy-tree-layout';
import clone from 'fast-clone'; import clone from 'fast-clone';
import * as db from './mindmapDb'; import * as db from './mindmapDb';
@@ -85,8 +85,9 @@ function rightToLeft(mindmap) {
/** /**
* @param mindmap * @param mindmap
* @param dir * @param dir
* @param conf
*/ */
function layout(mindmap, dir) { function layout(mindmap, dir, conf) {
const bb = new BoundingBox(30, 60); const bb = new BoundingBox(30, 60);
const layout = new Layout(bb); const layout = new Layout(bb);
@@ -191,7 +192,8 @@ function layoutMindmap(node, conf) {
}); });
// Merge the trees into a single tree // Merge the trees into a single tree
mergeTrees(node, trees); const result = mergeTrees(node, trees);
eachNode;
return node; return node;
} }
/** /**
@@ -230,11 +232,13 @@ export const draw = (text, id, version, diagObj) => {
securityLevel === 'sandbox' securityLevel === 'sandbox'
? select(sandboxElement.nodes()[0].contentDocument.body) ? select(sandboxElement.nodes()[0].contentDocument.body)
: select('body'); : select('body');
const doc = securityLevel === 'sandbox' ? sandboxElement.nodes()[0].contentDocument : document;
// Parse the graph definition // Parse the graph definition
const svg = root.select('#' + id); const svg = root.select('#' + id);
svg.append('g'); const g = svg.append('g');
const mm = diagObj.db.getMindmap(); const mm = diagObj.db.getMindmap();
// Draw the graph and start with drawing the nodes without proper position // Draw the graph and start with drawing the nodes without proper position

View File

@@ -1,4 +1,4 @@
import { darken, lighten, isDark } from 'khroma'; import { darken, lighten, adjust, invert, isDark } from 'khroma';
const genSections = (options) => { const genSections = (options) => {
let sections = ''; let sections = '';

View File

@@ -47,9 +47,9 @@ function wrap(text, width) {
}); });
} }
const defaultBkg = function (elem, node, section) { const defaultBkg = function (elem, node, section, conf) {
const rd = 5; const rd = 5;
elem const r = elem
.append('path') .append('path')
.attr('id', 'node-' + node.id) .attr('id', 'node-' + node.id)
.attr('class', 'node-bkg node-' + db.type2Str(node.type)) .attr('class', 'node-bkg node-' + db.type2Str(node.type))
@@ -68,22 +68,25 @@ const defaultBkg = function (elem, node, section) {
.attr('x2', node.width) .attr('x2', node.width)
.attr('y2', node.height); .attr('y2', node.height);
}; };
const rectBkg = function (elem, node) { const rectBkg = function (elem, node, section, conf) {
elem const r = elem
.append('rect') .append('rect')
.attr('id', 'node-' + node.id) .attr('id', 'node-' + node.id)
.attr('class', 'node-bkg node-' + db.type2Str(node.type)) .attr('class', 'node-bkg node-' + db.type2Str(node.type))
.attr('height', node.height) .attr('height', node.height)
.attr('width', node.width); .attr('width', node.width);
}; };
const cloudBkg = function (elem, node) { const cloudBkg = function (elem, node, section, conf) {
const rd = 5;
const r = elem;
const w = node.width; const w = node.width;
const h = node.height; const h = node.height;
const r0 = 0.1 * w;
const r1 = 0.15 * w; const r1 = 0.15 * w;
const r2 = 0.25 * w; const r2 = 0.25 * w;
const r3 = 0.35 * w; const r3 = 0.35 * w;
const r4 = 0.2 * w; const r4 = 0.2 * w;
elem const p = elem
.append('path') .append('path')
.attr('id', 'node-' + node.id) .attr('id', 'node-' + node.id)
.attr('class', 'node-bkg node-' + db.type2Str(node.type)) .attr('class', 'node-bkg node-' + db.type2Str(node.type))
@@ -106,11 +109,12 @@ const cloudBkg = function (elem, node) {
H0 V0 Z` H0 V0 Z`
); );
}; };
const bangBkg = function (elem, node) { const bangBkg = function (elem, node, section, conf) {
const rd = 5;
const w = node.width; const w = node.width;
const h = node.height; const h = node.height;
const r = 0.15 * w; const r = 0.15 * w;
elem const p = elem
.append('path') .append('path')
.attr('id', 'node-' + node.id) .attr('id', 'node-' + node.id)
.attr('class', 'node-bkg node-' + db.type2Str(node.type)) .attr('class', 'node-bkg node-' + db.type2Str(node.type))
@@ -137,15 +141,16 @@ const bangBkg = function (elem, node) {
H0 V0 Z` H0 V0 Z`
); );
}; };
const circleBkg = function (elem, node) { const circleBkg = function (elem, node, section, conf) {
elem const r = elem
.append('circle') .append('circle')
.attr('id', 'node-' + node.id) .attr('id', 'node-' + node.id)
.attr('class', 'node-bkg node-' + db.type2Str(node.type)) .attr('class', 'node-bkg node-' + db.type2Str(node.type))
.attr('r', node.width / 2); .attr('r', node.width / 2);
// .attr('width', node.width);
}; };
const roundedRectBkg = function (elem, node) { const roundedRectBkg = function (elem, node, section, conf) {
elem const r = elem
.append('rect') .append('rect')
.attr('id', 'node-' + node.id) .attr('id', 'node-' + node.id)
.attr('class', 'node-bkg node-' + db.type2Str(node.type)) .attr('class', 'node-bkg node-' + db.type2Str(node.type))
@@ -178,6 +183,7 @@ export const drawNode = function (elem, node, section, conf) {
.append('text') .append('text')
.text(node.descr) .text(node.descr)
.attr('dy', '1em') .attr('dy', '1em')
// .attr('dy', '0')
.attr('alignment-baseline', 'middle') .attr('alignment-baseline', 'middle')
.attr('dominant-baseline', 'middle') .attr('dominant-baseline', 'middle')
.attr('text-anchor', 'middle') .attr('text-anchor', 'middle')
@@ -189,12 +195,18 @@ export const drawNode = function (elem, node, section, conf) {
if (node.icon) { if (node.icon) {
if (node.type === db.nodeType.CIRCLE) { if (node.type === db.nodeType.CIRCLE) {
node.height += 50; node.height += 50;
const orgWidth = node.width;
node.width += 50; node.width += 50;
// node.width = Math.max(orgWidth, 100);
const widthDiff = Math.abs(node.width - orgWidth);
const icon = nodeElem const icon = nodeElem
.append('foreignObject') .append('foreignObject')
.attr('height', '50px') .attr('height', '50px')
.attr('width', node.width) .attr('width', node.width)
.attr('style', 'text-align: center;'); .attr('style', 'text-align: center;');
// .attr('x', 0)
// .attr('y', 0)
// .attr('class', 'node-icon ' + node.icon);
icon icon
.append('div') .append('div')
.attr('class', 'icon-container') .attr('class', 'icon-container')
@@ -214,7 +226,9 @@ export const drawNode = function (elem, node, section, conf) {
.attr('width', '60px') .attr('width', '60px')
.attr('height', node.height) .attr('height', node.height)
.attr('style', 'text-align: center;margin-top:' + heightDiff / 2 + 'px;'); .attr('style', 'text-align: center;margin-top:' + heightDiff / 2 + 'px;');
// .attr('x', 0)
// .attr('y', 0)
// .attr('class', 'node-icon ' + node.icon);
icon icon
.append('div') .append('div')
.attr('class', 'icon-container') .attr('class', 'icon-container')
@@ -244,11 +258,15 @@ export const drawNode = function (elem, node, section, conf) {
circleBkg(bkgElem, node, section, conf); circleBkg(bkgElem, node, section, conf);
break; break;
case db.nodeType.CLOUD: case db.nodeType.CLOUD:
// bkgElem.attr('transform', 'translate(' + node.width / 2 + ', ' + +node.height / 2 + ')');
cloudBkg(bkgElem, node, section, conf); cloudBkg(bkgElem, node, section, conf);
break; break;
case db.nodeType.BANG: case db.nodeType.BANG:
// bkgElem.attr('transform', 'translate(' + node.width / 2 + ', ' + +node.height / 2 + ')');
bangBkg(bkgElem, node, section, conf); bangBkg(bkgElem, node, section, conf);
break; break;
default:
// defaultBkg(bkgElem, node, section, conf);
} }
// Position the node to its coordinate // Position the node to its coordinate
@@ -259,7 +277,17 @@ export const drawNode = function (elem, node, section, conf) {
return node.height; return node.height;
}; };
export const drawEdge = function drawEdge(edgesElem, mindmap, parent, depth, section) { export const drawEdge = function drawEdge(edgesElem, mindmap, parent, depth, section, conf) {
// edgesElem
// .append('line')
// .attr('x1', parent.x + parent.width / 2)
// .attr('y1', parent.y + parent.height / 2)
// .attr('x2', mindmap.x + mindmap.width / 2)
// .attr('y2', mindmap.y + mindmap.height / 2)
// .attr('class', 'edge section-edge-' + section + ' edge-depth-' + depth);
//<path d="M100,250 Q250,100 400,250 T700,250" />
const sx = parent.x + parent.width / 2; const sx = parent.x + parent.width / 2;
const sy = parent.y + parent.height / 2; const sy = parent.y + parent.height / 2;
const ex = mindmap.x + mindmap.width / 2; const ex = mindmap.x + mindmap.width / 2;
@@ -280,7 +308,7 @@ export const drawEdge = function drawEdge(edgesElem, mindmap, parent, depth, sec
.attr('class', 'edge section-edge-' + section + ' edge-depth-' + depth); .attr('class', 'edge section-edge-' + section + ' edge-depth-' + depth);
}; };
export const positionNode = function (node) { export const positionNode = function (node, conf) {
const nodeElem = db.getElementById(node.id); const nodeElem = db.getElementById(node.id);
const x = node.x || 0; const x = node.x || 0;

View File

@@ -13,6 +13,8 @@ import {
} from '../../commonDb'; } from '../../commonDb';
let sections = {}; let sections = {};
let title = '';
let description = '';
let showData = false; let showData = false;
export const parseDirective = function (statement, context, type) { export const parseDirective = function (statement, context, type) {
@@ -47,6 +49,7 @@ const cleanupValue = function (value) {
const clear = function () { const clear = function () {
sections = {}; sections = {};
title = '';
showData = false; showData = false;
commonClear(); commonClear();
}; };

View File

@@ -1,7 +1,7 @@
import * as configApi from '../../config'; import * as configApi from '../../config';
import { log } from '../../logger'; import { log } from '../../logger';
import mermaidAPI from '../../mermaidAPI'; import mermaidAPI from '../../mermaidAPI';
import common from '../common/common';
import { import {
setAccTitle, setAccTitle,
getAccTitle, getAccTitle,
@@ -15,6 +15,10 @@ let latestRequirement = {};
let requirements = {}; let requirements = {};
let latestElement = {}; let latestElement = {};
let elements = {}; let elements = {};
let title = '';
let accDescription = '';
const sanitizeText = (txt) => common.sanitizeText(txt, configApi.getConfig());
const RequirementType = { const RequirementType = {
REQUIREMENT: 'Requirement', REQUIREMENT: 'Requirement',

View File

@@ -320,6 +320,7 @@ export const draw = (text, id, _version, diagObj) => {
securityLevel === 'sandbox' securityLevel === 'sandbox'
? select(sandboxElement.nodes()[0].contentDocument.body) ? select(sandboxElement.nodes()[0].contentDocument.body)
: select('body'); : select('body');
const doc = securityLevel === 'sandbox' ? sandboxElement.nodes()[0].contentDocument : document;
const svg = root.select(`[id='${id}']`); const svg = root.select(`[id='${id}']`);
markers.insertLineEndings(svg, conf); markers.insertLineEndings(svg, conf);

View File

@@ -16,6 +16,8 @@ let prevActor = undefined;
let actors = {}; let actors = {};
let messages = []; let messages = [];
const notes = []; const notes = [];
let diagramTitle = '';
let description = '';
let sequenceNumbersEnabled = false; let sequenceNumbersEnabled = false;
let wrapEnabled; let wrapEnabled;
@@ -151,6 +153,7 @@ export const clear = function () {
actors = {}; actors = {};
messages = []; messages = [];
sequenceNumbersEnabled = false; sequenceNumbersEnabled = false;
diagramTitle = '';
commonClear(); commonClear();
}; };

View File

@@ -11,6 +11,8 @@ import {
clear as commonClear, clear as commonClear,
} from '../../commonDb'; } from '../../commonDb';
const sanitizeText = (txt) => common.sanitizeText(txt, configApi.getConfig());
const clone = (o) => JSON.parse(JSON.stringify(o)); const clone = (o) => JSON.parse(JSON.stringify(o));
let rootDoc = []; let rootDoc = [];
@@ -119,6 +121,10 @@ let documents = {
let currentDocument = documents.root; let currentDocument = documents.root;
let startCnt = 0; let startCnt = 0;
let endCnt = 0; // let stateCnt = 0;
let title = 'State diagram';
let description = '';
/** /**
* Function called by parser when a node definition has been found. * Function called by parser when a node definition has been found.
@@ -173,6 +179,7 @@ export const clear = function (saveCommon) {
currentDocument = documents.root; currentDocument = documents.root;
startCnt = 0; startCnt = 0;
endCnt = 0;
classes = []; classes = [];
if (!saveCommon) { if (!saveCommon) {
commonClear(); commonClear();
@@ -204,6 +211,7 @@ export const addRelation = function (_id1, _id2, title) {
type1 = 'start'; type1 = 'start';
} }
if (_id2 === '[*]') { if (_id2 === '[*]') {
endCnt++;
id2 = 'end' + startCnt; id2 = 'end' + startCnt;
type2 = 'end'; type2 = 'end';
} }

View File

@@ -283,6 +283,7 @@ export const draw = function (text, id, _version, diag) {
securityLevel === 'sandbox' securityLevel === 'sandbox'
? select(sandboxElement.nodes()[0].contentDocument.body) ? select(sandboxElement.nodes()[0].contentDocument.body)
: select('body'); : select('body');
const doc = securityLevel === 'sandbox' ? sandboxElement.nodes()[0].contentDocument : document;
const svg = root.select(`[id="${id}"]`); const svg = root.select(`[id="${id}"]`);
// Run the renderer. This is what draws the final graph. // Run the renderer. This is what draws the final graph.

View File

@@ -1,5 +1,6 @@
import mermaidAPI from '../../mermaidAPI'; import mermaidAPI from '../../mermaidAPI';
import * as configApi from '../../config'; import * as configApi from '../../config';
import common from '../common/common';
import { import {
setAccTitle, setAccTitle,
getAccTitle, getAccTitle,
@@ -10,6 +11,10 @@ import {
clear as commonClear, clear as commonClear,
} from '../../commonDb'; } from '../../commonDb';
const sanitizeText = (txt) => common.sanitizeText(txt, configApi.getConfig());
let title = '';
let description = '';
let currentSection = ''; let currentSection = '';
const sections = []; const sections = [];
@@ -24,6 +29,8 @@ export const clear = function () {
sections.length = 0; sections.length = 0;
tasks.length = 0; tasks.length = 0;
currentSection = ''; currentSection = '';
title = '';
description = '';
rawTasks.length = 0; rawTasks.length = 0;
commonClear(); commonClear();
}; };

View File

@@ -1,7 +1,7 @@
/** Created by knut on 14-12-11. */ /** Created by knut on 14-12-11. */
import { select } from 'd3'; import { select } from 'd3';
import { log } from '../../logger'; import { log } from './logger';
import { getErrorMessage } from '../../utils'; import { getErrorMessage } from './utils';
let conf = {}; let conf = {};
@@ -17,11 +17,10 @@ export const setConf = function (cnf: any) {
/** /**
* Draws a an info picture in the tag with id: id based on the graph definition in text. * Draws a an info picture in the tag with id: id based on the graph definition in text.
* *
* @param text
* @param {string} id The text for the error * @param {string} id The text for the error
* @param {string} mermaidVersion The version * @param {string} mermaidVersion The version
*/ */
export const draw = (text: string, id: string, mermaidVersion: string) => { export const draw = (id: string, mermaidVersion: string) => {
try { try {
log.debug('Renering svg for syntax error\n'); log.debug('Renering svg for syntax error\n');
@@ -73,22 +72,22 @@ export const draw = (text: string, id: string, mermaidVersion: string) => {
g.append('text') // text label for the x axis g.append('text') // text label for the x axis
.attr('class', 'error-text') .attr('class', 'error-text')
.attr('x', 1440) .attr('x', 1240)
.attr('y', 250) .attr('y', 250)
.attr('font-size', '150px') .attr('font-size', '150px')
.style('text-anchor', 'middle') .style('text-anchor', 'middle')
.text('Syntax error in graph'); .text('Syntax error in graph');
g.append('text') // text label for the x axis g.append('text') // text label for the x axis
.attr('class', 'error-text') .attr('class', 'error-text')
.attr('x', 1250) .attr('x', 1050)
.attr('y', 400) .attr('y', 400)
.attr('font-size', '100px') .attr('font-size', '100px')
.style('text-anchor', 'middle') .style('text-anchor', 'middle')
.text('mermaid version ' + mermaidVersion); .text('mermaid version ' + mermaidVersion);
svg.attr('height', 100); svg.attr('height', 100);
svg.attr('width', 500); svg.attr('width', 400);
svg.attr('viewBox', '768 0 912 512'); svg.attr('viewBox', '768 0 512 512');
} catch (e) { } catch (e) {
log.error('Error while rendering info diagram'); log.error('Error while rendering info diagram');
log.error(getErrorMessage(e)); log.error(getErrorMessage(e));

View File

@@ -95,11 +95,9 @@ const initThrowsErrors = function (
const idGenerator = new utils.initIdGenerator(conf.deterministicIds, conf.deterministicIDSeed); const idGenerator = new utils.initIdGenerator(conf.deterministicIds, conf.deterministicIDSeed);
let txt; let txt;
const errors = [];
// element is the current div with mermaid class // element is the current div with mermaid class
for (const element of Array.from(nodesToProcess)) { for (const element of Array.from(nodesToProcess)) {
log.info('Rendering diagram: ' + element.id);
/*! Check if previously processed */ /*! Check if previously processed */
if (element.getAttribute('data-processed')) { if (element.getAttribute('data-processed')) {
continue; continue;
@@ -137,16 +135,9 @@ const initThrowsErrors = function (
} catch (error) { } catch (error) {
log.warn('Catching Error (bootstrap)', error); log.warn('Catching Error (bootstrap)', error);
// @ts-ignore: TODO Fix ts errors // @ts-ignore: TODO Fix ts errors
const mermaidError = { error, str: error.str, hash: error.hash, message: error.str };
if (typeof mermaid.parseError === 'function') {
mermaid.parseError(mermaidError);
}
errors.push(mermaidError);
}
}
if (errors.length > 0) {
// TODO: We should be throwing an error object. // TODO: We should be throwing an error object.
throw errors[0]; throw { error, message: error.str };
}
} }
}; };

View File

@@ -26,7 +26,7 @@ import flowDb from './diagrams/flowchart/flowDb';
import flowRenderer from './diagrams/flowchart/flowRenderer'; import flowRenderer from './diagrams/flowchart/flowRenderer';
import ganttDb from './diagrams/gantt/ganttDb'; import ganttDb from './diagrams/gantt/ganttDb';
import Diagram from './Diagram'; import Diagram from './Diagram';
import errorRenderer from './diagrams/error/errorRenderer'; import errorRenderer from './errorRenderer';
import { attachFunctions } from './interactionDb'; import { attachFunctions } from './interactionDb';
import { log, setLogLevel } from './logger'; import { log, setLogLevel } from './logger';
import getStyles from './styles'; import getStyles from './styles';
@@ -118,16 +118,12 @@ export const decodeEntities = function (text: string): string {
* element will be removed when rendering is completed. * element will be removed when rendering is completed.
* @returns {void} * @returns {void}
*/ */
const render = function ( const render = async function (
id: string, id: string,
text: string, text: string,
cb: (svgCode: string, bindFunctions?: (element: Element) => void) => void, cb: (svgCode: string, bindFunctions?: (element: Element) => void) => void,
container?: Element container?: Element
): void { ): Promise<void> {
if (!hasLoadedDiagrams) {
addDiagrams();
hasLoadedDiagrams = true;
}
configApi.reset(); configApi.reset();
text = text.replace(/\r\n?/g, '\n'); // parser problems on CRLF ignore all CR and leave LF;; text = text.replace(/\r\n?/g, '\n'); // parser problems on CRLF ignore all CR and leave LF;;
const graphInit = utils.detectInit(text); const graphInit = utils.detectInit(text);
@@ -232,14 +228,7 @@ const render = function (
text = encodeEntities(text); text = encodeEntities(text);
// Important that we do not create the diagram until after the directives have been included // Important that we do not create the diagram until after the directives have been included
let diag; const diag = new Diagram(text);
let parseEncounteredException;
try {
diag = new Diagram(text);
} catch (error) {
diag = new Diagram('error');
parseEncounteredException = error;
}
// Get the tmp element containing the the svg // Get the tmp element containing the the svg
const element = root.select('#d' + id).node(); const element = root.select('#d' + id).node();
const graphType = diag.type; const graphType = diag.type;
@@ -310,9 +299,9 @@ const render = function (
svg.insertBefore(style1, firstChild); svg.insertBefore(style1, firstChild);
try { try {
diag.renderer.draw(text, id, pkg.version, diag); await diag.renderer.draw(text, id, pkg.version, diag);
} catch (e) { } catch (e) {
errorRenderer.draw(text, id, pkg.version); errorRenderer.draw(id, pkg.version);
throw e; throw e;
} }
@@ -382,10 +371,6 @@ const render = function (
node.remove(); node.remove();
} }
if (parseEncounteredException) {
throw parseEncounteredException;
}
return svgCode; return svgCode;
}; };

View File

@@ -1,6 +1,5 @@
import classDiagram from './diagrams/class/styles'; import classDiagram from './diagrams/class/styles';
import er from './diagrams/er/styles'; import er from './diagrams/er/styles';
import error from './diagrams/error/styles';
import flowchart from './diagrams/flowchart/styles'; import flowchart from './diagrams/flowchart/styles';
import gantt from './diagrams/gantt/styles'; import gantt from './diagrams/gantt/styles';
// import gitGraph from './diagrams/git/styles'; // import gitGraph from './diagrams/git/styles';
@@ -29,7 +28,6 @@ const themes: Record<string, any> = {
info, info,
pie, pie,
er, er,
error,
journey, journey,
requirement, requirement,
c4, c4,

View File

@@ -39,10 +39,12 @@ const directive =
/[%]{2}[{]\s*(?:(?:(\w+)\s*:|(\w+))\s*(?:(?:(\w+))|((?:(?![}][%]{2}).|\r?\n)*))?\s*)(?:[}][%]{2})?/gi; /[%]{2}[{]\s*(?:(?:(\w+)\s*:|(\w+))\s*(?:(?:(\w+))|((?:(?![}][%]{2}).|\r?\n)*))?\s*)(?:[}][%]{2})?/gi;
const directiveWithoutOpen = const directiveWithoutOpen =
/\s*(?:(?:(\w+)(?=:):|(\w+))\s*(?:(?:(\w+))|((?:(?![}][%]{2}).|\r?\n)*))?\s*)(?:[}][%]{2})?/gi; /\s*(?:(?:(\w+)(?=:):|(\w+))\s*(?:(?:(\w+))|((?:(?![}][%]{2}).|\r?\n)*))?\s*)(?:[}][%]{2})?/gi;
const anyComment = /\s*%%.*\n/gm;
/** /**
* @function detectInit Detects the init config object from the text * @function detectInit Detects the init config object from the text
* @param config * @param config
* @param config
* *
* ```mermaid * ```mermaid
* *
@@ -71,7 +73,7 @@ const directiveWithoutOpen =
* g-->h * g-->h
* ``` * ```
* @param {string} text The text defining the graph * @param {string} text The text defining the graph
* @param {any} config * @param {any} cnf
* @returns {object} The json object representing the init passed to mermaid.initialize() * @returns {object} The json object representing the init passed to mermaid.initialize()
*/ */
export const detectInit = function (text: string, config?: MermaidConfig): MermaidConfig { export const detectInit = function (text: string, config?: MermaidConfig): MermaidConfig {
@@ -327,6 +329,7 @@ const calcLabelPosition = (points) => {
const calcCardinalityPosition = (isRelationTypePresent, points, initialPosition) => { const calcCardinalityPosition = (isRelationTypePresent, points, initialPosition) => {
let prevPoint; let prevPoint;
let totalDistance = 0;
log.info('our points', points); log.info('our points', points);
if (points[0] !== initialPosition) { if (points[0] !== initialPosition) {
points = points.reverse(); points = points.reverse();
@@ -386,12 +389,14 @@ const calcTerminalLabelPosition = (terminalMarkerSize, position, _points) => {
// Todo looking to faster cloning method // Todo looking to faster cloning method
let points = JSON.parse(JSON.stringify(_points)); let points = JSON.parse(JSON.stringify(_points));
let prevPoint; let prevPoint;
let totalDistance = 0;
log.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();
} }
points.forEach((point) => { points.forEach((point) => {
totalDistance += distance(point, prevPoint);
prevPoint = point; prevPoint = point;
}); });
@@ -723,6 +728,19 @@ export const calculateTextDimensions = memoize(
(text, config) => `${text}-${config.fontSize}-${config.fontWeight}-${config.fontFamily}` (text, config) => `${text}-${config.fontSize}-${config.fontWeight}-${config.fontFamily}`
); );
/**
* Applys d3 attributes
*
* @param {any} d3Elem D3 Element to apply the attributes onto
* @param {[string, string][]} attrs Object.keys equivalent format of key to value mapping of
* attributes
*/
const d3Attrs = function (d3Elem, attrs) {
for (const attr of attrs) {
d3Elem.attr(attr[0], attr[1]);
}
};
export const initIdGenerator = class iterator { export const initIdGenerator = class iterator {
constructor(deterministic, seed) { constructor(deterministic, seed) {
this.deterministic = deterministic; this.deterministic = deterministic;
@@ -745,7 +763,7 @@ let decoder;
* Decodes HTML, source: {@link https://github.com/shrpne/entity-decode/blob/v2.0.1/browser.js} * Decodes HTML, source: {@link https://github.com/shrpne/entity-decode/blob/v2.0.1/browser.js}
* *
* @param {string} html HTML as a string * @param {string} html HTML as a string
* @returns {string} Unescaped HTML * @returns Unescaped HTML
*/ */
export const entityDecode = function (html) { export const entityDecode = function (html) {
decoder = decoder || document.createElement('div'); decoder = decoder || document.createElement('div');

View File

@@ -4710,6 +4710,14 @@ cypress@9.7.0:
untildify "^4.0.0" untildify "^4.0.0"
yauzl "^2.10.0" yauzl "^2.10.0"
cytoscape@^3.23.0:
version "3.23.0"
resolved "https://registry.yarnpkg.com/cytoscape/-/cytoscape-3.23.0.tgz#054ee05a6d0aa3b4f139382bbf2f4e5226df3c6d"
integrity sha512-gRZqJj/1kiAVPkrVFvz/GccxsXhF3Qwpptl32gKKypO4IlqnKBjTOu+HbXtEggSGzC5KCaHp3/F7GgENrtsFkA==
dependencies:
heap "^0.2.6"
lodash "^4.17.21"
"d3-array@2 - 3", "d3-array@2.10.0 - 3", "d3-array@2.5.0 - 3", d3-array@3: "d3-array@2 - 3", "d3-array@2.10.0 - 3", "d3-array@2.5.0 - 3", d3-array@3:
version "3.1.1" version "3.1.1"
resolved "https://registry.yarnpkg.com/d3-array/-/d3-array-3.1.1.tgz#7797eb53ead6b9083c75a45a681e93fc41bc468c" resolved "https://registry.yarnpkg.com/d3-array/-/d3-array-3.1.1.tgz#7797eb53ead6b9083c75a45a681e93fc41bc468c"
@@ -5370,10 +5378,10 @@ domhandler@^5.0.1, domhandler@^5.0.2:
dependencies: dependencies:
domelementtype "^2.3.0" domelementtype "^2.3.0"
dompurify@2.4.0: dompurify@2.3.10:
version "2.4.0" version "2.3.10"
resolved "https://registry.yarnpkg.com/dompurify/-/dompurify-2.4.0.tgz#c9c88390f024c2823332615c9e20a453cf3825dd" resolved "https://registry.yarnpkg.com/dompurify/-/dompurify-2.3.10.tgz#901f7390ffe16a91a5a556b94043314cd4850385"
integrity sha512-Be9tbQMZds4a3C6xTmz68NlMfeONA//4dOavl/1rNw50E+/QO0KVpbcU0PcaW0nsQxurXls9ZocqFxk8R2mWEA== integrity sha512-o7Fg/AgC7p/XpKjf/+RC3Ok6k4St5F7Q6q6+Nnm3p2zGWioAY6dh0CbbuwOhH2UcSzKsdniE/YnE2/92JcsA+g==
domutils@^3.0.1: domutils@^3.0.1:
version "3.0.1" version "3.0.1"
@@ -6775,6 +6783,11 @@ he@^1.1.0:
resolved "https://registry.yarnpkg.com/he/-/he-1.2.0.tgz#84ae65fa7eafb165fddb61566ae14baf05664f0f" resolved "https://registry.yarnpkg.com/he/-/he-1.2.0.tgz#84ae65fa7eafb165fddb61566ae14baf05664f0f"
integrity sha512-F/1DnUGPopORZi0ni+CvrCgHQ5FyEAHRLSApuYWMmrbSwoN2Mn/7k+Gl38gJnR7yyDZk6WLXwiGod1JOWNDKGw== integrity sha512-F/1DnUGPopORZi0ni+CvrCgHQ5FyEAHRLSApuYWMmrbSwoN2Mn/7k+Gl38gJnR7yyDZk6WLXwiGod1JOWNDKGw==
heap@^0.2.6:
version "0.2.7"
resolved "https://registry.yarnpkg.com/heap/-/heap-0.2.7.tgz#1e6adf711d3f27ce35a81fe3b7bd576c2260a8fc"
integrity sha512-2bsegYkkHO+h/9MGbn6KWcE45cHZgPANo5LXF7EvWdT0yT2EguSVO1nDgU5c8+ZOPwp2vMNa7YFsJhVcDR9Sdg==
highlight.js@^10.5.0: highlight.js@^10.5.0:
version "10.7.3" version "10.7.3"
resolved "https://registry.yarnpkg.com/highlight.js/-/highlight.js-10.7.3.tgz#697272e3991356e40c3cac566a74eef681756531" resolved "https://registry.yarnpkg.com/highlight.js/-/highlight.js-10.7.3.tgz#697272e3991356e40c3cac566a74eef681756531"
@@ -11270,10 +11283,10 @@ strip-json-comments@^3.1.0, strip-json-comments@^3.1.1:
resolved "https://registry.yarnpkg.com/strip-json-comments/-/strip-json-comments-3.1.1.tgz#31f1281b3832630434831c310c01cccda8cbe006" resolved "https://registry.yarnpkg.com/strip-json-comments/-/strip-json-comments-3.1.1.tgz#31f1281b3832630434831c310c01cccda8cbe006"
integrity sha512-6fPc+R4ihwqP6N/aIv2f1gMH8lOVtWQHoqC4yK6oSDVVocumAsfCqjkXnqiYMhmMwS/mEHLp7Vehlt3ql6lEig== integrity sha512-6fPc+R4ihwqP6N/aIv2f1gMH8lOVtWQHoqC4yK6oSDVVocumAsfCqjkXnqiYMhmMwS/mEHLp7Vehlt3ql6lEig==
stylis@^4.1.2: stylis@^4.0.10:
version "4.1.2" version "4.1.1"
resolved "https://registry.yarnpkg.com/stylis/-/stylis-4.1.2.tgz#870b3c1c2275f51b702bb3da9e94eedad87bba41" resolved "https://registry.yarnpkg.com/stylis/-/stylis-4.1.1.tgz#e46c6a9bbf7c58db1e65bb730be157311ae1fe12"
integrity sha512-Nn2CCrG2ZaFziDxaZPN43CXqn+j7tcdjPFCkRBkFue8QYXC2HdEwnw5TCBo4yQZ2WxKYeSi0fdoOrtEqgDrXbA== integrity sha512-lVrM/bNdhVX2OgBFNa2YJ9Lxj7kPzylieHd3TNjuGE0Re9JB7joL5VUKOVH1kdNNJTgGPpT8hmwIAPLaSyEVFQ==
subarg@^1.0.0: subarg@^1.0.0:
version "1.0.0" version "1.0.0"
@@ -12299,10 +12312,10 @@ webpack-dev-middleware@^5.3.1:
range-parser "^1.2.1" range-parser "^1.2.1"
schema-utils "^4.0.0" schema-utils "^4.0.0"
webpack-dev-server@^4.11.0: webpack-dev-server@^4.10.1:
version "4.11.0" version "4.10.1"
resolved "https://registry.yarnpkg.com/webpack-dev-server/-/webpack-dev-server-4.11.0.tgz#290ee594765cd8260adfe83b2d18115ea04484e7" resolved "https://registry.yarnpkg.com/webpack-dev-server/-/webpack-dev-server-4.10.1.tgz#124ac9ac261e75303d74d95ab6712b4aec3e12ed"
integrity sha512-L5S4Q2zT57SK7tazgzjMiSMBdsw+rGYIX27MgPgx7LDhWO0lViPrHKoLS7jo5In06PWYAhlYu3PbyoC6yAThbw== integrity sha512-FIzMq3jbBarz3ld9l7rbM7m6Rj1lOsgq/DyLGMX/fPEB1UBUPtf5iL/4eNfhx8YYJTRlzfv107UfWSWcBK5Odw==
dependencies: dependencies:
"@types/bonjour" "^3.5.9" "@types/bonjour" "^3.5.9"
"@types/connect-history-api-fallback" "^1.3.5" "@types/connect-history-api-fallback" "^1.3.5"