Merge from develop

This commit is contained in:
Ashish Jain
2024-08-21 16:25:58 +02:00
27 changed files with 1068 additions and 1017 deletions

View File

@@ -86,14 +86,20 @@
--- ---
config: config:
look: handDrawn look: handDrawn
flowchart: layout: elk
htmlLabels: false elk:
nodePlacementStrategy: BRANDES_KOEPF
--- ---
flowchart flowchart TB
A[I am a long text, where do I go??? handdrawn - false] %% A --> C
B -- sdf sdf --> C{"Evaluate"}
C --> n4["salkdfjh akljd lkasdjf lkashj lksjadf klasdh"]
C --> F
</pre </pre
> >
<pre id="diagram" class="mermaid"> <pre id="diagram" class="mermaid2">
--- ---
config: config:
look: handdrawn look: handdrawn
@@ -106,7 +112,7 @@ flowchart
> >
</div> </div>
<div class="flex"> <div class="flex">
<pre id="diagram" class="mermaid"> <pre id="diagram" class="mermaid2">
--- ---
config: config:
flowchart: flowchart:
@@ -116,7 +122,7 @@ flowchart
A[I am a long text, where do I go??? classic - false] A[I am a long text, where do I go??? classic - false]
</pre </pre
> >
<pre id="diagram" class="mermaid"> <pre id="diagram" class="mermaid2">
--- ---
config: config:
flowchart: flowchart:
@@ -159,8 +165,8 @@ flowchart LR
<script type="module"> <script type="module">
import mermaid from './mermaid.esm.mjs'; import mermaid from './mermaid.esm.mjs';
// import layouts from './mermaid-layout-elk.esm.mjs'; import layouts from './mermaid-layout-elk.esm.mjs';
// mermaid.registerLayoutLoaders(layouts); mermaid.registerLayoutLoaders(layouts);
mermaid.parseError = function (err, hash) { mermaid.parseError = function (err, hash) {
console.error('Mermaid error: ', err); console.error('Mermaid error: ', err);
}; };

View File

@@ -16,7 +16,7 @@
#### Defined in #### Defined in
[packages/mermaid/src/rendering-util/render.ts:11](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/rendering-util/render.ts#L11) [packages/mermaid/src/rendering-util/render.ts:25](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/rendering-util/render.ts#L25)
--- ---
@@ -26,7 +26,7 @@
#### Defined in #### Defined in
[packages/mermaid/src/rendering-util/render.ts:10](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/rendering-util/render.ts#L10) [packages/mermaid/src/rendering-util/render.ts:24](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/rendering-util/render.ts#L24)
--- ---
@@ -36,4 +36,4 @@
#### Defined in #### Defined in
[packages/mermaid/src/rendering-util/render.ts:9](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/rendering-util/render.ts#L9) [packages/mermaid/src/rendering-util/render.ts:23](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/rendering-util/render.ts#L23)

View File

@@ -28,7 +28,7 @@ page.
#### Defined in #### Defined in
[packages/mermaid/src/mermaid.ts:432](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/mermaid.ts#L432) [packages/mermaid/src/mermaid.ts:435](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/mermaid.ts#L435)
--- ---
@@ -59,7 +59,7 @@ A graph definition key
#### Defined in #### Defined in
[packages/mermaid/src/mermaid.ts:434](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/mermaid.ts#L434) [packages/mermaid/src/mermaid.ts:437](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/mermaid.ts#L437)
--- ---
@@ -89,7 +89,7 @@ Use [initialize](mermaid.Mermaid.md#initialize) and [run](mermaid.Mermaid.md#run
#### Defined in #### Defined in
[packages/mermaid/src/mermaid.ts:427](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/mermaid.ts#L427) [packages/mermaid/src/mermaid.ts:430](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/mermaid.ts#L430)
--- ---
@@ -116,50 +116,7 @@ This function should be called before the run function.
#### Defined in #### Defined in
[packages/mermaid/src/mermaid.ts:431](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/mermaid.ts#L431) [packages/mermaid/src/mermaid.ts:434](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/mermaid.ts#L434)
---
### internalHelpers
**internalHelpers**: `Object`
Internal helpers for mermaid
**`Deprecated`**
- This should not be used by external packages, as the definitions will change without notice.
#### Type declaration
| Name | Type |
| :--------------------------- | :-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `common` | { `evaluate`: (`val?`: `string` \| `boolean`) => `boolean` ; `getMax`: (...`values`: `number`\[]) => `number` ; `getMin`: (...`values`: `number`\[]) => `number` ; `getRows`: (`s?`: `string`) => `string`\[] ; `getUrl`: (`useAbsolute`: `boolean`) => `string` ; `hasBreaks`: (`text`: `string`) => `boolean` ; `lineBreakRegex`: `RegExp` ; `removeScript`: (`txt`: `string`) => `string` ; `sanitizeText`: (`text`: `string`, `config`: [`MermaidConfig`](mermaid.MermaidConfig.md)) => `string` ; `sanitizeTextOrArray`: (`a`: `string` \| `string`\[] \| `string`\[]\[], `config`: [`MermaidConfig`](mermaid.MermaidConfig.md)) => `string` \| `string`\[] ; `splitBreaks`: (`text`: `string`) => `string`\[] } |
| `common.evaluate` | (`val?`: `string` \| `boolean`) => `boolean` |
| `common.getMax` | (...`values`: `number`\[]) => `number` |
| `common.getMin` | (...`values`: `number`\[]) => `number` |
| `common.getRows` | (`s?`: `string`) => `string`\[] |
| `common.getUrl` | (`useAbsolute`: `boolean`) => `string` |
| `common.hasBreaks` | (`text`: `string`) => `boolean` |
| `common.lineBreakRegex` | `RegExp` |
| `common.removeScript` | (`txt`: `string`) => `string` |
| `common.sanitizeText` | (`text`: `string`, `config`: [`MermaidConfig`](mermaid.MermaidConfig.md)) => `string` |
| `common.sanitizeTextOrArray` | (`a`: `string` \| `string`\[] \| `string`\[]\[], `config`: [`MermaidConfig`](mermaid.MermaidConfig.md)) => `string` \| `string`\[] |
| `common.splitBreaks` | (`text`: `string`) => `string`\[] |
| `getConfig` | () => [`MermaidConfig`](mermaid.MermaidConfig.md) |
| `insertCluster` | (`elem`: `any`, `node`: `any`) => `Promise`<`any`> |
| `insertEdge` | (`elem`: `any`, `edge`: `any`, `clusterDb`: `any`, `diagramType`: `any`, `startNode`: `any`, `endNode`: `any`, `id`: `any`) => { `originalPath`: `any` ; `updatedPath`: `any` } |
| `insertEdgeLabel` | (`elem`: `any`, `edge`: `any`) => `Promise`<`any`> |
| `insertMarkers` | (`elem`: `any`, `markerArray`: `any`, `type`: `any`, `id`: `any`) => `void` |
| `insertNode` | (`elem`: `any`, `node`: `any`, `dir`: `any`) => `Promise`<`any`> |
| `interpolateToCurve` | (`interpolate`: `undefined` \| `string`, `defaultCurve`: `CurveFactory`) => `CurveFactory` |
| `labelHelper` | (`parent`: `any`, `node`: `any`, `_classes`: `any`) => `Promise`<{ `bbox`: `any` ; `halfPadding`: `number` ; `label`: `any` = labelEl; `shapeSvg`: `any` }> |
| `log` | `Record`<`LogLevel`, (...`data`: `any`\[]) => `void`(`message?`: `any`, ...`optionalParams`: `any`\[]) => `void`> |
| `positionEdgeLabel` | (`edge`: `any`, `paths`: `any`) => `void` |
#### Defined in
[packages/mermaid/src/mermaid.ts:439](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/mermaid.ts#L439)
--- ---
@@ -173,7 +130,7 @@ Use [parse](mermaid.Mermaid.md#parse) and [render](mermaid.Mermaid.md#render) in
#### Defined in #### Defined in
[packages/mermaid/src/mermaid.ts:421](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/mermaid.ts#L421) [packages/mermaid/src/mermaid.ts:424](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/mermaid.ts#L424)
--- ---
@@ -223,7 +180,7 @@ Error if the diagram is invalid and parseOptions.suppressErrors is false or not
#### Defined in #### Defined in
[packages/mermaid/src/mermaid.ts:422](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/mermaid.ts#L422) [packages/mermaid/src/mermaid.ts:425](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/mermaid.ts#L425)
--- ---
@@ -233,7 +190,7 @@ Error if the diagram is invalid and parseOptions.suppressErrors is false or not
#### Defined in #### Defined in
[packages/mermaid/src/mermaid.ts:416](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/mermaid.ts#L416) [packages/mermaid/src/mermaid.ts:419](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/mermaid.ts#L419)
--- ---
@@ -261,7 +218,7 @@ Used to register external diagram types.
#### Defined in #### Defined in
[packages/mermaid/src/mermaid.ts:430](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/mermaid.ts#L430) [packages/mermaid/src/mermaid.ts:433](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/mermaid.ts#L433)
--- ---
@@ -285,7 +242,7 @@ Used to register external diagram types.
#### Defined in #### Defined in
[packages/mermaid/src/mermaid.ts:429](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/mermaid.ts#L429) [packages/mermaid/src/mermaid.ts:432](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/mermaid.ts#L432)
--- ---
@@ -311,7 +268,7 @@ Used to register external diagram types.
#### Defined in #### Defined in
[packages/mermaid/src/mermaid.ts:423](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/mermaid.ts#L423) [packages/mermaid/src/mermaid.ts:426](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/mermaid.ts#L426)
--- ---
@@ -359,7 +316,7 @@ Renders the mermaid diagrams
#### Defined in #### Defined in
[packages/mermaid/src/mermaid.ts:428](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/mermaid.ts#L428) [packages/mermaid/src/mermaid.ts:431](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/mermaid.ts#L431)
--- ---
@@ -394,7 +351,7 @@ to it (eg. dart interop wrapper). (Initially there is no parseError member of me
#### Defined in #### Defined in
[packages/mermaid/src/mermaid.ts:433](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/mermaid.ts#L433) [packages/mermaid/src/mermaid.ts:436](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/mermaid.ts#L436)
--- ---
@@ -404,4 +361,4 @@ to it (eg. dart interop wrapper). (Initially there is no parseError member of me
#### Defined in #### Defined in
[packages/mermaid/src/mermaid.ts:415](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/mermaid.ts#L415) [packages/mermaid/src/mermaid.ts:418](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/mermaid.ts#L418)

View File

@@ -0,0 +1,19 @@
> **Warning**
>
> ## THIS IS AN AUTOGENERATED FILE. DO NOT EDIT.
>
> ## Please edit the corresponding file in [/packages/mermaid/src/docs/config/setup/interfaces/mermaid.RenderOptions.md](../../../../packages/mermaid/src/docs/config/setup/interfaces/mermaid.RenderOptions.md).
# Interface: RenderOptions
[mermaid](../modules/mermaid.md).RenderOptions
## Properties
### algorithm
`Optional` **algorithm**: `string`
#### Defined in
[packages/mermaid/src/rendering-util/render.ts:8](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/rendering-util/render.ts#L8)

View File

@@ -18,7 +18,7 @@ The nodes to render. If this is set, `querySelector` will be ignored.
#### Defined in #### Defined in
[packages/mermaid/src/mermaid.ts:45](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/mermaid.ts#L45) [packages/mermaid/src/mermaid.ts:48](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/mermaid.ts#L48)
--- ---
@@ -44,7 +44,7 @@ A callback to call after each diagram is rendered.
#### Defined in #### Defined in
[packages/mermaid/src/mermaid.ts:49](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/mermaid.ts#L49) [packages/mermaid/src/mermaid.ts:52](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/mermaid.ts#L52)
--- ---
@@ -56,7 +56,7 @@ The query selector to use when finding elements to render. Default: `".mermaid"`
#### Defined in #### Defined in
[packages/mermaid/src/mermaid.ts:41](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/mermaid.ts#L41) [packages/mermaid/src/mermaid.ts:44](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/mermaid.ts#L44)
--- ---
@@ -68,4 +68,4 @@ If `true`, errors will be logged to the console, but not thrown. Default: `false
#### Defined in #### Defined in
[packages/mermaid/src/mermaid.ts:53](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/mermaid.ts#L53) [packages/mermaid/src/mermaid.ts:56](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/mermaid.ts#L56)

View File

@@ -20,11 +20,22 @@
- [MermaidConfig](../interfaces/mermaid.MermaidConfig.md) - [MermaidConfig](../interfaces/mermaid.MermaidConfig.md)
- [ParseOptions](../interfaces/mermaid.ParseOptions.md) - [ParseOptions](../interfaces/mermaid.ParseOptions.md)
- [ParseResult](../interfaces/mermaid.ParseResult.md) - [ParseResult](../interfaces/mermaid.ParseResult.md)
- [RenderOptions](../interfaces/mermaid.RenderOptions.md)
- [RenderResult](../interfaces/mermaid.RenderResult.md) - [RenderResult](../interfaces/mermaid.RenderResult.md)
- [RunOptions](../interfaces/mermaid.RunOptions.md) - [RunOptions](../interfaces/mermaid.RunOptions.md)
## Type Aliases ## Type Aliases
### InternalHelpers
Ƭ **InternalHelpers**: typeof `internalHelpers`
#### Defined in
[packages/mermaid/src/internals.ts:33](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/internals.ts#L33)
---
### ParseErrorFunction ### ParseErrorFunction
Ƭ **ParseErrorFunction**: (`err`: `string` | [`DetailedError`](../interfaces/mermaid.DetailedError.md) | `unknown`, `hash?`: `any`) => `void` Ƭ **ParseErrorFunction**: (`err`: `string` | [`DetailedError`](../interfaces/mermaid.DetailedError.md) | `unknown`, `hash?`: `any`) => `void`
@@ -48,6 +59,26 @@
[packages/mermaid/src/Diagram.ts:10](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/Diagram.ts#L10) [packages/mermaid/src/Diagram.ts:10](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/Diagram.ts#L10)
---
### SVG
Ƭ **SVG**: `d3.Selection`<`SVGSVGElement`, `unknown`, `Element` | `null`, `unknown`>
#### Defined in
[packages/mermaid/src/diagram-api/types.ts:130](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/diagram-api/types.ts#L130)
---
### SVGGroup
Ƭ **SVGGroup**: `d3.Selection`<`SVGGElement`, `unknown`, `Element` | `null`, `unknown`>
#### Defined in
[packages/mermaid/src/diagram-api/types.ts:132](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/diagram-api/types.ts#L132)
## Variables ## Variables
### default ### default
@@ -56,4 +87,4 @@
#### Defined in #### Defined in
[packages/mermaid/src/mermaid.ts:442](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/mermaid.ts#L442) [packages/mermaid/src/mermaid.ts:440](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/mermaid.ts#L440)

View File

@@ -31,13 +31,16 @@
], ],
"license": "MIT", "license": "MIT",
"dependencies": { "dependencies": {
"elkjs": "^0.9.3", "d3": "^7.9.0",
"d3": "^7.9.0" "elkjs": "^0.9.3"
}, },
"peerDependencies": { "peerDependencies": {
"mermaid": "workspace:^" "mermaid": "workspace:^"
}, },
"files": [ "files": [
"dist" "dist"
] ],
"devDependencies": {
"@types/d3": "^7.4.3"
}
} }

View File

@@ -1,10 +1,13 @@
// @ts-nocheck File not ready to check types
import { curveLinear } from 'd3'; import { curveLinear } from 'd3';
import ELK from 'elkjs/lib/elk.bundled.js'; import ELK from 'elkjs/lib/elk.bundled.js';
import mermaid, { type LayoutData } from 'mermaid'; import type { InternalHelpers, LayoutData, RenderOptions, SVG, SVGGroup } from 'mermaid';
import { type TreeData, findCommonAncestor } from './find-common-ancestor.js'; import { type TreeData, findCommonAncestor } from './find-common-ancestor.js';
const { export const render = async (
data4Layout: LayoutData,
svg: SVG,
element: any,
{
common, common,
getConfig, getConfig,
insertCluster, insertCluster,
@@ -16,45 +19,18 @@ const {
labelHelper, labelHelper,
log, log,
positionEdgeLabel, positionEdgeLabel,
} = mermaid.internalHelpers; }: InternalHelpers,
// import { insertEdge } from '../../mermaid/src/rendering-util/rendering-elements/edges.js'; { algorithm }: RenderOptions
const nodeDb = {}; ) => {
const portPos = {}; const nodeDb: Record<string, any> = {};
const clusterDb = {}; const clusterDb: Record<string, any> = {};
export const addVertex = async (nodeEl, graph, nodeArr, node) => { const addVertex = async (nodeEl: any, graph: { children: any[] }, nodeArr: any, node: any) => {
const labelData = { width: 0, height: 0 }; const labelData: any = { width: 0, height: 0 };
// const ports = [
// {
// id: node.id + '-west',
// layoutOptions: {
// 'port.side': 'WEST',
// },
// },
// {
// id: node.id + '-east',
// layoutOptions: {
// 'port.side': 'EAST',
// },
// },
// {
// id: node.id + '-south',
// layoutOptions: {
// 'port.side': 'SOUTH',
// },
// },
// {
// id: node.id + '-north',
// layoutOptions: {
// 'port.side': 'NORTH',
// },
// },
// ];
let boundingBox; let boundingBox;
const child = { const child = {
...node, ...node,
// ports: node.shape === 'diamond' ? ports : [],
}; };
graph.children.push(child); graph.children.push(child);
nodeDb[node.id] = child; nodeDb[node.id] = child;
@@ -72,9 +48,10 @@ export const addVertex = async (nodeEl, graph, nodeArr, node) => {
await addVertices(nodeEl, nodeArr, child, node.id); await addVertices(nodeEl, nodeArr, child, node.id);
if (node.label) { if (node.label) {
// @ts-ignore TODO: fix this
const { shapeSvg, bbox } = await labelHelper(nodeEl, node, undefined, true); const { shapeSvg, bbox } = await labelHelper(nodeEl, node, undefined, true);
labelData.width = bbox.width; labelData.width = bbox.width;
labelData.wrappingWidth = getConfig().flowchart.wrappingWidth; labelData.wrappingWidth = getConfig().flowchart!.wrappingWidth;
// Give some padding for elk // Give some padding for elk
labelData.height = bbox.height - 2; labelData.height = bbox.height - 2;
labelData.labelNode = shapeSvg.node(); labelData.labelNode = shapeSvg.node();
@@ -90,21 +67,57 @@ export const addVertex = async (nodeEl, graph, nodeArr, node) => {
} }
}; };
export const addVertices = async function (nodeEl, nodeArr, graph, parentId) { const addVertices = async function (
const siblings = nodeArr.filter((node) => node.parentId === parentId); nodeEl: any,
nodeArr: any[],
graph: {
id: string;
layoutOptions: {
'elk.hierarchyHandling': string;
'elk.algorithm': any;
'nodePlacement.strategy': any;
'elk.layered.mergeEdges': any;
'elk.direction': string;
'spacing.baseValue': number;
};
children: never[];
edges: never[];
},
parentId?: undefined
) {
const siblings = nodeArr.filter((node: { parentId: any }) => node.parentId === parentId);
log.info('addVertices APA12', siblings, parentId); log.info('addVertices APA12', siblings, parentId);
// 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
await Promise.all( await Promise.all(
siblings.map(async (node) => { siblings.map(async (node: any) => {
await addVertex(nodeEl, graph, nodeArr, node); await addVertex(nodeEl, graph, nodeArr, node);
}) })
); );
return graph; return graph;
}; };
const drawNodes = async (relX, relY, nodeArray, svg, subgraphsEl, depth) => { const drawNodes = async (
relX: number,
relY: number,
nodeArray: any[],
svg: any,
subgraphsEl: SVGGroup,
depth: number
) => {
await Promise.all( await Promise.all(
nodeArray.map(async function (node) { nodeArray.map(async function (node: {
id: string | number;
x: any;
y: any;
width: number;
labels: { width: any }[];
height: number;
isGroup: any;
labelData: any;
offset: { posX: number; posY: number };
shape: any;
domId: { node: () => any; attr: (arg0: string, arg1: string) => void };
}) {
if (node) { if (node) {
nodeDb[node.id] = node; nodeDb[node.id] = node;
nodeDb[node.id].offset = { nodeDb[node.id].offset = {
@@ -147,7 +160,7 @@ const drawNodes = async (relX, relY, nodeArray, svg, subgraphsEl, depth) => {
); );
await Promise.all( await Promise.all(
nodeArray.map(async function (node) { nodeArray.map(async function (node: { isGroup: any; x: any; y: any; children: any }) {
if (node?.isGroup) { if (node?.isGroup) {
await drawNodes(relX + node.x, relY + node.y, node.children, svg, subgraphsEl, depth + 1); await drawNodes(relX + node.x, relY + node.y, node.children, svg, subgraphsEl, depth + 1);
} }
@@ -155,62 +168,13 @@ const drawNodes = async (relX, relY, nodeArray, svg, subgraphsEl, depth) => {
); );
}; };
const getNextPort = (node, edgeDirection, graphDirection) => { const addSubGraphs = (nodeArr: any[]): TreeData => {
log.info('getNextPort abc88', { node, edgeDirection, graphDirection });
if (!portPos[node]) {
switch (graphDirection) {
case 'TB':
case 'TD':
portPos[node] = {
inPosition: 'north',
outPosition: 'south',
};
break;
case 'BT':
portPos[node] = {
inPosition: 'south',
outPosition: 'north',
};
break;
case 'RL':
portPos[node] = {
inPosition: 'east',
outPosition: 'west',
};
break;
case 'LR':
portPos[node] = {
inPosition: 'west',
outPosition: 'east',
};
break;
}
}
const result = edgeDirection === 'in' ? portPos[node].inPosition : portPos[node].outPosition;
if (edgeDirection === 'in') {
portPos[node].inPosition = getNextPosition(
portPos[node].inPosition,
edgeDirection,
graphDirection
);
} else {
portPos[node].outPosition = getNextPosition(
portPos[node].outPosition,
edgeDirection,
graphDirection
);
}
return result;
};
const addSubGraphs = (nodeArr): TreeData => {
const parentLookupDb: TreeData = { parentById: {}, childrenById: {} }; const parentLookupDb: TreeData = { parentById: {}, childrenById: {} };
const subgraphs = nodeArr.filter((node) => node.isGroup); const subgraphs = nodeArr.filter((node: { isGroup: any }) => node.isGroup);
log.info('Subgraphs - ', subgraphs); log.info('Subgraphs - ', subgraphs);
subgraphs.forEach((subgraph) => { subgraphs.forEach((subgraph: { id: string }) => {
const children = nodeArr.filter((node) => node.parentId === subgraph.id); const children = nodeArr.filter((node: { parentId: any }) => node.parentId === subgraph.id);
children.forEach((node) => { children.forEach((node: any) => {
parentLookupDb.parentById[node.id] = subgraph.id; parentLookupDb.parentById[node.id] = subgraph.id;
if (parentLookupDb.childrenById[subgraph.id] === undefined) { if (parentLookupDb.childrenById[subgraph.id] === undefined) {
parentLookupDb.childrenById[subgraph.id] = []; parentLookupDb.childrenById[subgraph.id] = [];
@@ -219,8 +183,8 @@ const addSubGraphs = (nodeArr): TreeData => {
}); });
}); });
subgraphs.forEach(function (subgraph) { subgraphs.forEach(function (subgraph: { id: string | number }) {
const data = { id: subgraph.id }; const data: any = { id: subgraph.id };
if (parentLookupDb.parentById[subgraph.id] !== undefined) { if (parentLookupDb.parentById[subgraph.id] !== undefined) {
data.parent = parentLookupDb.parentById[subgraph.id]; data.parent = parentLookupDb.parentById[subgraph.id];
} }
@@ -228,9 +192,9 @@ const addSubGraphs = (nodeArr): TreeData => {
return parentLookupDb; return parentLookupDb;
}; };
const getEdgeStartEndPoint = (edge, dir) => { const getEdgeStartEndPoint = (edge: any) => {
let source = edge.start; const source: any = edge.start;
let target = edge.end; const target: any = edge.end;
// Save the original source and target // Save the original source and target
const sourceId = source; const sourceId = source;
@@ -243,14 +207,6 @@ const getEdgeStartEndPoint = (edge, dir) => {
return { source, target }; return { source, target };
} }
if (startNode.shape === 'diamond') {
source = `${source}-${getNextPort(source, 'out', dir)}`;
}
if (endNode.shape === 'diamond') {
target = `${target}-${getNextPort(target, 'in', dir)}`;
}
// Add the edge to the graph // Add the edge to the graph
return { source, target, sourceId, targetId }; return { source, target, sourceId, targetId };
}; };
@@ -268,17 +224,45 @@ const calcOffset = function (src: string, dest: string, parentLookupDb: TreeData
/** /**
* Add edges to graph based on parsed graph definition * Add edges to graph based on parsed graph definition
*/ */
export const addEdges = async function (dataForLayout, graph, svg) { const addEdges = async function (
dataForLayout: { edges: any; direction: string },
graph: {
id?: string;
layoutOptions?: {
'elk.hierarchyHandling': string;
'elk.algorithm': any;
'nodePlacement.strategy': any;
'elk.layered.mergeEdges': any;
'elk.direction': string;
'spacing.baseValue': number;
};
children?: never[];
edges: any;
},
svg: SVG
) {
log.info('abc78 DAGA edges = ', dataForLayout); log.info('abc78 DAGA edges = ', dataForLayout);
const edges = dataForLayout.edges; const edges = dataForLayout.edges;
const labelsEl = svg.insert('g').attr('class', 'edgeLabels'); const labelsEl = svg.insert('g').attr('class', 'edgeLabels');
const linkIdCnt = {}; const linkIdCnt: any = {};
const dir = dataForLayout.direction || 'DOWN'; const dir = dataForLayout.direction || 'DOWN';
let defaultStyle; let defaultStyle: string | undefined;
let defaultLabelStyle; let defaultLabelStyle: string | undefined;
await Promise.all( await Promise.all(
edges.map(async function (edge) { edges.map(async function (edge: {
id: string;
start: string;
end: string;
length: number;
text: undefined;
label: any;
type: string;
stroke: any;
interpolate: undefined;
style: undefined;
labelType: any;
}) {
// Identify Link // Identify Link
const linkIdBase = edge.id; // 'L-' + edge.start + '-' + edge.end; const linkIdBase = edge.id; // 'L-' + edge.start + '-' + edge.end;
// count the links from+to the same node to give unique id // count the links from+to the same node to give unique id
@@ -295,7 +279,7 @@ export const addEdges = async function (dataForLayout, graph, svg) {
const linkNameStart = 'LS_' + edge.start; const linkNameStart = 'LS_' + edge.start;
const linkNameEnd = 'LE_' + edge.end; const linkNameEnd = 'LE_' + edge.end;
const edgeData = { style: '', labelStyle: '' }; const edgeData: any = { style: '', labelStyle: '' };
edgeData.minlen = edge.length || 1; edgeData.minlen = edge.length || 1;
edge.text = edge.label; edge.text = edge.label;
// Set link type for rendering // Set link type for rendering
@@ -364,6 +348,7 @@ export const addEdges = async function (dataForLayout, graph, svg) {
} else if (edges.defaultInterpolate !== undefined) { } else if (edges.defaultInterpolate !== undefined) {
edgeData.curve = interpolateToCurve(edges.defaultInterpolate, curveLinear); edgeData.curve = interpolateToCurve(edges.defaultInterpolate, curveLinear);
} else { } else {
// @ts-ignore TODO: fix this
edgeData.curve = interpolateToCurve(conf.curve, curveLinear); edgeData.curve = interpolateToCurve(conf.curve, curveLinear);
} }
@@ -396,6 +381,7 @@ export const addEdges = async function (dataForLayout, graph, svg) {
log.debug('abc78 source and target', source, target); log.debug('abc78 source and target', source, target);
// Add the edge to the graph // Add the edge to the graph
graph.edges.push({ graph.edges.push({
// @ts-ignore TODO: fix this
id: 'e' + edge.start + edge.end, id: 'e' + edge.start + edge.end,
...edge, ...edge,
sources: [source], sources: [source],
@@ -423,7 +409,7 @@ export const addEdges = async function (dataForLayout, graph, svg) {
return graph; return graph;
}; };
function dir2ElkDirection(dir) { function dir2ElkDirection(dir: any) {
switch (dir) { switch (dir) {
case 'LR': case 'LR':
return 'RIGHT'; return 'RIGHT';
@@ -453,268 +439,12 @@ function setIncludeChildrenPolicy(nodeId: string, ancestorId: string) {
} }
} }
export const render = async (data4Layout: LayoutData, svg, element, algorithm) => { function intersectLine(
const elk = new ELK(); p1: { y: number; x: number },
p2: { y: number; x: number },
// Add the arrowheads to the svg q1: { x: any; y: any },
insertMarkers(element, data4Layout.markers, data4Layout.type, data4Layout.diagramId); q2: { x: any; y: any }
) {
// Setup the graph with the layout options and the data for the layout
let elkGraph = {
id: 'root',
layoutOptions: {
'elk.hierarchyHandling': 'INCLUDE_CHILDREN',
'elk.algorithm': algorithm,
'nodePlacement.strategy': data4Layout.config.elk.nodePlacementStrategy,
'elk.layered.mergeEdges': data4Layout.config.elk.mergeEdges,
'elk.direction': 'DOWN',
'spacing.baseValue': 30,
// 'spacing.nodeNode': 40,
// 'spacing.nodeNodeBetweenLayers': 45,
// 'spacing.edgeNode': 40,
// 'spacing.edgeNodeBetweenLayers': 30,
// 'spacing.edgeEdge': 30,
// 'spacing.edgeEdgeBetweenLayers': 40,
// 'spacing.nodeSelfLoop': 50,
},
children: [],
edges: [],
};
log.info('Drawing flowchart using v4 renderer', elk);
// Set the direction of the graph based on the parsed information
const dir = data4Layout.direction || 'DOWN';
elkGraph.layoutOptions['elk.direction'] = dir2ElkDirection(dir);
// Create the lookup db for the subgraphs and their children to used when creating
// the tree structured graph
const parentLookupDb = addSubGraphs(data4Layout.nodes);
// Add elements in the svg to be used to hold the subgraphs container
// elements and the nodes
const subGraphsEl = svg.insert('g').attr('class', 'subgraphs');
const nodeEl = svg.insert('g').attr('class', 'nodes');
// Add the nodes to the graph, this will entail creating the actual nodes
// in order to get the size of the node. You can't get the size of a node
// that is not in the dom so we need to add it to the dom, get the size
// we will position the nodes when we get the layout from elkjs
elkGraph = await addVertices(nodeEl, data4Layout.nodes, elkGraph);
// Time for the edges, we start with adding an element in the node to hold the edges
const edgesEl = svg.insert('g').attr('class', 'edges edgePaths');
// Add the edges to the elk graph, this will entail creating the actual edges
elkGraph = await addEdges(data4Layout, elkGraph, svg);
// Iterate through all nodes and add the top level nodes to the graph
const nodes = data4Layout.nodes;
nodes.forEach((n) => {
const node = nodeDb[n.id];
// Subgraph
if (parentLookupDb.childrenById[node.id] !== undefined) {
node.labels = [
{
text: node.label,
width: node?.labelData?.width || 50,
height: node?.labelData?.height || 50,
},
(node.width = node.width + 2 * node.padding),
log.debug('UIO node label', node?.labelData?.width, node.padding),
];
node.layoutOptions = {
'spacing.baseValue': 30,
'nodeLabels.placement': '[H_CENTER V_TOP, INSIDE]',
};
if (node.dir) {
node.layoutOptions = {
...node.layoutOptions,
'elk.algorithm': algorithm,
'elk.direction': dir2ElkDirection(node.dir),
'nodePlacement.strategy': data4Layout.config['elk.nodePlacement.strategy'],
'elk.layered.mergeEdges': data4Layout.config['elk.mergeEdges'],
'elk.hierarchyHandling': 'SEPARATE_CHILDREN',
};
}
delete node.x;
delete node.y;
delete node.width;
delete node.height;
}
});
elkGraph.edges.forEach((edge) => {
const source = edge.sources[0];
const target = edge.targets[0];
if (nodeDb[source].parentId !== nodeDb[target].parentId) {
const ancestorId = findCommonAncestor(source, target, parentLookupDb);
// an edge that breaks a subgraph has been identified, set configuration accordingly
setIncludeChildrenPolicy(source, ancestorId);
setIncludeChildrenPolicy(target, ancestorId);
}
});
const g = await elk.layout(elkGraph);
// debugger;
await drawNodes(0, 0, g.children, svg, subGraphsEl, 0);
g.edges?.map((edge) => {
// (elem, edge, clusterDb, diagramType, graph, id)
const startNode = nodeDb[edge.sources[0]];
const startCluster = parentLookupDb[edge.sources[0]];
const endNode = nodeDb[edge.targets[0]];
const sourceId = edge.start;
const targetId = edge.end;
const offset = calcOffset(sourceId, targetId, parentLookupDb);
log.debug(
'offset',
offset,
sourceId,
' ==> ',
targetId,
'edge:',
edge,
'cluster:',
startCluster,
startNode
);
if (edge.sections) {
const src = edge.sections[0].startPoint;
const dest = edge.sections[0].endPoint;
const segments = edge.sections[0].bendPoints ? edge.sections[0].bendPoints : [];
const segPoints = segments.map((segment) => {
return { x: segment.x + offset.x, y: segment.y + offset.y };
});
edge.points = [
{ x: src.x + offset.x, y: src.y + offset.y },
...segPoints,
{ x: dest.x + offset.x, y: dest.y + offset.y },
];
let sw = startNode.width;
let ew = endNode.width;
if (startNode.isGroup) {
const bbox = startNode.domId.node().getBBox();
// sw = Math.max(bbox.width, startNode.width, startNode.labels[0].width);
sw = Math.max(startNode.width, startNode.labels[0].width + startNode.padding);
// sw = startNode.width;
log.debug(
'UIO width',
startNode.id,
startNode.with,
'bbox.width=',
bbox.width,
'lw=',
startNode.labels[0].width,
'node:',
startNode.width,
'SW = ',
sw
// 'HTML:',
// startNode.domId.node().innerHTML
);
}
if (endNode.isGroup) {
const bbox = endNode.domId.node().getBBox();
ew = Math.max(endNode.width, endNode.labels[0].width + endNode.padding);
log.debug(
'UIO width',
startNode.id,
startNode.with,
bbox.width,
'EW = ',
ew,
'HTML:',
startNode.innerHTML
);
}
if (startNode.shape === 'diamond') {
edge.points.unshift({
x: startNode.x + startNode.width / 2 + offset.x,
y: startNode.y + startNode.height / 2 + offset.y,
});
}
if (endNode.shape === 'diamond') {
edge.points.push({
x: endNode.x + endNode.width / 2 + offset.x,
y: endNode.y + endNode.height / 2 + offset.y,
});
}
edge.points = cutPathAtIntersect(
edge.points.reverse(),
{
x: startNode.x + startNode.width / 2 + offset.x,
y: startNode.y + startNode.height / 2 + offset.y,
width: sw,
height: startNode.height,
padding: startNode.padding,
},
startNode.shape === 'diamond'
).reverse();
edge.points = cutPathAtIntersect(
edge.points,
{
x: endNode.x + ew / 2 + endNode.offset.x,
y: endNode.y + endNode.height / 2 + endNode.offset.y,
width: ew,
height: endNode.height,
padding: endNode.padding,
},
endNode.shape === 'diamond'
);
const paths = insertEdge(
edgesEl,
edge,
clusterDb,
data4Layout.type,
startNode,
endNode,
data4Layout.diagramId
);
log.info('APA12 edge points after insert', JSON.stringify(edge.points));
edge.x = edge.labels[0].x + offset.x + edge.labels[0].width / 2;
edge.y = edge.labels[0].y + offset.y + edge.labels[0].height / 2;
positionEdgeLabel(edge, paths);
}
// const src = edge.sections[0].startPoint;
// const dest = edge.sections[0].endPoint;
// const segments = edge.sections[0].bendPoints ? edge.sections[0].bendPoints : [];
// const segPoints = segments.map((segment) => {
// return { x: segment.x + offset.x, y: segment.y + offset.y };
// });
// edge.points = [
// { x: src.x + offset.x, y: src.y + offset.y },
// ...segPoints,
// { x: dest.x + offset.x, y: dest.y + offset.y },
// ];
// const paths = insertEdge(
// edgesEl,
// edge,
// clusterDb,
// data4Layout.type,
// startNode,
// endNode,
// data4Layout.diagramId
// );
// log.info('APA12 edge points after insert', JSON.stringify(edge.points));
// edge.x = edge.labels[0].x + offset.x + edge.labels[0].width / 2;
// edge.y = edge.labels[0].y + offset.y + edge.labels[0].height / 2;
// positionEdgeLabel(edge, paths);
});
};
function intersectLine(p1, p2, q1, q2) {
log.debug('UIO intersectLine', p1, p2, q1, q2); log.debug('UIO intersectLine', p1, p2, q1, q2);
// Algorithm from J. Avro, (ed.) Graphics Gems, No 2, Morgan Kaufmann, 1994, // Algorithm from J. Avro, (ed.) Graphics Gems, No 2, Morgan Kaufmann, 1994,
// p7 and p473. // p7 and p473.
@@ -776,10 +506,14 @@ function intersectLine(p1, p2, q1, q2) {
return { x: x, y: y }; return { x: x, y: y };
} }
function sameSign(r1, r2) { function sameSign(r1: number, r2: number) {
return r1 * r2 > 0; return r1 * r2 > 0;
} }
const diamondIntersection = (bounds, outsidePoint, insidePoint) => { const diamondIntersection = (
bounds: { x: any; y: any; width: any; height: any },
outsidePoint: { x: number; y: number },
insidePoint: any
) => {
const x1 = bounds.x; const x1 = bounds.x;
const y1 = bounds.y; const y1 = bounds.y;
@@ -804,15 +538,11 @@ const diamondIntersection = (bounds, outsidePoint, insidePoint) => {
let minX = Number.POSITIVE_INFINITY; let minX = Number.POSITIVE_INFINITY;
let minY = Number.POSITIVE_INFINITY; let minY = Number.POSITIVE_INFINITY;
if (typeof polyPoints.forEach === 'function') {
polyPoints.forEach(function (entry) { polyPoints.forEach(function (entry) {
minX = Math.min(minX, entry.x); minX = Math.min(minX, entry.x);
minY = Math.min(minY, entry.y); minY = Math.min(minY, entry.y);
}); });
} else {
minX = Math.min(minX, polyPoints.x);
minY = Math.min(minY, polyPoints.y);
}
// const left = x1 - w / 2; // const left = x1 - w / 2;
// const top = y1 + h / 2; // const top = y1 + h / 2;
@@ -856,7 +586,11 @@ const diamondIntersection = (bounds, outsidePoint, insidePoint) => {
return intersections[0]; return intersections[0];
}; };
export const intersection = (node, outsidePoint, insidePoint) => { const intersection = (
node: { x: any; y: any; width: number; height: number },
outsidePoint: { x: number; y: number },
insidePoint: { x: number; y: number }
) => {
log.debug(`intersection calc abc89: log.debug(`intersection calc abc89:
outsidePoint: ${JSON.stringify(outsidePoint)} outsidePoint: ${JSON.stringify(outsidePoint)}
insidePoint : ${JSON.stringify(insidePoint)} insidePoint : ${JSON.stringify(insidePoint)}
@@ -925,7 +659,10 @@ export const intersection = (node, outsidePoint, insidePoint) => {
return { x: _x, y: _y }; return { x: _x, y: _y };
} }
}; };
const outsideNode = (node, point) => { const outsideNode = (
node: { x: any; y: any; width: number; height: number },
point: { x: number; y: number }
) => {
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);
@@ -941,12 +678,16 @@ const outsideNode = (node, point) => {
* This function will page a path and node where the last point(s) in the path is inside the node * This function will page a path and node where the last point(s) in the path is inside the node
* and return an update path ending by the border of the node. * and return an update path ending by the border of the node.
*/ */
const cutPathAtIntersect = (_points, bounds, isDiamond: boolean) => { const cutPathAtIntersect = (
_points: any[],
bounds: { x: any; y: any; width: any; height: any; padding: any },
isDiamond: boolean
) => {
log.debug('UIO cutPathAtIntersect Points:', _points, 'node:', bounds, 'isDiamond', isDiamond); log.debug('UIO cutPathAtIntersect Points:', _points, 'node:', bounds, 'isDiamond', isDiamond);
const points = []; const points: any[] = [];
let lastPointOutside = _points[0]; let lastPointOutside = _points[0];
let isInside = false; let isInside = false;
_points.forEach((point) => { _points.forEach((point: any) => {
// const node = clusterDb[edge.toCluster].node; // const node = clusterDb[edge.toCluster].node;
log.debug(' checking point', point, bounds); log.debug(' checking point', point, bounds);
@@ -995,3 +736,257 @@ const cutPathAtIntersect = (_points, bounds, isDiamond: boolean) => {
log.debug('returning points', points); log.debug('returning points', points);
return points; return points;
}; };
// @ts-ignore - ELK is not typed
const elk = new ELK();
// Add the arrowheads to the svg
insertMarkers(element, data4Layout.markers, data4Layout.type, data4Layout.diagramId);
// Setup the graph with the layout options and the data for the layout
let elkGraph: any = {
id: 'root',
layoutOptions: {
'elk.hierarchyHandling': 'INCLUDE_CHILDREN',
'elk.algorithm': algorithm,
'nodePlacement.strategy': data4Layout.config.elk.nodePlacementStrategy,
'elk.layered.mergeEdges': data4Layout.config.elk.mergeEdges,
'elk.direction': 'DOWN',
'spacing.baseValue': 30,
// 'spacing.nodeNode': 40,
// 'spacing.nodeNodeBetweenLayers': 45,
// 'spacing.edgeNode': 40,
// 'spacing.edgeNodeBetweenLayers': 30,
// 'spacing.edgeEdge': 30,
// 'spacing.edgeEdgeBetweenLayers': 40,
// 'spacing.nodeSelfLoop': 50,
},
children: [],
edges: [],
};
log.info('Drawing flowchart using v4 renderer', elk);
// Set the direction of the graph based on the parsed information
const dir = data4Layout.direction || 'DOWN';
elkGraph.layoutOptions['elk.direction'] = dir2ElkDirection(dir);
// Create the lookup db for the subgraphs and their children to used when creating
// the tree structured graph
const parentLookupDb: any = addSubGraphs(data4Layout.nodes);
// Add elements in the svg to be used to hold the subgraphs container
// elements and the nodes
const subGraphsEl = svg.insert('g').attr('class', 'subgraphs');
const nodeEl = svg.insert('g').attr('class', 'nodes');
// Add the nodes to the graph, this will entail creating the actual nodes
// in order to get the size of the node. You can't get the size of a node
// that is not in the dom so we need to add it to the dom, get the size
// we will position the nodes when we get the layout from elkjs
elkGraph = await addVertices(nodeEl, data4Layout.nodes, elkGraph);
// Time for the edges, we start with adding an element in the node to hold the edges
const edgesEl = svg.insert('g').attr('class', 'edges edgePaths');
// Add the edges to the elk graph, this will entail creating the actual edges
elkGraph = await addEdges(data4Layout, elkGraph, svg);
// Iterate through all nodes and add the top level nodes to the graph
const nodes = data4Layout.nodes;
nodes.forEach((n: { id: string | number }) => {
const node = nodeDb[n.id];
// Subgraph
if (parentLookupDb.childrenById[node.id] !== undefined) {
node.labels = [
{
text: node.label,
width: node?.labelData?.width || 50,
height: node?.labelData?.height || 50,
},
(node.width = node.width + 2 * node.padding),
log.debug('UIO node label', node?.labelData?.width, node.padding),
];
node.layoutOptions = {
'spacing.baseValue': 30,
'nodeLabels.placement': '[H_CENTER V_TOP, INSIDE]',
};
if (node.dir) {
node.layoutOptions = {
...node.layoutOptions,
'elk.algorithm': algorithm,
'elk.direction': dir2ElkDirection(node.dir),
'nodePlacement.strategy': data4Layout.config['elk.nodePlacement.strategy'],
'elk.layered.mergeEdges': data4Layout.config['elk.mergeEdges'],
'elk.hierarchyHandling': 'SEPARATE_CHILDREN',
};
}
delete node.x;
delete node.y;
delete node.width;
delete node.height;
}
});
elkGraph.edges.forEach((edge: any) => {
const source = edge.sources[0];
const target = edge.targets[0];
if (nodeDb[source].parentId !== nodeDb[target].parentId) {
const ancestorId = findCommonAncestor(source, target, parentLookupDb);
// an edge that breaks a subgraph has been identified, set configuration accordingly
setIncludeChildrenPolicy(source, ancestorId);
setIncludeChildrenPolicy(target, ancestorId);
}
});
const g = await elk.layout(elkGraph);
// debugger;
await drawNodes(0, 0, g.children, svg, subGraphsEl, 0);
g.edges?.map(
(edge: {
sources: (string | number)[];
targets: (string | number)[];
start: any;
end: any;
sections: { startPoint: any; endPoint: any; bendPoints: any }[];
points: any[];
x: any;
labels: { height: number; width: number; x: number; y: number }[];
y: any;
}) => {
// (elem, edge, clusterDb, diagramType, graph, id)
const startNode = nodeDb[edge.sources[0]];
const startCluster = parentLookupDb[edge.sources[0]];
const endNode = nodeDb[edge.targets[0]];
const sourceId = edge.start;
const targetId = edge.end;
const offset = calcOffset(sourceId, targetId, parentLookupDb);
log.debug(
'offset',
offset,
sourceId,
' ==> ',
targetId,
'edge:',
edge,
'cluster:',
startCluster,
startNode
);
if (edge.sections) {
const src = edge.sections[0].startPoint;
const dest = edge.sections[0].endPoint;
const segments = edge.sections[0].bendPoints ? edge.sections[0].bendPoints : [];
const segPoints = segments.map((segment: { x: any; y: any }) => {
return { x: segment.x + offset.x, y: segment.y + offset.y };
});
edge.points = [
{ x: src.x + offset.x, y: src.y + offset.y },
...segPoints,
{ x: dest.x + offset.x, y: dest.y + offset.y },
];
let sw = startNode.width;
let ew = endNode.width;
if (startNode.isGroup) {
const bbox = startNode.domId.node().getBBox();
// sw = Math.max(bbox.width, startNode.width, startNode.labels[0].width);
sw = Math.max(startNode.width, startNode.labels[0].width + startNode.padding);
// sw = startNode.width;
log.debug(
'UIO width',
startNode.id,
startNode.with,
'bbox.width=',
bbox.width,
'lw=',
startNode.labels[0].width,
'node:',
startNode.width,
'SW = ',
sw
// 'HTML:',
// startNode.domId.node().innerHTML
);
}
if (endNode.isGroup) {
const bbox = endNode.domId.node().getBBox();
ew = Math.max(endNode.width, endNode.labels[0].width + endNode.padding);
log.debug(
'UIO width',
startNode.id,
startNode.with,
bbox.width,
'EW = ',
ew,
'HTML:',
startNode.innerHTML
);
}
if (startNode.shape === 'diamond') {
edge.points.unshift({
x: startNode.x + startNode.width / 2 + offset.x,
y: startNode.y + startNode.height / 2 + offset.y,
});
}
if (endNode.shape === 'diamond') {
const x = endNode.x + endNode.width / 2 + offset.x;
// Add a point at the center of the diamond
if (
Math.abs(edge.points[edge.points.length - 1].y - endNode.y - offset.y) > 0.001 ||
Math.abs(edge.points[edge.points.length - 1].x - x) > 0.001
) {
edge.points.push({
x: endNode.x + endNode.width / 2 + offset.x,
y: endNode.y + endNode.height / 2 + offset.y,
});
}
}
edge.points = cutPathAtIntersect(
edge.points.reverse(),
{
x: startNode.x + startNode.width / 2 + offset.x,
y: startNode.y + startNode.height / 2 + offset.y,
width: sw,
height: startNode.height,
padding: startNode.padding,
},
startNode.shape === 'diamond'
).reverse();
edge.points = cutPathAtIntersect(
edge.points,
{
x: endNode.x + ew / 2 + endNode.offset.x,
y: endNode.y + endNode.height / 2 + endNode.offset.y,
width: ew,
height: endNode.height,
padding: endNode.padding,
},
endNode.shape === 'diamond'
);
const paths = insertEdge(
edgesEl,
edge,
clusterDb,
data4Layout.type,
startNode,
endNode,
data4Layout.diagramId
);
log.info('APA12 edge points after insert', JSON.stringify(edge.points));
edge.x = edge.labels[0].x + offset.x + edge.labels[0].width / 2;
edge.y = edge.labels[0].y + offset.y + edge.labels[0].height / 2;
positionEdgeLabel(edge, paths);
}
}
);
};

View File

@@ -129,6 +129,6 @@ export type HTML = d3.Selection<HTMLIFrameElement, unknown, Element | null, unkn
export type SVG = d3.Selection<SVGSVGElement, unknown, Element | null, unknown>; export type SVG = d3.Selection<SVGSVGElement, unknown, Element | null, unknown>;
export type Group = d3.Selection<SVGGElement, unknown, Element | null, unknown>; export type SVGGroup = d3.Selection<SVGGElement, unknown, Element | null, unknown>;
export type DiagramStylesProvider = (options?: any) => string; export type DiagramStylesProvider = (options?: any) => string;

View File

@@ -1,5 +1,6 @@
import { sanitizeUrl } from '@braintree/sanitize-url'; import { sanitizeUrl } from '@braintree/sanitize-url';
import type { Group, SVG } from '../../diagram-api/types.js'; import type { SVG, SVGGroup } from '../../diagram-api/types.js';
import { lineBreakRegex } from './common.js';
import type { import type {
Bound, Bound,
D3ImageElement, D3ImageElement,
@@ -11,9 +12,8 @@ import type {
TextData, TextData,
TextObject, TextObject,
} from './commonTypes.js'; } from './commonTypes.js';
import { lineBreakRegex } from './common.js';
export const drawRect = (element: SVG | Group, rectData: RectData): D3RectElement => { export const drawRect = (element: SVG | SVGGroup, rectData: RectData): D3RectElement => {
const rectElement: D3RectElement = element.append('rect'); const rectElement: D3RectElement = element.append('rect');
rectElement.attr('x', rectData.x); rectElement.attr('x', rectData.x);
rectElement.attr('y', rectData.y); rectElement.attr('y', rectData.y);
@@ -50,7 +50,7 @@ export const drawRect = (element: SVG | Group, rectData: RectData): D3RectElemen
* @param element - Diagram (reference for bounds) * @param element - Diagram (reference for bounds)
* @param bounds - Shape of the rectangle * @param bounds - Shape of the rectangle
*/ */
export const drawBackgroundRect = (element: SVG | Group, bounds: Bound): void => { export const drawBackgroundRect = (element: SVG | SVGGroup, bounds: Bound): void => {
const rectData: RectData = { const rectData: RectData = {
x: bounds.startx, x: bounds.startx,
y: bounds.starty, y: bounds.starty,
@@ -64,7 +64,7 @@ export const drawBackgroundRect = (element: SVG | Group, bounds: Bound): void =>
rectElement.lower(); rectElement.lower();
}; };
export const drawText = (element: SVG | Group, textData: TextData): D3TextElement => { export const drawText = (element: SVG | SVGGroup, textData: TextData): D3TextElement => {
const nText: string = textData.text.replace(lineBreakRegex, ' '); const nText: string = textData.text.replace(lineBreakRegex, ' ');
const textElem: D3TextElement = element.append('text'); const textElem: D3TextElement = element.append('text');
@@ -84,7 +84,7 @@ export const drawText = (element: SVG | Group, textData: TextData): D3TextElemen
return textElem; return textElem;
}; };
export const drawImage = (elem: SVG | Group, x: number, y: number, link: string): void => { export const drawImage = (elem: SVG | SVGGroup, x: number, y: number, link: string): void => {
const imageElement: D3ImageElement = elem.append('image'); const imageElement: D3ImageElement = elem.append('image');
imageElement.attr('x', x); imageElement.attr('x', x);
imageElement.attr('y', y); imageElement.attr('y', y);
@@ -93,7 +93,7 @@ export const drawImage = (elem: SVG | Group, x: number, y: number, link: string)
}; };
export const drawEmbeddedImage = ( export const drawEmbeddedImage = (
element: SVG | Group, element: SVG | SVGGroup,
x: number, x: number,
y: number, y: number,
link: string link: string

View File

@@ -1,5 +1,5 @@
import type { SVG, SVGGroup } from '../../diagram-api/types.js';
import { log } from '../../logger.js'; import { log } from '../../logger.js';
import type { Group, SVG } from '../../diagram-api/types.js';
import { selectSvgElement } from '../../rendering-util/selectSvgElement.js'; import { selectSvgElement } from '../../rendering-util/selectSvgElement.js';
import { configureSvgSize } from '../../setupGraphViewbox.js'; import { configureSvgSize } from '../../setupGraphViewbox.js';
@@ -13,7 +13,7 @@ import { configureSvgSize } from '../../setupGraphViewbox.js';
export const draw = (_text: string, id: string, version: string) => { export const draw = (_text: string, id: string, version: string) => {
log.debug('rendering svg for syntax error\n'); log.debug('rendering svg for syntax error\n');
const svg: SVG = selectSvgElement(id); const svg: SVG = selectSvgElement(id);
const g: Group = svg.append('g'); const g: SVGGroup = svg.append('g');
svg.attr('viewBox', '0 0 2412 512'); svg.attr('viewBox', '0 0 2412 512');
configureSvgSize(svg, 100, 512, true); configureSvgSize(svg, 100, 512, true);

View File

@@ -1,7 +1,7 @@
import type { DrawDefinition, SVG, SVGGroup } from '../../diagram-api/types.js';
import { log } from '../../logger.js'; import { log } from '../../logger.js';
import { configureSvgSize } from '../../setupGraphViewbox.js';
import type { DrawDefinition, Group, SVG } from '../../diagram-api/types.js';
import { selectSvgElement } from '../../rendering-util/selectSvgElement.js'; import { selectSvgElement } from '../../rendering-util/selectSvgElement.js';
import { configureSvgSize } from '../../setupGraphViewbox.js';
/** /**
* 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.
@@ -16,7 +16,7 @@ const draw: DrawDefinition = (text, id, version) => {
const svg: SVG = selectSvgElement(id); const svg: SVG = selectSvgElement(id);
configureSvgSize(svg, 100, 400, true); configureSvgSize(svg, 100, 400, true);
const group: Group = svg.append('g'); const group: SVGGroup = svg.append('g');
group group
.append('text') .append('text')
.attr('x', 100) .attr('x', 100)

View File

@@ -1,6 +1,6 @@
import type { Diagram } from '../../Diagram.js'; import type { Diagram } from '../../Diagram.js';
import type { PacketDiagramConfig } from '../../config.type.js'; import type { PacketDiagramConfig } from '../../config.type.js';
import type { DiagramRenderer, DrawDefinition, Group, SVG } from '../../diagram-api/types.js'; import type { DiagramRenderer, DrawDefinition, SVG, SVGGroup } from '../../diagram-api/types.js';
import { selectSvgElement } from '../../rendering-util/selectSvgElement.js'; import { selectSvgElement } from '../../rendering-util/selectSvgElement.js';
import { configureSvgSize } from '../../setupGraphViewbox.js'; import { configureSvgSize } from '../../setupGraphViewbox.js';
import type { PacketDB, PacketWord } from './types.js'; import type { PacketDB, PacketWord } from './types.js';
@@ -39,7 +39,7 @@ const drawWord = (
rowNumber: number, rowNumber: number,
{ rowHeight, paddingX, paddingY, bitWidth, bitsPerRow, showBits }: Required<PacketDiagramConfig> { rowHeight, paddingX, paddingY, bitWidth, bitsPerRow, showBits }: Required<PacketDiagramConfig>
) => { ) => {
const group: Group = svg.append('g'); const group: SVGGroup = svg.append('g');
const wordY = rowNumber * (rowHeight + paddingY) + paddingY; const wordY = rowNumber * (rowHeight + paddingY) + paddingY;
for (const block of word) { for (const block of word) {
const blockX = (block.start % bitsPerRow) * bitWidth + 1; const blockX = (block.start % bitsPerRow) * bitWidth + 1;

View File

@@ -1,13 +1,13 @@
import type d3 from 'd3'; import type d3 from 'd3';
import { scaleOrdinal, pie as d3pie, arc } from 'd3'; import { arc, pie as d3pie, scaleOrdinal } from 'd3';
import { log } from '../../logger.js';
import { configureSvgSize } from '../../setupGraphViewbox.js';
import { getConfig } from '../../diagram-api/diagramAPI.js';
import { cleanAndMerge, parseFontSize } from '../../utils.js';
import type { DrawDefinition, Group, SVG } from '../../diagram-api/types.js';
import type { D3Section, PieDB, Sections } from './pieTypes.js';
import type { MermaidConfig, PieDiagramConfig } from '../../config.type.js'; import type { MermaidConfig, PieDiagramConfig } from '../../config.type.js';
import { getConfig } from '../../diagram-api/diagramAPI.js';
import type { DrawDefinition, SVG, SVGGroup } from '../../diagram-api/types.js';
import { log } from '../../logger.js';
import { selectSvgElement } from '../../rendering-util/selectSvgElement.js'; import { selectSvgElement } from '../../rendering-util/selectSvgElement.js';
import { configureSvgSize } from '../../setupGraphViewbox.js';
import { cleanAndMerge, parseFontSize } from '../../utils.js';
import type { D3Section, PieDB, Sections } from './pieTypes.js';
const createPieArcs = (sections: Sections): d3.PieArcDatum<D3Section>[] => { const createPieArcs = (sections: Sections): d3.PieArcDatum<D3Section>[] => {
// Compute the position of each group on the pie: // Compute the position of each group on the pie:
@@ -46,7 +46,7 @@ export const draw: DrawDefinition = (text, id, _version, diagObj) => {
const height = 450; const height = 450;
const pieWidth: number = height; const pieWidth: number = height;
const svg: SVG = selectSvgElement(id); const svg: SVG = selectSvgElement(id);
const group: Group = svg.append('g'); const group: SVGGroup = svg.append('g');
group.attr('transform', 'translate(' + pieWidth / 2 + ',' + height / 2 + ')'); group.attr('transform', 'translate(' + pieWidth / 2 + ',' + height / 2 + ')');
const { themeVariables } = globalConfig; const { themeVariables } = globalConfig;

View File

@@ -1,4 +1,4 @@
import type { Group } from '../../../../../diagram-api/types.js'; import type { SVGGroup } from '../../../../../diagram-api/types.js';
import type { import type {
AxisDataType, AxisDataType,
ChartComponent, ChartComponent,
@@ -25,7 +25,7 @@ export function getAxis(
data: AxisDataType, data: AxisDataType,
axisConfig: XYChartAxisConfig, axisConfig: XYChartAxisConfig,
axisThemeConfig: XYChartAxisThemeConfig, axisThemeConfig: XYChartAxisThemeConfig,
tmpSVGGroup: Group tmpSVGGroup: SVGGroup
): Axis { ): Axis {
const textDimensionCalculator = new TextDimensionCalculatorWithFont(tmpSVGGroup); const textDimensionCalculator = new TextDimensionCalculatorWithFont(tmpSVGGroup);
if (isBandAxisData(data)) { if (isBandAxisData(data)) {

View File

@@ -1,13 +1,13 @@
import type { Group } from '../../../../diagram-api/types.js'; import type { SVGGroup } from '../../../../diagram-api/types.js';
import type { import type {
BoundingRect, BoundingRect,
ChartComponent, ChartComponent,
Dimension, Dimension,
DrawableElem, DrawableElem,
Point, Point,
XYChartConfig,
XYChartData, XYChartData,
XYChartThemeConfig, XYChartThemeConfig,
XYChartConfig,
} from '../interfaces.js'; } from '../interfaces.js';
import type { TextDimensionCalculator } from '../textDimensionCalculator.js'; import type { TextDimensionCalculator } from '../textDimensionCalculator.js';
import { TextDimensionCalculatorWithFont } from '../textDimensionCalculator.js'; import { TextDimensionCalculatorWithFont } from '../textDimensionCalculator.js';
@@ -84,7 +84,7 @@ export function getChartTitleComponent(
chartConfig: XYChartConfig, chartConfig: XYChartConfig,
chartData: XYChartData, chartData: XYChartData,
chartThemeConfig: XYChartThemeConfig, chartThemeConfig: XYChartThemeConfig,
tmpSVGGroup: Group tmpSVGGroup: SVGGroup
): ChartComponent { ): ChartComponent {
const textDimensionCalculator = new TextDimensionCalculatorWithFont(tmpSVGGroup); const textDimensionCalculator = new TextDimensionCalculatorWithFont(tmpSVGGroup);
return new ChartTitle(textDimensionCalculator, chartConfig, chartData, chartThemeConfig); return new ChartTitle(textDimensionCalculator, chartConfig, chartData, chartThemeConfig);

View File

@@ -1,4 +1,4 @@
import type { Group } from '../../../diagram-api/types.js'; import type { SVGGroup } from '../../../diagram-api/types.js';
import type { DrawableElem, XYChartConfig, XYChartData, XYChartThemeConfig } from './interfaces.js'; import type { DrawableElem, XYChartConfig, XYChartData, XYChartThemeConfig } from './interfaces.js';
import { Orchestrator } from './orchestrator.js'; import { Orchestrator } from './orchestrator.js';
@@ -7,7 +7,7 @@ export class XYChartBuilder {
config: XYChartConfig, config: XYChartConfig,
chartData: XYChartData, chartData: XYChartData,
chartThemeConfig: XYChartThemeConfig, chartThemeConfig: XYChartThemeConfig,
tmpSVGGroup: Group tmpSVGGroup: SVGGroup
): DrawableElem[] { ): DrawableElem[] {
const orchestrator = new Orchestrator(config, chartData, chartThemeConfig, tmpSVGGroup); const orchestrator = new Orchestrator(config, chartData, chartThemeConfig, tmpSVGGroup);
return orchestrator.getDrawableElement(); return orchestrator.getDrawableElement();

View File

@@ -1,3 +1,9 @@
import type { SVGGroup } from '../../../diagram-api/types.js';
import type { Axis } from './components/axis/index.js';
import { getAxis } from './components/axis/index.js';
import { getChartTitleComponent } from './components/chartTitle.js';
import type { Plot } from './components/plot/index.js';
import { getPlotComponent } from './components/plot/index.js';
import type { import type {
ChartComponent, ChartComponent,
DrawableElem, DrawableElem,
@@ -6,12 +12,6 @@ import type {
XYChartThemeConfig, XYChartThemeConfig,
} from './interfaces.js'; } from './interfaces.js';
import { isBarPlot } from './interfaces.js'; import { isBarPlot } from './interfaces.js';
import type { Axis } from './components/axis/index.js';
import { getAxis } from './components/axis/index.js';
import { getChartTitleComponent } from './components/chartTitle.js';
import type { Plot } from './components/plot/index.js';
import { getPlotComponent } from './components/plot/index.js';
import type { Group } from '../../../diagram-api/types.js';
export class Orchestrator { export class Orchestrator {
private componentStore: { private componentStore: {
@@ -24,7 +24,7 @@ export class Orchestrator {
private chartConfig: XYChartConfig, private chartConfig: XYChartConfig,
private chartData: XYChartData, private chartData: XYChartData,
chartThemeConfig: XYChartThemeConfig, chartThemeConfig: XYChartThemeConfig,
tmpSVGGroup: Group tmpSVGGroup: SVGGroup
) { ) {
this.componentStore = { this.componentStore = {
title: getChartTitleComponent(chartConfig, chartData, chartThemeConfig, tmpSVGGroup), title: getChartTitleComponent(chartConfig, chartData, chartThemeConfig, tmpSVGGroup),

View File

@@ -1,13 +1,13 @@
import type { Dimension } from './interfaces.js'; import type { SVGGroup } from '../../../diagram-api/types.js';
import { computeDimensionOfText } from '../../../rendering-util/createText.js'; import { computeDimensionOfText } from '../../../rendering-util/createText.js';
import type { Group } from '../../../diagram-api/types.js'; import type { Dimension } from './interfaces.js';
export interface TextDimensionCalculator { export interface TextDimensionCalculator {
getMaxDimension(texts: string[], fontSize: number): Dimension; getMaxDimension(texts: string[], fontSize: number): Dimension;
} }
export class TextDimensionCalculatorWithFont implements TextDimensionCalculator { export class TextDimensionCalculatorWithFont implements TextDimensionCalculator {
constructor(private parentGroup: Group) {} constructor(private parentGroup: SVGGroup) {}
getMaxDimension(texts: string[], fontSize: number): Dimension { getMaxDimension(texts: string[], fontSize: number): Dimension {
if (!this.parentGroup) { if (!this.parentGroup) {
return { return {

View File

@@ -1,3 +1,9 @@
import * as configApi from '../../config.js';
import defaultConfig from '../../defaultConfig.js';
import type { SVGGroup } from '../../diagram-api/types.js';
import { getThemeVariables } from '../../themes/theme-default.js';
import { cleanAndMerge } from '../../utils.js';
import { sanitizeText } from '../common/common.js';
import { import {
clear as commonClear, clear as commonClear,
getAccDescription, getAccDescription,
@@ -7,11 +13,6 @@ import {
setAccTitle, setAccTitle,
setDiagramTitle, setDiagramTitle,
} from '../common/commonDb.js'; } from '../common/commonDb.js';
import * as configApi from '../../config.js';
import defaultConfig from '../../defaultConfig.js';
import { getThemeVariables } from '../../themes/theme-default.js';
import { cleanAndMerge } from '../../utils.js';
import { sanitizeText } from '../common/common.js';
import { XYChartBuilder } from './chartBuilder/index.js'; import { XYChartBuilder } from './chartBuilder/index.js';
import type { import type {
DrawableElem, DrawableElem,
@@ -21,11 +22,10 @@ import type {
XYChartThemeConfig, XYChartThemeConfig,
} from './chartBuilder/interfaces.js'; } from './chartBuilder/interfaces.js';
import { isBandAxisData, isLinearAxisData } from './chartBuilder/interfaces.js'; import { isBandAxisData, isLinearAxisData } from './chartBuilder/interfaces.js';
import type { Group } from '../../diagram-api/types.js';
let plotIndex = 0; let plotIndex = 0;
let tmpSVGGroup: Group; let tmpSVGGroup: SVGGroup;
let xyChartConfig: XYChartConfig = getChartDefaultConfig(); let xyChartConfig: XYChartConfig = getChartDefaultConfig();
let xyChartThemeConfig: XYChartThemeConfig = getChartDefaultThemeConfig(); let xyChartThemeConfig: XYChartThemeConfig = getChartDefaultThemeConfig();
@@ -75,7 +75,7 @@ function textSanitizer(text: string) {
return sanitizeText(text.trim(), config); return sanitizeText(text.trim(), config);
} }
function setTmpSVGG(SVGG: Group) { function setTmpSVGG(SVGG: SVGGroup) {
tmpSVGGroup = SVGG; tmpSVGGroup = SVGG;
} }
function setOrientation(orientation: string) { function setOrientation(orientation: string) {

View File

@@ -29,3 +29,5 @@ export const internalHelpers = {
log, log,
positionEdgeLabel, positionEdgeLabel,
}; };
export type InternalHelpers = typeof internalHelpers;

View File

@@ -4,34 +4,37 @@
*/ */
import { dedent } from 'ts-dedent'; import { dedent } from 'ts-dedent';
import type { MermaidConfig } from './config.type.js'; import type { MermaidConfig } from './config.type.js';
import { log } from './logger.js'; import { detectType, registerLazyLoadedDiagrams } from './diagram-api/detectType.js';
import utils from './utils.js';
import type { ParseOptions, ParseResult, RenderResult } from './types.js';
import { mermaidAPI } from './mermaidAPI.js';
import { registerLazyLoadedDiagrams, detectType } from './diagram-api/detectType.js';
import { loadRegisteredDiagrams } from './diagram-api/loadDiagram.js';
import type { ParseErrorFunction } from './Diagram.js';
import { isDetailedError } from './utils.js';
import type { DetailedError } from './utils.js';
import type { ExternalDiagramDefinition } from './diagram-api/types.js';
import type { UnknownDiagramError } from './errors.js';
import { addDiagrams } from './diagram-api/diagram-orchestration.js'; import { addDiagrams } from './diagram-api/diagram-orchestration.js';
import { loadRegisteredDiagrams } from './diagram-api/loadDiagram.js';
import type { ExternalDiagramDefinition, SVG, SVGGroup } from './diagram-api/types.js';
import type { ParseErrorFunction } from './Diagram.js';
import type { UnknownDiagramError } from './errors.js';
import type { InternalHelpers } from './internals.js';
import { log } from './logger.js';
import { mermaidAPI } from './mermaidAPI.js';
import type { LayoutLoaderDefinition, RenderOptions } from './rendering-util/render.js';
import { registerLayoutLoaders } from './rendering-util/render.js'; import { registerLayoutLoaders } from './rendering-util/render.js';
import type { LayoutLoaderDefinition } from './rendering-util/render.js';
import { internalHelpers } from './internals.js';
import type { LayoutData } from './rendering-util/types.js'; import type { LayoutData } from './rendering-util/types.js';
import type { ParseOptions, ParseResult, RenderResult } from './types.js';
import type { DetailedError } from './utils.js';
import utils, { isDetailedError } from './utils.js';
export type { export type {
MermaidConfig,
DetailedError, DetailedError,
ExternalDiagramDefinition, ExternalDiagramDefinition,
InternalHelpers,
LayoutData,
LayoutLoaderDefinition,
MermaidConfig,
ParseErrorFunction, ParseErrorFunction,
RenderResult,
ParseOptions, ParseOptions,
ParseResult, ParseResult,
RenderOptions,
RenderResult,
SVG,
SVGGroup,
UnknownDiagramError, UnknownDiagramError,
LayoutLoaderDefinition,
LayoutData,
}; };
export interface RunOptions { export interface RunOptions {
@@ -432,11 +435,6 @@ export interface Mermaid {
contentLoaded: typeof contentLoaded; contentLoaded: typeof contentLoaded;
setParseErrorHandler: typeof setParseErrorHandler; setParseErrorHandler: typeof setParseErrorHandler;
detectType: typeof detectType; detectType: typeof detectType;
/**
* Internal helpers for mermaid
* @deprecated - This should not be used by external packages, as the definitions will change without notice.
*/
internalHelpers: typeof internalHelpers;
} }
const mermaid: Mermaid = { const mermaid: Mermaid = {
@@ -453,7 +451,6 @@ const mermaid: Mermaid = {
contentLoaded, contentLoaded,
setParseErrorHandler, setParseErrorHandler,
detectType, detectType,
internalHelpers,
}; };
export default mermaid; export default mermaid;

View File

@@ -1,16 +1,16 @@
/* eslint-disable @typescript-eslint/no-explicit-any */ /* eslint-disable @typescript-eslint/no-explicit-any */
// @ts-nocheck TODO: Fix types // @ts-nocheck TODO: Fix types
import type { MermaidConfig } from '../config.type.js'; import { getConfig } from '$root/diagram-api/diagramAPI.js';
import type { Group } from '../diagram-api/types.js'; import common, { hasKatex, renderKatex } from '$root/diagrams/common/common.js';
import { select } from 'd3'; import { select } from 'd3';
import type { MermaidConfig } from '../config.type.js';
import type { SVGGroup } from '../diagram-api/types.js';
import type { D3TSpanElement, D3TextElement } from '../diagrams/common/commonTypes.js'; import type { D3TSpanElement, D3TextElement } from '../diagrams/common/commonTypes.js';
import { log } from '../logger.js'; import { log } from '../logger.js';
import { markdownToHTML, markdownToLines } from '../rendering-util/handle-markdown-text.js'; import { markdownToHTML, markdownToLines } from '../rendering-util/handle-markdown-text.js';
import { decodeEntities } from '../utils.js'; import { decodeEntities } from '../utils.js';
import { splitLineToFitWidth } from './splitText.js'; import { splitLineToFitWidth } from './splitText.js';
import type { MarkdownLine, MarkdownWord } from './types.js'; import type { MarkdownLine, MarkdownWord } from './types.js';
import common, { hasKatex, renderKatex } from '$root/diagrams/common/common.js';
import { getConfig } from '$root/diagram-api/diagramAPI.js';
function applyStyle(dom, styleFn) { function applyStyle(dom, styleFn) {
if (styleFn) { if (styleFn) {
@@ -82,7 +82,7 @@ function computeWidthOfText(parentNode: any, lineHeight: number, line: MarkdownL
} }
export function computeDimensionOfText( export function computeDimensionOfText(
parentNode: Group, parentNode: SVGGroup,
lineHeight: number, lineHeight: number,
text: string text: string
): DOMRect | undefined { ): DOMRect | undefined {

View File

@@ -1,7 +1,21 @@
import type { SVG } from '$root/diagram-api/types.js';
import type { InternalHelpers } from '$root/internals.js';
import { internalHelpers } from '$root/internals.js';
import { log } from '$root/logger.js'; import { log } from '$root/logger.js';
import type { LayoutData } from './types.js';
export interface RenderOptions {
algorithm?: string;
}
export interface LayoutAlgorithm { export interface LayoutAlgorithm {
render(data4Layout: any, svg: any, element: any, algorithm?: string): any; render(
layoutData: LayoutData,
svg: SVG,
element: any,
helpers: InternalHelpers,
options?: RenderOptions
): Promise<void>;
} }
export type LayoutLoader = () => Promise<LayoutAlgorithm>; export type LayoutLoader = () => Promise<LayoutAlgorithm>;
@@ -31,14 +45,16 @@ const registerDefaultLayoutLoaders = () => {
registerDefaultLayoutLoaders(); registerDefaultLayoutLoaders();
export const render = async (data4Layout: any, svg: any, element: any) => { export const render = async (data4Layout: LayoutData, svg: SVG, element: any) => {
if (!(data4Layout.layoutAlgorithm in layoutAlgorithms)) { if (!(data4Layout.layoutAlgorithm in layoutAlgorithms)) {
throw new Error(`Unknown layout algorithm: ${data4Layout.layoutAlgorithm}`); throw new Error(`Unknown layout algorithm: ${data4Layout.layoutAlgorithm}`);
} }
const layoutDefinition = layoutAlgorithms[data4Layout.layoutAlgorithm]; const layoutDefinition = layoutAlgorithms[data4Layout.layoutAlgorithm];
const layoutRenderer = await layoutDefinition.loader(); const layoutRenderer = await layoutDefinition.loader();
return layoutRenderer.render(data4Layout, svg, element, layoutDefinition.algorithm); return layoutRenderer.render(data4Layout, svg, element, internalHelpers, {
algorithm: layoutDefinition.algorithm,
});
}; };
/** /**

View File

@@ -538,6 +538,27 @@ export const insertEdge = function (elem, edge, clusterDb, diagramType, startNod
.attr('style', edgeStyles ? edgeStyles.reduce((acc, style) => acc + ';' + style, '') : ''); .attr('style', edgeStyles ? edgeStyles.reduce((acc, style) => acc + ';' + style, '') : '');
} }
// DEBUG code, DO NOT REMOVE
// adds a red circle at each edge coordinate
// cornerPoints.forEach((point) => {
// elem
// .append('circle')
// .style('stroke', 'blue')
// .style('fill', 'blue')
// .attr('r', 3)
// .attr('cx', point.x)
// .attr('cy', point.y);
// });
// lineData.forEach((point) => {
// elem
// .append('circle')
// .style('stroke', 'blue')
// .style('fill', 'blue')
// .attr('r', 3)
// .attr('cx', point.x)
// .attr('cy', point.y);
// });
let url = ''; let url = '';
if (getConfig().flowchart.arrowMarkerAbsolute || getConfig().state.arrowMarkerAbsolute) { if (getConfig().flowchart.arrowMarkerAbsolute || getConfig().state.arrowMarkerAbsolute) {
url = url =

View File

@@ -118,7 +118,7 @@ properties:
- NETWORK_SIMPLEX - NETWORK_SIMPLEX
- LINEAR_SEGMENTS - LINEAR_SEGMENTS
- BRANDES_KOEPF - BRANDES_KOEPF
default: SIMPLE default: BRANDES_KOEPF
darkMode: darkMode:
type: boolean type: boolean
default: false default: false

4
pnpm-lock.yaml generated
View File

@@ -412,6 +412,10 @@ importers:
mermaid: mermaid:
specifier: workspace:^ specifier: workspace:^
version: link:../mermaid version: link:../mermaid
devDependencies:
'@types/d3':
specifier: ^7.4.3
version: 7.4.3
packages/mermaid-zenuml: packages/mermaid-zenuml:
dependencies: dependencies: