Compare commits

..

8 Commits

Author SHA1 Message Date
darshanr0107
9fdd34c55c fix: move mindmap icons logic into a separate file
on-behalf-of: @Mermaid-Chart <hello@mermaidchart.com>
2025-10-03 16:28:25 +05:30
darshanr0107
81a43e3d7c fix: node label positioning in mindmap nodes
on-behalf-of: @Mermaid-Chart <hello@mermaidchart.com>
2025-10-01 17:00:56 +05:30
darshanr0107
9a4dc563ed Merge branch 'mindmap-node-icons' of https://github.com/mermaid-js/mermaid into mindmap-node-icons 2025-10-01 11:47:32 +05:30
darshanr0107
9266ea2673 chore: fix roughjs imports
on-behalf-of: @Mermaid-Chart <hello@mermaidchart.com>
2025-10-01 11:47:00 +05:30
darshanr0107
b48b2a60f5 Merge branch 'develop' into mindmap-node-icons 2025-10-01 11:34:33 +05:30
autofix-ci[bot]
f1e64cd175 [autofix.ci] apply automated fixes 2025-09-30 14:30:01 +00:00
darshanr0107
132b028f94 fix: CI issues
on-behalf-of: @Mermaid-Chart <hello@mermaidchart.com>
2025-09-30 19:54:27 +05:30
darshanr0107
39d9c0212a fix: add support for icons in mindmap nodes
on-behalf-of: @Mermaid-Chart <hello@mermaidchart.com>
2025-09-30 19:19:17 +05:30
45 changed files with 902 additions and 885 deletions

View File

@@ -1,5 +0,0 @@
---
'mermaid': patch
---
fix: Support edge animation in hand drawn look

View File

@@ -1,5 +0,0 @@
---
'mermaid': patch
---
fix: Resolved parsing error where direction TD was not recognized within subgraphs

View File

@@ -1,5 +0,0 @@
---
'mermaid': patch
---
fix: Correct viewBox casing and make SVGs responsive

View File

@@ -1,5 +0,0 @@
---
'mermaid': patch
---
fix: Improve participant parsing and prevent recursive loops on invalid syntax

View File

@@ -1,5 +0,0 @@
---
'mermaid': minor
---
feat: allow to put notes in namespaces on classDiagram

View File

@@ -5,7 +5,7 @@ USER 0:0
RUN corepack enable \ RUN corepack enable \
&& corepack enable pnpm && corepack enable pnpm
RUN apk add --no-cache git~=2.43 \ RUN apk add --no-cache git~=2.43.4 \
&& git config --add --system safe.directory /mermaid && git config --add --system safe.directory /mermaid
ENV NODE_OPTIONS="--max_old_space_size=8192" ENV NODE_OPTIONS="--max_old_space_size=8192"

View File

@@ -6,7 +6,6 @@ interface CypressConfig {
listUrl?: boolean; listUrl?: boolean;
listId?: string; listId?: string;
name?: string; name?: string;
screenshot?: boolean;
} }
type CypressMermaidConfig = MermaidConfig & CypressConfig; type CypressMermaidConfig = MermaidConfig & CypressConfig;
@@ -91,7 +90,7 @@ export const renderGraph = (
export const openURLAndVerifyRendering = ( export const openURLAndVerifyRendering = (
url: string, url: string,
{ screenshot = true, ...options }: CypressMermaidConfig, options: CypressMermaidConfig,
validation?: any validation?: any
): void => { ): void => {
const name: string = (options.name ?? cy.state('runnable').fullTitle()).replace(/\s+/g, '-'); const name: string = (options.name ?? cy.state('runnable').fullTitle()).replace(/\s+/g, '-');
@@ -99,15 +98,12 @@ export const openURLAndVerifyRendering = (
cy.visit(url); cy.visit(url);
cy.window().should('have.property', 'rendered', true); cy.window().should('have.property', 'rendered', true);
cy.get('svg').should('be.visible'); cy.get('svg').should('be.visible');
cy.get('svg').should('not.have.attr', 'viewbox');
if (validation) { if (validation) {
cy.get('svg').should(validation); cy.get('svg').should(validation);
} }
if (screenshot) {
verifyScreenshot(name); verifyScreenshot(name);
}
}; };
export const verifyScreenshot = (name: string): void => { export const verifyScreenshot = (name: string): void => {

View File

@@ -562,20 +562,6 @@ class C13["With Città foreign language"]
` `
); );
}); });
it('should add notes in namespaces', function () {
imgSnapshotTest(
`
classDiagram
note "This is a outer note"
note for C1 "This is a outer note for C1"
namespace Namespace1 {
note "This is a inner note"
note for C1 "This is a inner note for C1"
class C1
}
`
);
});
it('should render a simple class diagram with no members', () => { it('should render a simple class diagram with no members', () => {
imgSnapshotTest( imgSnapshotTest(
` `

View File

@@ -709,20 +709,6 @@ class C13["With Città foreign language"]
` `
); );
}); });
it('should add notes in namespaces', function () {
imgSnapshotTest(
`
classDiagram
note "This is a outer note"
note for C1 "This is a outer note for C1"
namespace Namespace1 {
note "This is a inner note"
note for C1 "This is a inner note for C1"
class C1
}
`
);
});
it('should render a simple class diagram with no members', () => { it('should render a simple class diagram with no members', () => {
imgSnapshotTest( imgSnapshotTest(
` `

View File

@@ -1029,19 +1029,4 @@ graph TD
} }
); );
}); });
it('FDH49: should add edge animation', () => {
renderGraph(
`
flowchart TD
A(["Start"]) L_A_B_0@--> B{"Decision"}
B --> C["Option A"] & D["Option B"]
style C stroke-width:4px,stroke-dasharray: 5
L_A_B_0@{ animation: slow }
L_B_D_0@{ animation: fast }`,
{ look: 'handDrawn', screenshot: false }
);
cy.get('path#L_A_B_0').should('have.class', 'edge-animation-slow');
cy.get('path#L_B_D_0').should('have.class', 'edge-animation-fast');
});
}); });

View File

@@ -774,21 +774,6 @@ describe('Graph', () => {
expect(svg).to.not.have.attr('style'); expect(svg).to.not.have.attr('style');
}); });
}); });
it('40: should add edge animation', () => {
renderGraph(
`
flowchart TD
A(["Start"]) L_A_B_0@--> B{"Decision"}
B --> C["Option A"] & D["Option B"]
style C stroke-width:4px,stroke-dasharray: 5
L_A_B_0@{ animation: slow }
L_B_D_0@{ animation: fast }`,
{ screenshot: false }
);
// Verify animation classes are applied to both edges
cy.get('path#L_A_B_0').should('have.class', 'edge-animation-slow');
cy.get('path#L_B_D_0').should('have.class', 'edge-animation-fast');
});
it('58: handle styling with style expressions', () => { it('58: handle styling with style expressions', () => {
imgSnapshotTest( imgSnapshotTest(
` `
@@ -988,19 +973,4 @@ graph TD
} }
); );
}); });
it('70: should render a subgraph with direction TD', () => {
imgSnapshotTest(
`
flowchart LR
subgraph A
direction TD
a --> b
end
`,
{
fontFamily: 'courier',
}
);
});
}); });

View File

@@ -6,6 +6,14 @@
href="https://fonts.googleapis.com/css?family=Noto+Sans+SC&display=swap" href="https://fonts.googleapis.com/css?family=Noto+Sans+SC&display=swap"
rel="stylesheet" rel="stylesheet"
/> />
<link
rel="stylesheet"
href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.7.2/css/all.min.css"
/>
<link
href="https://cdn.jsdelivr.net/npm/@mdi/font@6.9.96/css/materialdesignicons.min.css"
rel="stylesheet"
/>
<style> <style>
svg:not(svg svg) { svg:not(svg svg) {
border: 2px solid darkred; border: 2px solid darkred;

View File

@@ -603,10 +603,6 @@
</div> </div>
<div class="test"> <div class="test">
<pre class="mermaid"> <pre class="mermaid">
---
config:
theme: dark
---
classDiagram classDiagram
test ()--() test2 test ()--() test2
</pre> </pre>

View File

@@ -184,7 +184,6 @@
} }
Admin --> Report : generates Admin --> Report : generates
</pre> </pre>
<hr />
<pre class="mermaid"> <pre class="mermaid">
classDiagram classDiagram
namespace Company.Project.Module { namespace Company.Project.Module {
@@ -241,20 +240,6 @@
Bike --> Square : "Logo Shape" Bike --> Square : "Logo Shape"
</pre> </pre>
<hr />
<pre class="mermaid">
classDiagram
note "This is a outer note"
note for Class1 "This is a outer note for Class1"
namespace ns {
note "This is a inner note"
note for Class1 "This is a inner note for Class1"
class Class1
class Class2
}
</pre>
<hr />
<script type="module"> <script type="module">
import mermaid from './mermaid.esm.mjs'; import mermaid from './mermaid.esm.mjs';
mermaid.initialize({ mermaid.initialize({

View File

@@ -10,7 +10,7 @@
# Interface: LayoutData # Interface: LayoutData
Defined in: [packages/mermaid/src/rendering-util/types.ts:168](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/rendering-util/types.ts#L168) Defined in: [packages/mermaid/src/rendering-util/types.ts:169](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/rendering-util/types.ts#L169)
## Indexable ## Indexable
@@ -22,7 +22,7 @@ Defined in: [packages/mermaid/src/rendering-util/types.ts:168](https://github.co
> **config**: [`MermaidConfig`](MermaidConfig.md) > **config**: [`MermaidConfig`](MermaidConfig.md)
Defined in: [packages/mermaid/src/rendering-util/types.ts:171](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/rendering-util/types.ts#L171) Defined in: [packages/mermaid/src/rendering-util/types.ts:172](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/rendering-util/types.ts#L172)
--- ---
@@ -30,7 +30,7 @@ Defined in: [packages/mermaid/src/rendering-util/types.ts:171](https://github.co
> **edges**: `Edge`\[] > **edges**: `Edge`\[]
Defined in: [packages/mermaid/src/rendering-util/types.ts:170](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/rendering-util/types.ts#L170) Defined in: [packages/mermaid/src/rendering-util/types.ts:171](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/rendering-util/types.ts#L171)
--- ---
@@ -38,4 +38,4 @@ Defined in: [packages/mermaid/src/rendering-util/types.ts:170](https://github.co
> **nodes**: `Node`\[] > **nodes**: `Node`\[]
Defined in: [packages/mermaid/src/rendering-util/types.ts:169](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/rendering-util/types.ts#L169) Defined in: [packages/mermaid/src/rendering-util/types.ts:170](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/rendering-util/types.ts#L170)

View File

@@ -21,7 +21,7 @@ title: Animal example
classDiagram classDiagram
note "From Duck till Zebra" note "From Duck till Zebra"
Animal <|-- Duck Animal <|-- Duck
note for Duck "can fly<br>can swim<br>can dive<br>can help in debugging" note for Duck "can fly\ncan swim\ncan dive\ncan help in debugging"
Animal <|-- Fish Animal <|-- Fish
Animal <|-- Zebra Animal <|-- Zebra
Animal : +int age Animal : +int age
@@ -50,7 +50,7 @@ title: Animal example
classDiagram classDiagram
note "From Duck till Zebra" note "From Duck till Zebra"
Animal <|-- Duck Animal <|-- Duck
note for Duck "can fly<br>can swim<br>can dive<br>can help in debugging" note for Duck "can fly\ncan swim\ncan dive\ncan help in debugging"
Animal <|-- Fish Animal <|-- Fish
Animal <|-- Zebra Animal <|-- Zebra
Animal : +int age Animal : +int age

View File

@@ -64,10 +64,10 @@
}, },
"devDependencies": { "devDependencies": {
"@applitools/eyes-cypress": "^3.55.2", "@applitools/eyes-cypress": "^3.55.2",
"@argos-ci/cypress": "^6.1.3", "@argos-ci/cypress": "^6.1.1",
"@changesets/changelog-github": "^0.5.1", "@changesets/changelog-github": "^0.5.1",
"@changesets/cli": "^2.29.7", "@changesets/cli": "^2.29.7",
"@cspell/eslint-plugin": "^9.2.2", "@cspell/eslint-plugin": "^8.19.4",
"@cypress/code-coverage": "^3.14.6", "@cypress/code-coverage": "^3.14.6",
"@eslint/js": "^9.26.0", "@eslint/js": "^9.26.0",
"@rollup/plugin-typescript": "^12.1.4", "@rollup/plugin-typescript": "^12.1.4",
@@ -95,16 +95,16 @@
"esbuild": "^0.25.10", "esbuild": "^0.25.10",
"eslint": "^9.26.0", "eslint": "^9.26.0",
"eslint-config-prettier": "^10.1.8", "eslint-config-prettier": "^10.1.8",
"eslint-plugin-cypress": "^5.2.0", "eslint-plugin-cypress": "^4.3.0",
"eslint-plugin-html": "^8.1.3", "eslint-plugin-html": "^8.1.3",
"eslint-plugin-jest": "^29.0.1", "eslint-plugin-jest": "^28.14.0",
"eslint-plugin-jsdoc": "^61.1.9", "eslint-plugin-jsdoc": "^50.8.0",
"eslint-plugin-json": "^4.0.1", "eslint-plugin-json": "^4.0.1",
"eslint-plugin-lodash": "^8.0.0", "eslint-plugin-lodash": "^8.0.0",
"eslint-plugin-markdown": "^5.1.0", "eslint-plugin-markdown": "^5.1.0",
"eslint-plugin-no-only-tests": "^3.3.0", "eslint-plugin-no-only-tests": "^3.3.0",
"eslint-plugin-tsdoc": "^0.4.0", "eslint-plugin-tsdoc": "^0.4.0",
"eslint-plugin-unicorn": "^62.0.0", "eslint-plugin-unicorn": "^59.0.1",
"express": "^5.1.0", "express": "^5.1.0",
"globals": "^16.4.0", "globals": "^16.4.0",
"globby": "^14.1.0", "globby": "^14.1.0",

View File

@@ -17,7 +17,6 @@ import type {
ClassRelation, ClassRelation,
ClassNode, ClassNode,
ClassNote, ClassNote,
ClassNoteMap,
ClassMap, ClassMap,
NamespaceMap, NamespaceMap,
NamespaceNode, NamespaceNode,
@@ -34,16 +33,15 @@ const sanitizeText = (txt: string) => common.sanitizeText(txt, getConfig());
export class ClassDB implements DiagramDB { export class ClassDB implements DiagramDB {
private relations: ClassRelation[] = []; private relations: ClassRelation[] = [];
private classes: ClassMap = new Map<string, ClassNode>(); private classes = new Map<string, ClassNode>();
private readonly styleClasses = new Map<string, StyleClass>(); private readonly styleClasses = new Map<string, StyleClass>();
private notes: ClassNoteMap = new Map<string, ClassNote>(); private notes: ClassNote[] = [];
private interfaces: Interface[] = []; private interfaces: Interface[] = [];
// private static classCounter = 0; // private static classCounter = 0;
private namespaces = new Map<string, NamespaceNode>(); private namespaces = new Map<string, NamespaceNode>();
private namespaceCounter = 0; private namespaceCounter = 0;
// eslint-disable-next-line @typescript-eslint/no-unsafe-function-type private functions: any[] = [];
private functions: Function[] = [];
constructor() { constructor() {
this.functions.push(this.setupToolTips.bind(this)); this.functions.push(this.setupToolTips.bind(this));
@@ -126,7 +124,7 @@ export class ClassDB implements DiagramDB {
annotations: [], annotations: [],
styles: [], styles: [],
domId: MERMAID_DOM_ID_PREFIX + name + '-' + classCounter, domId: MERMAID_DOM_ID_PREFIX + name + '-' + classCounter,
}); } as ClassNode);
classCounter++; classCounter++;
} }
@@ -157,12 +155,12 @@ export class ClassDB implements DiagramDB {
public clear() { public clear() {
this.relations = []; this.relations = [];
this.classes = new Map<string, ClassNode>(); this.classes = new Map();
this.notes = new Map<string, ClassNote>(); this.notes = [];
this.interfaces = []; this.interfaces = [];
this.functions = []; this.functions = [];
this.functions.push(this.setupToolTips.bind(this)); this.functions.push(this.setupToolTips.bind(this));
this.namespaces = new Map<string, NamespaceNode>(); this.namespaces = new Map();
this.namespaceCounter = 0; this.namespaceCounter = 0;
this.direction = 'TB'; this.direction = 'TB';
commonClear(); commonClear();
@@ -180,12 +178,7 @@ export class ClassDB implements DiagramDB {
return this.relations; return this.relations;
} }
public getNote(id: string | number): ClassNote { public getNotes() {
const key = typeof id === 'number' ? `note${id}` : id;
return this.notes.get(key)!;
}
public getNotes(): ClassNoteMap {
return this.notes; return this.notes;
} }
@@ -286,19 +279,16 @@ export class ClassDB implements DiagramDB {
} }
} }
public addNote(text: string, className: string): string { public addNote(text: string, className: string) {
const index = this.notes.size;
const note = { const note = {
id: `note${index}`, id: `note${this.notes.length}`,
class: className, class: className,
text: text, text: text,
index: index,
}; };
this.notes.set(note.id, note); this.notes.push(note);
return note.id;
} }
public cleanupLabel(label: string): string { public cleanupLabel(label: string) {
if (label.startsWith(':')) { if (label.startsWith(':')) {
label = label.substring(1); label = label.substring(1);
} }
@@ -364,7 +354,7 @@ export class ClassDB implements DiagramDB {
}); });
} }
public getTooltip(id: string, namespace?: string): string | undefined { public getTooltip(id: string, namespace?: string) {
if (namespace && this.namespaces.has(namespace)) { if (namespace && this.namespaces.has(namespace)) {
return this.namespaces.get(namespace)!.classes.get(id)!.tooltip; return this.namespaces.get(namespace)!.classes.get(id)!.tooltip;
} }
@@ -544,11 +534,10 @@ export class ClassDB implements DiagramDB {
this.namespaces.set(id, { this.namespaces.set(id, {
id: id, id: id,
classes: new Map<string, ClassNode>(), classes: new Map(),
notes: new Map<string, ClassNote>(), children: {},
children: new Map<string, NamespaceNode>(),
domId: MERMAID_DOM_ID_PREFIX + id + '-' + this.namespaceCounter, domId: MERMAID_DOM_ID_PREFIX + id + '-' + this.namespaceCounter,
}); } as NamespaceNode);
this.namespaceCounter++; this.namespaceCounter++;
} }
@@ -566,23 +555,16 @@ export class ClassDB implements DiagramDB {
* *
* @param id - ID of the namespace to add * @param id - ID of the namespace to add
* @param classNames - IDs of the class to add * @param classNames - IDs of the class to add
* @param noteNames - IDs of the notes to add
* @public * @public
*/ */
public addClassesToNamespace(id: string, classNames: string[], noteNames: string[]) { public addClassesToNamespace(id: string, classNames: string[]) {
if (!this.namespaces.has(id)) { if (!this.namespaces.has(id)) {
return; return;
} }
for (const name of classNames) { for (const name of classNames) {
const { className } = this.splitClassNameAndType(name); const { className } = this.splitClassNameAndType(name);
const classNode = this.getClass(className); this.classes.get(className)!.parent = id;
classNode.parent = id; this.namespaces.get(id)!.classes.set(className, this.classes.get(className)!);
this.namespaces.get(id)!.classes.set(className, classNode);
}
for (const noteName of noteNames) {
const noteNode = this.getNote(noteName);
noteNode.parent = id;
this.namespaces.get(id)!.notes.set(noteName, noteNode);
} }
} }
@@ -635,7 +617,9 @@ export class ClassDB implements DiagramDB {
const edges: Edge[] = []; const edges: Edge[] = [];
const config = getConfig(); const config = getConfig();
for (const namespace of this.namespaces.values()) { for (const namespaceKey of this.namespaces.keys()) {
const namespace = this.namespaces.get(namespaceKey);
if (namespace) {
const node: Node = { const node: Node = {
id: namespace.id, id: namespace.id,
label: namespace.id, label: namespace.id,
@@ -643,24 +627,26 @@ export class ClassDB implements DiagramDB {
padding: config.class!.padding ?? 16, padding: config.class!.padding ?? 16,
// parent node must be one of [rect, roundedWithTitle, noteGroup, divider] // parent node must be one of [rect, roundedWithTitle, noteGroup, divider]
shape: 'rect', shape: 'rect',
cssStyles: [], cssStyles: ['fill: none', 'stroke: black'],
look: config.look, look: config.look,
}; };
nodes.push(node); nodes.push(node);
} }
for (const classNode of this.classes.values()) {
const node: Node = {
...classNode,
type: undefined,
isGroup: false,
parentId: classNode.parent,
look: config.look,
};
nodes.push(node);
} }
for (const note of this.notes.values()) { for (const classKey of this.classes.keys()) {
const classNode = this.classes.get(classKey);
if (classNode) {
const node = classNode as unknown as Node;
node.parentId = classNode.parent;
node.look = config.look;
nodes.push(node);
}
}
let cnt = 0;
for (const note of this.notes) {
cnt++;
const noteNode: Node = { const noteNode: Node = {
id: note.id, id: note.id,
label: note.text, label: note.text,
@@ -674,15 +660,14 @@ export class ClassDB implements DiagramDB {
`stroke: ${config.themeVariables.noteBorderColor}`, `stroke: ${config.themeVariables.noteBorderColor}`,
], ],
look: config.look, look: config.look,
parentId: note.parent,
}; };
nodes.push(noteNode); nodes.push(noteNode);
const noteClassId = this.classes.get(note.class)?.id; const noteClassId = this.classes.get(note.class)?.id ?? '';
if (noteClassId) { if (noteClassId) {
const edge: Edge = { const edge: Edge = {
id: `edgeNote${note.index}`, id: `edgeNote${cnt}`,
start: note.id, start: note.id,
end: noteClassId, end: noteClassId,
type: 'normal', type: 'normal',
@@ -712,7 +697,7 @@ export class ClassDB implements DiagramDB {
nodes.push(interfaceNode); nodes.push(interfaceNode);
} }
let cnt = 0; cnt = 0;
for (const classRelation of this.relations) { for (const classRelation of this.relations) {
cnt++; cnt++;
const edge: Edge = { const edge: Edge = {

View File

@@ -417,7 +417,7 @@ class C13["With Città foreign language"]
note "This is a keyword: ${keyword}. It truly is." note "This is a keyword: ${keyword}. It truly is."
`; `;
parser.parse(str); parser.parse(str);
expect(classDb.getNote(0).text).toEqual(`This is a keyword: ${keyword}. It truly is.`); expect(classDb.getNotes()[0].text).toEqual(`This is a keyword: ${keyword}. It truly is.`);
}); });
it.each(keywords)( it.each(keywords)(
@@ -427,7 +427,7 @@ class C13["With Città foreign language"]
note "${keyword}"`; note "${keyword}"`;
parser.parse(str); parser.parse(str);
expect(classDb.getNote(0).text).toEqual(`${keyword}`); expect(classDb.getNotes()[0].text).toEqual(`${keyword}`);
} }
); );
@@ -441,7 +441,7 @@ class C13["With Città foreign language"]
`; `;
parser.parse(str); parser.parse(str);
expect(classDb.getNote(0).text).toEqual(`This is a keyword: ${keyword}. It truly is.`); expect(classDb.getNotes()[0].text).toEqual(`This is a keyword: ${keyword}. It truly is.`);
}); });
it.each(keywords)( it.each(keywords)(
@@ -456,7 +456,7 @@ class C13["With Città foreign language"]
`; `;
parser.parse(str); parser.parse(str);
expect(classDb.getNote(0).text).toEqual(`${keyword}`); expect(classDb.getNotes()[0].text).toEqual(`${keyword}`);
} }
); );

View File

@@ -8,7 +8,7 @@ import utils, { getEdgeId } from '../../utils.js';
import { interpolateToCurve, getStylesFromArray } from '../../utils.js'; import { interpolateToCurve, getStylesFromArray } from '../../utils.js';
import { setupGraphViewbox } from '../../setupGraphViewbox.js'; import { setupGraphViewbox } from '../../setupGraphViewbox.js';
import common from '../common/common.js'; import common from '../common/common.js';
import type { ClassRelation, ClassMap, ClassNoteMap, NamespaceMap } from './classTypes.js'; import type { ClassRelation, ClassNote, ClassMap, NamespaceMap } from './classTypes.js';
import type { EdgeData } from '../../types.js'; import type { EdgeData } from '../../types.js';
const sanitizeText = (txt: string) => common.sanitizeText(txt, getConfig()); const sanitizeText = (txt: string) => common.sanitizeText(txt, getConfig());
@@ -65,9 +65,6 @@ export const addNamespaces = function (
g.setNode(vertex.id, node); g.setNode(vertex.id, node);
addClasses(vertex.classes, g, _id, diagObj, vertex.id); addClasses(vertex.classes, g, _id, diagObj, vertex.id);
const classes: ClassMap = diagObj.db.getClasses();
const relations: ClassRelation[] = diagObj.db.getRelations();
addNotes(vertex.notes, g, relations.length + 1, classes, vertex.id);
log.info('setNode', node); log.info('setNode', node);
}); });
@@ -147,17 +144,16 @@ export const addClasses = function (
* @param classes - Classes * @param classes - Classes
*/ */
export const addNotes = function ( export const addNotes = function (
notes: ClassNoteMap, notes: ClassNote[],
g: graphlib.Graph, g: graphlib.Graph,
startEdgeId: number, startEdgeId: number,
classes: ClassMap, classes: ClassMap
parent?: string
) { ) {
log.info(notes); log.info(notes);
[...notes.values()] notes.forEach(function (note, i) {
.filter((note) => note.parent === parent) const vertex = note;
.forEach(function (vertex) {
const cssNoteStr = ''; const cssNoteStr = '';
const styles = { labelStyle: '', style: '' }; const styles = { labelStyle: '', style: '' };
@@ -185,14 +181,10 @@ export const addNotes = function (
g.setNode(vertex.id, node); g.setNode(vertex.id, node);
log.info('setNode', node); log.info('setNode', node);
if (parent) {
g.setParent(vertex.id, parent);
}
if (!vertex.class || !classes.has(vertex.class)) { if (!vertex.class || !classes.has(vertex.class)) {
return; return;
} }
const edgeId = startEdgeId + vertex.index; const edgeId = startEdgeId + i;
const edgeData: EdgeData = { const edgeData: EdgeData = {
id: `edgeNote${edgeId}`, id: `edgeNote${edgeId}`,
@@ -337,7 +329,7 @@ export const draw = async function (text: string, id: string, _version: string,
const namespaces: NamespaceMap = diagObj.db.getNamespaces(); const namespaces: NamespaceMap = diagObj.db.getNamespaces();
const classes: ClassMap = diagObj.db.getClasses(); const classes: ClassMap = diagObj.db.getClasses();
const relations: ClassRelation[] = diagObj.db.getRelations(); const relations: ClassRelation[] = diagObj.db.getRelations();
const notes: ClassNoteMap = diagObj.db.getNotes(); const notes: ClassNote[] = diagObj.db.getNotes();
log.info(relations); log.info(relations);
addNamespaces(namespaces, g, id, diagObj); addNamespaces(namespaces, g, id, diagObj);
addClasses(classes, g, id, diagObj); addClasses(classes, g, id, diagObj);

View File

@@ -206,7 +206,7 @@ export const draw = function (text, id, _version, diagObj) {
); );
}); });
const notes = diagObj.db.getNotes().values(); const notes = diagObj.db.getNotes();
notes.forEach(function (note) { notes.forEach(function (note) {
log.debug(`Adding note: ${JSON.stringify(note)}`); log.debug(`Adding note: ${JSON.stringify(note)}`);
const node = svgDraw.drawNote(diagram, note, conf, diagObj); const node = svgDraw.drawNote(diagram, note, conf, diagObj);

View File

@@ -5,7 +5,7 @@ export interface ClassNode {
id: string; id: string;
type: string; type: string;
label: string; label: string;
shape: 'classBox'; shape: string;
text: string; text: string;
cssClasses: string; cssClasses: string;
methods: ClassMember[]; methods: ClassMember[];
@@ -149,8 +149,6 @@ export interface ClassNote {
id: string; id: string;
class: string; class: string;
text: string; text: string;
index: number;
parent?: string;
} }
export interface ClassRelation { export interface ClassRelation {
@@ -179,7 +177,6 @@ export interface NamespaceNode {
id: string; id: string;
domId: string; domId: string;
classes: ClassMap; classes: ClassMap;
notes: ClassNoteMap;
children: NamespaceMap; children: NamespaceMap;
} }
@@ -190,5 +187,4 @@ export interface StyleClass {
} }
export type ClassMap = Map<string, ClassNode>; export type ClassMap = Map<string, ClassNode>;
export type ClassNoteMap = Map<string, ClassNote>;
export type NamespaceMap = Map<string, NamespaceNode>; export type NamespaceMap = Map<string, NamespaceNode>;

View File

@@ -275,8 +275,8 @@ statement
; ;
namespaceStatement namespaceStatement
: namespaceIdentifier STRUCT_START classStatements STRUCT_STOP { yy.addClassesToNamespace($1, $3[0], $3[1]); } : namespaceIdentifier STRUCT_START classStatements STRUCT_STOP { yy.addClassesToNamespace($1, $3); }
| namespaceIdentifier STRUCT_START NEWLINE classStatements STRUCT_STOP { yy.addClassesToNamespace($1, $4[0], $4[1]); } | namespaceIdentifier STRUCT_START NEWLINE classStatements STRUCT_STOP { yy.addClassesToNamespace($1, $4); }
; ;
namespaceIdentifier namespaceIdentifier
@@ -284,12 +284,9 @@ namespaceIdentifier
; ;
classStatements classStatements
: classStatement {$$=[[$1], []]} : classStatement {$$=[$1]}
| classStatement NEWLINE {$$=[[$1], []]} | classStatement NEWLINE {$$=[$1]}
| classStatement NEWLINE classStatements {$3[0].unshift($1); $$=$3} | classStatement NEWLINE classStatements {$3.unshift($1); $$=$3}
| noteStatement {$$=[[], [$1]]}
| noteStatement NEWLINE {$$=[[], [$1]]}
| noteStatement NEWLINE classStatements {$3[1].unshift($1); $$=$3}
; ;
classStatement classStatement
@@ -336,8 +333,8 @@ relationStatement
; ;
noteStatement noteStatement
: NOTE_FOR className noteText { $$ = yy.addNote($3, $2); } : NOTE_FOR className noteText { yy.addNote($3, $2); }
| NOTE noteText { $$ = yy.addNote($2); } | NOTE noteText { yy.addNote($2); }
; ;
classDefStatement classDefStatement

View File

@@ -13,30 +13,6 @@ const getStyles = (options) =>
} }
.cluster-label text {
fill: ${options.titleColor};
}
.cluster-label span {
color: ${options.titleColor};
}
.cluster-label span p {
background-color: transparent;
}
.cluster rect {
fill: ${options.clusterBkg};
stroke: ${options.clusterBorder};
stroke-width: 1px;
}
.cluster text {
fill: ${options.titleColor};
}
.cluster span {
color: ${options.titleColor};
}
.nodeLabel, .edgeLabel { .nodeLabel, .edgeLabel {
color: ${options.classText}; color: ${options.classText};
} }

View File

@@ -140,7 +140,6 @@ that id.
.*direction\s+BT[^\n]* return 'direction_bt'; .*direction\s+BT[^\n]* return 'direction_bt';
.*direction\s+RL[^\n]* return 'direction_rl'; .*direction\s+RL[^\n]* return 'direction_rl';
.*direction\s+LR[^\n]* return 'direction_lr'; .*direction\s+LR[^\n]* return 'direction_lr';
.*direction\s+TD[^\n]* return 'direction_td';
[^\s\"]+\@(?=[^\{\"]) { return 'LINK_ID'; } [^\s\"]+\@(?=[^\{\"]) { return 'LINK_ID'; }
[0-9]+ return 'NUM'; [0-9]+ return 'NUM';
@@ -627,8 +626,6 @@ direction
{ $$={stmt:'dir', value:'RL'};} { $$={stmt:'dir', value:'RL'};}
| direction_lr | direction_lr
{ $$={stmt:'dir', value:'LR'};} { $$={stmt:'dir', value:'LR'};}
| direction_td
{ $$={stmt:'dir', value:'TD'};}
; ;
%% %%

View File

@@ -309,21 +309,4 @@ describe('when parsing subgraphs', function () {
expect(subgraphA.nodes).toContain('a'); expect(subgraphA.nodes).toContain('a');
expect(subgraphA.nodes).not.toContain('c'); expect(subgraphA.nodes).not.toContain('c');
}); });
it('should correctly parse direction TD inside a subgraph', function () {
const res = flow.parser.parse(`
graph LR
subgraph WithTD
direction TD
A1 --> A2
end
`);
const subgraphs = flow.parser.yy.getSubGraphs();
expect(subgraphs.length).toBe(1);
const subgraph = subgraphs[0];
expect(subgraph.dir).toBe('TD');
expect(subgraph.nodes).toContain('A1');
expect(subgraph.nodes).toContain('A2');
});
}); });

View File

@@ -0,0 +1,222 @@
import { log } from '../../logger.js';
import type { D3Selection } from '../../types.js';
import type { Node } from '../../rendering-util/types.js';
import { getIconSVG, isIconAvailable } from '../../rendering-util/icons.js';
export interface MindmapIconConfig {
iconSize: number;
iconPadding: number;
shapeType: 'circle' | 'rect' | 'rounded' | 'bang' | 'cloud' | 'hexagon' | 'default';
}
export interface MindmapDimensions {
width: number;
height: number;
labelOffset: { x: number; y: number };
}
/**
* Get icon configuration for different mindmap shape types
*/
export function getMindmapIconConfig(shapeType: string): MindmapIconConfig {
const baseConfig = {
iconSize: 30,
iconPadding: 15,
shapeType: shapeType as MindmapIconConfig['shapeType'],
};
switch (shapeType) {
case 'bang':
return { ...baseConfig, iconPadding: 1 };
case 'rect':
case 'default':
return { ...baseConfig, iconPadding: 10 };
default:
return baseConfig;
}
}
/**
* Calculate dimensions and label positioning for mindmap nodes with icons
*/
export function calculateMindmapDimensions(
node: Node,
bbox: any,
baseWidth: number,
baseHeight: number,
basePadding: number,
config: MindmapIconConfig
): MindmapDimensions {
const hasIcon = Boolean(node.icon);
if (!hasIcon) {
return {
width: baseWidth,
height: baseHeight,
labelOffset: { x: -bbox.width / 2, y: -bbox.height / 2 },
};
}
const { iconSize, iconPadding, shapeType } = config;
let width = baseWidth;
let height = baseHeight;
let labelXOffset = -bbox.width / 2;
const labelYOffset = -bbox.height / 2;
switch (shapeType) {
case 'circle': {
const totalWidthNeeded = bbox.width + iconSize + iconPadding * 2;
const minRadiusWithIcon = totalWidthNeeded / 2 + basePadding;
const radius = Math.max(baseWidth / 2, minRadiusWithIcon);
width = radius * 2;
height = radius * 2;
labelXOffset = -radius + iconSize + iconPadding;
break;
}
case 'rect':
case 'rounded':
case 'default': {
const minWidthWithIcon = bbox.width + iconSize + iconPadding * 2 + basePadding * 2;
width = Math.max(baseWidth, minWidthWithIcon);
height = Math.max(baseHeight, iconSize + basePadding * 2);
const availableTextSpace = width - iconSize - iconPadding * 2;
labelXOffset = -width / 2 + iconSize + iconPadding + availableTextSpace / 2 - bbox.width / 2;
break;
}
case 'bang':
case 'cloud': {
const minWidthWithIcon = bbox.width + iconSize + iconPadding * 2 + basePadding;
width = Math.max(baseWidth, minWidthWithIcon);
height = Math.max(baseHeight, iconSize + basePadding);
const availableTextSpace = width - iconSize - iconPadding * 2;
labelXOffset = -width / 2 + iconSize + iconPadding + availableTextSpace / 2 - bbox.width / 2;
break;
}
default: {
const minWidthWithIcon = bbox.width + iconSize + iconPadding * 2 + basePadding * 2;
width = Math.max(baseWidth, minWidthWithIcon);
height = Math.max(baseHeight, iconSize + basePadding * 2);
const availableTextSpace = width - iconSize - iconPadding * 2;
labelXOffset = -width / 2 + iconSize + iconPadding + availableTextSpace / 2 - bbox.width / 2;
break;
}
}
return {
width,
height,
labelOffset: { x: labelXOffset, y: labelYOffset },
};
}
/**
* Insert mindmap icon into the shape SVG element
*/
export async function insertMindmapIcon(
parentElement: D3Selection<SVGGraphicsElement>,
node: Node,
config: MindmapIconConfig
): Promise<void> {
if (!node.icon) {
return;
}
const { iconSize, iconPadding, shapeType } = config;
const section = node.section ?? 0;
let iconName = node.icon;
const isCssFormat = iconName.includes(' ');
if (isCssFormat) {
iconName = iconName.replace(' ', ':');
}
try {
if (await isIconAvailable(iconName)) {
const iconSvg = await getIconSVG(
iconName,
{
height: iconSize,
width: iconSize,
},
{ class: 'label-icon' }
);
const iconElem = parentElement.append('g');
iconElem.html(`<g>${iconSvg}</g>`);
let iconX = 0;
let iconY = 0;
switch (shapeType) {
case 'circle': {
const nodeWidth = node.width || 100;
const radius = nodeWidth / 2;
iconX = -radius + iconSize / 2 + iconPadding;
iconY = 0;
break;
}
default: {
const nodeWidth = node.width || 100;
iconX = -nodeWidth / 2 + iconSize / 2 + iconPadding;
iconY = 0;
break;
}
}
iconElem.attr('transform', `translate(${iconX}, ${iconY})`);
iconElem.attr('style', 'color: currentColor;');
return;
}
} catch (error) {
log.debug('SVG icon rendering failed, falling back to CSS:', error);
}
// Fallback to CSS approach (original mindmap behavior)
const iconClass = isCssFormat ? node.icon : node.icon.replace(':', ' ');
let iconX = 0;
const iconY = -iconSize / 2;
switch (shapeType) {
case 'circle': {
const nodeWidth = node.width || 100;
const radius = nodeWidth / 2;
iconX = -radius + iconPadding;
break;
}
default: {
const nodeWidth = node.width || 100;
iconX = -nodeWidth / 2 + iconPadding;
break;
}
}
const icon = parentElement
.append('foreignObject')
.attr('height', `${iconSize}px`)
.attr('width', `${iconSize}px`)
.attr('x', iconX)
.attr('y', iconY)
.attr(
'style',
'text-align: center; display: flex; align-items: center; justify-content: center;'
);
icon
.append('div')
.attr('class', 'icon-container')
.attr(
'style',
'width: 100%; height: 100%; display: flex; align-items: center; justify-content: center;'
)
.append('i')
.attr('class', `node-icon-${section} ${iconClass}`)
.attr('style', `font-size: ${iconSize}px;`);
}

View File

@@ -7,6 +7,7 @@ import type { LayoutData } from '../../rendering-util/types.js';
import type { FilledMindMapNode } from './mindmapTypes.js'; import type { FilledMindMapNode } from './mindmapTypes.js';
import defaultConfig from '../../defaultConfig.js'; import defaultConfig from '../../defaultConfig.js';
import type { MindmapDB } from './mindmapDb.js'; import type { MindmapDB } from './mindmapDb.js';
import { getMindmapIconConfig, insertMindmapIcon } from './mindmapIconHelper.js';
/** /**
* Update the layout data with actual node dimensions after drawing * Update the layout data with actual node dimensions after drawing
@@ -71,6 +72,28 @@ export const draw: DrawDefinition = async (text, id, _version, diagObj) => {
// Use the unified rendering system // Use the unified rendering system
await render(data4Layout, svg); await render(data4Layout, svg);
const genericShapes = ['hexagon', 'rect', 'rounded', 'squareRect'];
const nodesWithIcons = data4Layout.nodes.filter(
(node) => node.icon && genericShapes.includes(node.shape || '')
);
if (nodesWithIcons.length > 0) {
for (const node of nodesWithIcons) {
const nodeId = node.domId || node.id;
const nodeElement = svg.select(`g[id="${nodeId}"]`);
if (!nodeElement.empty()) {
try {
const iconConfig = getMindmapIconConfig(node.shape || 'default');
await insertMindmapIcon(nodeElement, node, iconConfig);
} catch (error) {
log.warn(`Failed to add icon to ${nodeId}:`, error);
}
} else {
log.warn(`Could not find DOM element for node ${nodeId}`);
}
}
}
// Setup the view box and size of the svg element using config from data4Layout // Setup the view box and size of the svg element using config from data4Layout
setupViewPortForSVG( setupViewPortForSVG(

View File

@@ -16,7 +16,7 @@ const draw: DrawDefinition = (_text, id, _version, diagram: Diagram) => {
const svgWidth = bitWidth * bitsPerRow + 2; const svgWidth = bitWidth * bitsPerRow + 2;
const svg: SVG = selectSvgElement(id); const svg: SVG = selectSvgElement(id);
svg.attr('viewBox', `0 0 ${svgWidth} ${svgHeight}`); svg.attr('viewbox', `0 0 ${svgWidth} ${svgHeight}`);
configureSvgSize(svg, svgHeight, svgWidth, config.useMaxWidth); configureSvgSize(svg, svgHeight, svgWidth, config.useMaxWidth);
for (const [word, packet] of words.entries()) { for (const [word, packet] of words.entries()) {

View File

@@ -2,7 +2,6 @@ import type { Diagram } from '../../Diagram.js';
import type { RadarDiagramConfig } from '../../config.type.js'; import type { RadarDiagramConfig } from '../../config.type.js';
import type { DiagramRenderer, DrawDefinition, SVG, SVGGroup } 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 type { RadarDB, RadarAxis, RadarCurve } from './types.js'; import type { RadarDB, RadarAxis, RadarCurve } from './types.js';
const draw: DrawDefinition = (_text, id, _version, diagram: Diagram) => { const draw: DrawDefinition = (_text, id, _version, diagram: Diagram) => {
@@ -54,9 +53,11 @@ const drawFrame = (svg: SVG, config: Required<RadarDiagramConfig>): SVGGroup =>
x: config.marginLeft + config.width / 2, x: config.marginLeft + config.width / 2,
y: config.marginTop + config.height / 2, y: config.marginTop + config.height / 2,
}; };
configureSvgSize(svg, totalHeight, totalWidth, config.useMaxWidth ?? true); // Initialize the SVG
svg
svg.attr('viewBox', `0 0 ${totalWidth} ${totalHeight}`); .attr('viewbox', `0 0 ${totalWidth} ${totalHeight}`)
.attr('width', totalWidth)
.attr('height', totalHeight);
// g element to center the radar chart // g element to center the radar chart
return svg.append('g').attr('transform', `translate(${center.x}, ${center.y})`); return svg.append('g').attr('transform', `translate(${center.x}, ${center.y})`);
}; };

View File

@@ -32,14 +32,13 @@
<CONFIG>[^\}]+ { return 'CONFIG_CONTENT'; } <CONFIG>[^\}]+ { return 'CONFIG_CONTENT'; }
<CONFIG>\} { this.popState(); this.popState(); return 'CONFIG_END'; } <CONFIG>\} { this.popState(); this.popState(); return 'CONFIG_END'; }
<ID>[^\<->\->:\n,;@\s]+(?=\@\{) { yytext = yytext.trim(); return 'ACTOR'; } <ID>[^\<->\->:\n,;@\s]+(?=\@\{) { yytext = yytext.trim(); return 'ACTOR'; }
<ID>[^<>:\n,;@\s]+(?=\s+as\s) { yytext = yytext.trim(); this.begin('ALIAS'); return 'ACTOR'; } <ID>[^\<->\->:\n,;@]+?([\-]*[^\<->\->:\n,;@]+?)*?(?=((?!\n)\s)+"as"(?!\n)\s|[#\n;]|$) { yytext = yytext.trim(); this.begin('ALIAS'); return 'ACTOR'; }
<ID>[^<>:\n,;@]+(?=\s*[\n;#]|$) { yytext = yytext.trim(); this.popState(); return 'ACTOR'; }
<ID>[^<>:\n,;@]*\<[^\n]* { this.popState(); return 'INVALID'; }
"box" { this.begin('LINE'); return 'box'; } "box" { this.begin('LINE'); return 'box'; }
"participant" { this.begin('ID'); return 'participant'; } "participant" { this.begin('ID'); return 'participant'; }
"actor" { this.begin('ID'); return 'participant_actor'; } "actor" { this.begin('ID'); return 'participant_actor'; }
"create" return 'create'; "create" return 'create';
"destroy" { this.begin('ID'); return 'destroy'; } "destroy" { this.begin('ID'); return 'destroy'; }
<ID>[^<\->\->:\n,;]+?([\-]*[^<\->\->:\n,;]+?)*?(?=((?!\n)\s)+"as"(?!\n)\s|[#\n;]|$) { yytext = yytext.trim(); this.begin('ALIAS'); return 'ACTOR'; }
<ALIAS>"as" { this.popState(); this.popState(); this.begin('LINE'); return 'AS'; } <ALIAS>"as" { this.popState(); this.popState(); this.begin('LINE'); return 'AS'; }
<ALIAS>(?:) { this.popState(); this.popState(); return 'NEWLINE'; } <ALIAS>(?:) { this.popState(); this.popState(); return 'NEWLINE'; }
"loop" { this.begin('LINE'); return 'loop'; } "loop" { this.begin('LINE'); return 'loop'; }
@@ -146,7 +145,6 @@ line
: SPACE statement { $$ = $2 } : SPACE statement { $$ = $2 }
| statement { $$ = $1 } | statement { $$ = $1 }
| NEWLINE { $$=[]; } | NEWLINE { $$=[]; }
| INVALID { $$=[]; }
; ;
box_section box_section

View File

@@ -2609,17 +2609,5 @@ Bob->>Alice:Got it!
expect(actors.get('E').type).toBe('entity'); expect(actors.get('E').type).toBe('entity');
expect(actors.get('E').description).toBe('E'); expect(actors.get('E').description).toBe('E');
}); });
it('should handle fail parsing when alias token causes conflicts in participant definition', async () => {
let error = false;
try {
await Diagram.fromText(`
sequenceDiagram
participant SAS MyServiceWithMoreThan20Chars <br> service decription
`);
} catch (e) {
error = true;
}
expect(error).toBe(true);
});
}); });
}); });

View File

@@ -15,7 +15,7 @@ title: Animal example
classDiagram classDiagram
note "From Duck till Zebra" note "From Duck till Zebra"
Animal <|-- Duck Animal <|-- Duck
note for Duck "can fly<br>can swim<br>can dive<br>can help in debugging" note for Duck "can fly\ncan swim\ncan dive\ncan help in debugging"
Animal <|-- Fish Animal <|-- Fish
Animal <|-- Zebra Animal <|-- Zebra
Animal : +int age Animal : +int age

View File

@@ -605,14 +605,6 @@ export const insertEdge = function (
const edgeStyles = Array.isArray(edge.style) ? edge.style : [edge.style]; const edgeStyles = Array.isArray(edge.style) ? edge.style : [edge.style];
let strokeColor = edgeStyles.find((style) => style?.startsWith('stroke:')); let strokeColor = edgeStyles.find((style) => style?.startsWith('stroke:'));
let animationClass = '';
if (edge.animate) {
animationClass = 'edge-animation-fast';
}
if (edge.animation) {
animationClass = 'edge-animation-' + edge.animation;
}
let animatedEdge = false; let animatedEdge = false;
if (edge.look === 'handDrawn') { if (edge.look === 'handDrawn') {
const rc = rough.svg(elem); const rc = rough.svg(elem);
@@ -628,13 +620,7 @@ export const insertEdge = function (
svgPath = select(svgPathNode) svgPath = select(svgPathNode)
.select('path') .select('path')
.attr('id', edge.id) .attr('id', edge.id)
.attr( .attr('class', ' ' + strokeClasses + (edge.classes ? ' ' + edge.classes : ''))
'class',
' ' +
strokeClasses +
(edge.classes ? ' ' + edge.classes : '') +
(animationClass ? ' ' + animationClass : '')
)
.attr('style', edgeStyles ? edgeStyles.reduce((acc, style) => acc + ';' + style, '') : ''); .attr('style', edgeStyles ? edgeStyles.reduce((acc, style) => acc + ';' + style, '') : '');
let d = svgPath.attr('d'); let d = svgPath.attr('d');
svgPath.attr('d', d); svgPath.attr('d', d);
@@ -642,6 +628,13 @@ export const insertEdge = function (
} else { } else {
const stylesFromClasses = edgeClassStyles.join(';'); const stylesFromClasses = edgeClassStyles.join(';');
const styles = edgeStyles ? edgeStyles.reduce((acc, style) => acc + style + ';', '') : ''; const styles = edgeStyles ? edgeStyles.reduce((acc, style) => acc + style + ';', '') : '';
let animationClass = '';
if (edge.animate) {
animationClass = ' edge-animation-fast';
}
if (edge.animation) {
animationClass = ' edge-animation-' + edge.animation;
}
const pathStyle = const pathStyle =
(stylesFromClasses ? stylesFromClasses + ';' + styles + ';' : styles) + (stylesFromClasses ? stylesFromClasses + ';' + styles + ';' : styles) +
@@ -653,10 +646,7 @@ export const insertEdge = function (
.attr('id', edge.id) .attr('id', edge.id)
.attr( .attr(
'class', 'class',
' ' + ' ' + strokeClasses + (edge.classes ? ' ' + edge.classes : '') + (animationClass ?? '')
strokeClasses +
(edge.classes ? ' ' + edge.classes : '') +
(animationClass ? ' ' + animationClass : '')
) )
.attr('style', pathStyle); .attr('style', pathStyle);

View File

@@ -130,6 +130,7 @@ const lollipop = (elem, type, id) => {
.attr('markerHeight', 240) .attr('markerHeight', 240)
.attr('orient', 'auto') .attr('orient', 'auto')
.append('circle') .append('circle')
.attr('stroke', 'black')
.attr('fill', 'transparent') .attr('fill', 'transparent')
.attr('cx', 7) .attr('cx', 7)
.attr('cy', 7) .attr('cy', 7)
@@ -146,6 +147,7 @@ const lollipop = (elem, type, id) => {
.attr('markerHeight', 240) .attr('markerHeight', 240)
.attr('orient', 'auto') .attr('orient', 'auto')
.append('circle') .append('circle')
.attr('stroke', 'black')
.attr('fill', 'transparent') .attr('fill', 'transparent')
.attr('cx', 7) .attr('cx', 7)
.attr('cy', 7) .attr('cy', 7)

View File

@@ -7,6 +7,11 @@ import rough from 'roughjs';
import type { D3Selection } from '../../../types.js'; import type { D3Selection } from '../../../types.js';
import { handleUndefinedAttr } from '../../../utils.js'; import { handleUndefinedAttr } from '../../../utils.js';
import type { Bounds, Point } from '../../../types.js'; import type { Bounds, Point } from '../../../types.js';
import {
calculateMindmapDimensions,
getMindmapIconConfig,
insertMindmapIcon,
} from '../../../diagrams/mindmap/mindmapIconHelper.js';
export async function bang<T extends SVGGraphicsElement>(parent: D3Selection<T>, node: Node) { export async function bang<T extends SVGGraphicsElement>(parent: D3Selection<T>, node: Node) {
const { labelStyles, nodeStyles } = styles2String(node); const { labelStyles, nodeStyles } = styles2String(node);
@@ -17,19 +22,33 @@ export async function bang<T extends SVGGraphicsElement>(parent: D3Selection<T>,
getNodeClasses(node) getNodeClasses(node)
); );
const w = bbox.width + 10 * halfPadding; const baseWidth = bbox.width + 10 * halfPadding;
const h = bbox.height + 8 * halfPadding; const baseHeight = bbox.height + 8 * halfPadding;
const r = 0.15 * w;
const { cssStyles } = node; const iconConfig = getMindmapIconConfig('bang');
const dimensions = calculateMindmapDimensions(
node,
bbox,
baseWidth,
baseHeight,
halfPadding,
iconConfig
);
const w = dimensions.width;
const h = dimensions.height;
node.width = w;
node.height = h;
const minWidth = bbox.width + 20; const minWidth = bbox.width + 20;
const minHeight = bbox.height + 20; const minHeight = bbox.height + 20;
const effectiveWidth = Math.max(w, minWidth); const effectiveWidth = Math.max(w, minWidth);
const effectiveHeight = Math.max(h, minHeight); const effectiveHeight = Math.max(h, minHeight);
label.attr('transform', `translate(${-bbox.width / 2}, ${-bbox.height / 2})`); label.attr('transform', `translate(${dimensions.labelOffset.x}, ${dimensions.labelOffset.y})`);
let bangElem; const r = 0.15 * effectiveWidth;
const path = `M0 0 const path = `M0 0
a${r},${r} 1 0,0 ${effectiveWidth * 0.25},${-1 * effectiveHeight * 0.1} a${r},${r} 1 0,0 ${effectiveWidth * 0.25},${-1 * effectiveHeight * 0.1}
a${r},${r} 1 0,0 ${effectiveWidth * 0.25},${0} a${r},${r} 1 0,0 ${effectiveWidth * 0.25},${0}
@@ -50,13 +69,16 @@ export async function bang<T extends SVGGraphicsElement>(parent: D3Selection<T>,
a${r},${r} 1 0,0 ${effectiveWidth * 0.1},${-1 * effectiveHeight * 0.33} a${r},${r} 1 0,0 ${effectiveWidth * 0.1},${-1 * effectiveHeight * 0.33}
H0 V0 Z`; H0 V0 Z`;
let bangElem;
if (node.look === 'handDrawn') { if (node.look === 'handDrawn') {
// @ts-expect-error -- Passing a D3.Selection seems to work for some reason // @ts-expect-error -- Passing a D3.Selection seems to work for some reason
const rc = rough.svg(shapeSvg); const rc = rough.svg(shapeSvg);
const options = userNodeOverrides(node, {}); const options = userNodeOverrides(node, {});
const roughNode = rc.path(path, options); const roughNode = rc.path(path, options);
bangElem = shapeSvg.insert(() => roughNode, ':first-child'); bangElem = shapeSvg.insert(() => roughNode, ':first-child');
bangElem.attr('class', 'basic label-container').attr('style', handleUndefinedAttr(cssStyles)); bangElem
.attr('class', 'basic label-container')
.attr('style', handleUndefinedAttr(node.cssStyles));
} else { } else {
bangElem = shapeSvg bangElem = shapeSvg
.insert('path', ':first-child') .insert('path', ':first-child')
@@ -68,6 +90,10 @@ export async function bang<T extends SVGGraphicsElement>(parent: D3Selection<T>,
// Translate the path (center the shape) // Translate the path (center the shape)
bangElem.attr('transform', `translate(${-effectiveWidth / 2}, ${-effectiveHeight / 2})`); bangElem.attr('transform', `translate(${-effectiveWidth / 2}, ${-effectiveHeight / 2})`);
if (node.icon) {
await insertMindmapIcon(shapeSvg, node, iconConfig);
}
updateNodeBounds(node, bangElem); updateNodeBounds(node, bangElem);
node.calcIntersect = function (bounds: Bounds, point: Point) { node.calcIntersect = function (bounds: Bounds, point: Point) {
return intersect.rect(bounds, point); return intersect.rect(bounds, point);

View File

@@ -14,9 +14,25 @@ export async function circle<T extends SVGGraphicsElement>(
) { ) {
const { labelStyles, nodeStyles } = styles2String(node); const { labelStyles, nodeStyles } = styles2String(node);
node.labelStyle = labelStyles; node.labelStyle = labelStyles;
const { shapeSvg, bbox, halfPadding } = await labelHelper(parent, node, getNodeClasses(node));
const { shapeSvg, bbox, halfPadding, label } = await labelHelper(
parent,
node,
getNodeClasses(node)
);
const padding = options?.padding ?? halfPadding; const padding = options?.padding ?? halfPadding;
const radius = bbox.width / 2 + padding; const radius = bbox.width / 2 + padding;
node.width = radius * 2;
node.height = radius * 2;
const labelXOffset = -bbox.width / 2;
const labelYOffset = -bbox.height / 2;
if (node.icon) {
label.attr('transform', `translate(${labelXOffset}, ${labelYOffset})`);
}
let circleElem; let circleElem;
const { cssStyles } = node; const { cssStyles } = node;

View File

@@ -6,6 +6,11 @@ import type { Node } from '../../types.js';
import intersect from '../intersect/index.js'; import intersect from '../intersect/index.js';
import { styles2String, userNodeOverrides } from './handDrawnShapeStyles.js'; import { styles2String, userNodeOverrides } from './handDrawnShapeStyles.js';
import { getNodeClasses, labelHelper, updateNodeBounds } from './util.js'; import { getNodeClasses, labelHelper, updateNodeBounds } from './util.js';
import {
getMindmapIconConfig,
calculateMindmapDimensions,
insertMindmapIcon,
} from '../../../diagrams/mindmap/mindmapIconHelper.js';
export async function cloud<T extends SVGGraphicsElement>(parent: D3Selection<T>, node: Node) { export async function cloud<T extends SVGGraphicsElement>(parent: D3Selection<T>, node: Node) {
const { labelStyles, nodeStyles } = styles2String(node); const { labelStyles, nodeStyles } = styles2String(node);
@@ -17,8 +22,26 @@ export async function cloud<T extends SVGGraphicsElement>(parent: D3Selection<T>
getNodeClasses(node) getNodeClasses(node)
); );
const w = bbox.width + 2 * halfPadding; const baseWidth = bbox.width + 2 * halfPadding;
const h = bbox.height + 2 * halfPadding; const baseHeight = bbox.height + 2 * halfPadding;
const iconConfig = getMindmapIconConfig('cloud');
const dimensions = calculateMindmapDimensions(
node,
bbox,
baseWidth,
baseHeight,
halfPadding,
iconConfig
);
const w = dimensions.width;
const h = dimensions.height;
node.width = w;
node.height = h;
label.attr('transform', `translate(${dimensions.labelOffset.x}, ${dimensions.labelOffset.y})`);
// Cloud radii // Cloud radii
const r1 = 0.15 * w; const r1 = 0.15 * w;
@@ -61,11 +84,13 @@ export async function cloud<T extends SVGGraphicsElement>(parent: D3Selection<T>
.attr('d', path); .attr('d', path);
} }
label.attr('transform', `translate(${-bbox.width / 2}, ${-bbox.height / 2})`);
// Center the shape // Center the shape
cloudElem.attr('transform', `translate(${-w / 2}, ${-h / 2})`); cloudElem.attr('transform', `translate(${-w / 2}, ${-h / 2})`);
if (node.icon) {
await insertMindmapIcon(shapeSvg, node, iconConfig);
}
updateNodeBounds(node, cloudElem); updateNodeBounds(node, cloudElem);
node.calcIntersect = function (bounds: Bounds, point: Point) { node.calcIntersect = function (bounds: Bounds, point: Point) {

View File

@@ -3,6 +3,11 @@ import type { Node } from '../../types.js';
import intersect from '../intersect/index.js'; import intersect from '../intersect/index.js';
import { styles2String } from './handDrawnShapeStyles.js'; import { styles2String } from './handDrawnShapeStyles.js';
import { getNodeClasses, labelHelper, updateNodeBounds } from './util.js'; import { getNodeClasses, labelHelper, updateNodeBounds } from './util.js';
import {
getMindmapIconConfig,
calculateMindmapDimensions,
insertMindmapIcon,
} from '../../../diagrams/mindmap/mindmapIconHelper.js';
export async function defaultMindmapNode<T extends SVGGraphicsElement>( export async function defaultMindmapNode<T extends SVGGraphicsElement>(
parent: D3Selection<T>, parent: D3Selection<T>,
@@ -17,22 +22,38 @@ export async function defaultMindmapNode<T extends SVGGraphicsElement>(
getNodeClasses(node) getNodeClasses(node)
); );
const w = bbox.width + 8 * halfPadding; const baseWidth = bbox.width + 8 * halfPadding;
const h = bbox.height + 2 * halfPadding; const baseHeight = bbox.height + 2 * halfPadding;
const rd = 5;
const rectPath = ` const iconConfig = getMindmapIconConfig('default');
M${-w / 2} ${h / 2 - rd} const dimensions = calculateMindmapDimensions(
v${-h + 2 * rd} node,
q0,-${rd} ${rd},-${rd} bbox,
h${w - 2 * rd} baseWidth,
q${rd},0 ${rd},${rd} baseHeight,
v${h - 2 * rd} halfPadding,
q0,${rd} -${rd},${rd} iconConfig
h${-w + 2 * rd} );
q-${rd},0 -${rd},-${rd}
Z const w = dimensions.width;
`; const h = dimensions.height;
node.width = w;
node.height = h;
label.attr('transform', `translate(${dimensions.labelOffset.x}, ${dimensions.labelOffset.y})`);
const RD = 5;
const rectPath = `M${-w / 2} ${h / 2 - RD}
v${-h + 2 * RD}
q0,-${RD} ${RD},-${RD}
h${w - 2 * RD}
q${RD},0 ${RD},${RD}
v${h - 2 * RD}
q0,${RD} -${RD},${RD}
h${-w + 2 * RD}
q-${RD},0 -${RD},-${RD}
Z`;
const bg = shapeSvg const bg = shapeSvg
.append('path') .append('path')
@@ -49,9 +70,12 @@ export async function defaultMindmapNode<T extends SVGGraphicsElement>(
.attr('x2', w / 2) .attr('x2', w / 2)
.attr('y2', h / 2); .attr('y2', h / 2);
label.attr('transform', `translate(${-bbox.width / 2}, ${-bbox.height / 2})`);
shapeSvg.append(() => label.node()); shapeSvg.append(() => label.node());
if (node.icon) {
await insertMindmapIcon(shapeSvg, node, iconConfig);
}
updateNodeBounds(node, bg); updateNodeBounds(node, bg);
node.calcIntersect = function (bounds: Bounds, point: Point) { node.calcIntersect = function (bounds: Bounds, point: Point) {
return intersect.rect(bounds, point); return intersect.rect(bounds, point);

View File

@@ -15,11 +15,21 @@ export async function drawRect<T extends SVGGraphicsElement>(
) { ) {
const { labelStyles, nodeStyles } = styles2String(node); const { labelStyles, nodeStyles } = styles2String(node);
node.labelStyle = labelStyles; node.labelStyle = labelStyles;
// console.log('IPI labelStyles:', labelStyles);
const { shapeSvg, bbox } = await labelHelper(parent, node, getNodeClasses(node)); const { shapeSvg, bbox, label } = await labelHelper(parent, node, getNodeClasses(node));
const totalWidth = Math.max(bbox.width + options.labelPaddingX * 2, node?.width || 0); const totalWidth = Math.max(bbox.width + options.labelPaddingX * 2, node?.width || 0);
const totalHeight = Math.max(bbox.height + options.labelPaddingY * 2, node?.height || 0); const totalHeight = Math.max(bbox.height + options.labelPaddingY * 2, node?.height || 0);
node.width = totalWidth;
node.height = totalHeight;
const labelXOffset = -bbox.width / 2;
const labelYOffset = -bbox.height / 2;
if (node.icon) {
label.attr('transform', `translate(${labelXOffset}, ${labelYOffset})`);
}
const x = -totalWidth / 2; const x = -totalWidth / 2;
const y = -totalHeight / 2; const y = -totalHeight / 2;

View File

@@ -26,10 +26,22 @@ export const createHexagonPathD = (
export async function hexagon<T extends SVGGraphicsElement>(parent: D3Selection<T>, node: Node) { export async function hexagon<T extends SVGGraphicsElement>(parent: D3Selection<T>, node: Node) {
const { labelStyles, nodeStyles } = styles2String(node); const { labelStyles, nodeStyles } = styles2String(node);
node.labelStyle = labelStyles; node.labelStyle = labelStyles;
const { shapeSvg, bbox } = await labelHelper(parent, node, getNodeClasses(node));
const { shapeSvg, bbox, label } = await labelHelper(parent, node, getNodeClasses(node));
const h = bbox.height + (node.padding ?? 0); const h = bbox.height + (node.padding ?? 0);
const w = bbox.width + (node.padding ?? 0) * 2.5; const w = bbox.width + (node.padding ?? 0) * 2.5;
node.width = w;
node.height = h;
const labelXOffset = -bbox.width / 2;
const labelYOffset = -bbox.height / 2;
if (node.icon) {
label.attr('transform', `translate(${labelXOffset}, ${labelYOffset})`);
}
const { cssStyles } = node; const { cssStyles } = node;
// @ts-expect-error -- Passing a D3.Selection seems to work for some reason // @ts-expect-error -- Passing a D3.Selection seems to work for some reason
const rc = rough.svg(shapeSvg); const rc = rough.svg(shapeSvg);
@@ -74,9 +86,6 @@ export async function hexagon<T extends SVGGraphicsElement>(parent: D3Selection<
polygon.selectChildren('path').attr('style', nodeStyles); polygon.selectChildren('path').attr('style', nodeStyles);
} }
node.width = w;
node.height = h;
updateNodeBounds(node, polygon); updateNodeBounds(node, polygon);
node.intersect = function (point) { node.intersect = function (point) {

View File

@@ -1,13 +1,57 @@
import { circle } from './circle.js'; import type { Node } from '../../types.js';
import type { Node, MindmapOptions } from '../../types.js';
import type { D3Selection } from '../../../types.js'; import type { D3Selection } from '../../../types.js';
import { getNodeClasses, labelHelper, updateNodeBounds } from './util.js';
import { styles2String } from './handDrawnShapeStyles.js';
import intersect from '../intersect/index.js';
import {
getMindmapIconConfig,
calculateMindmapDimensions,
insertMindmapIcon,
} from '../../../diagrams/mindmap/mindmapIconHelper.js';
export async function mindmapCircle<T extends SVGGraphicsElement>( export async function mindmapCircle<T extends SVGGraphicsElement>(
parent: D3Selection<T>, parent: D3Selection<T>,
node: Node node: Node
) { ) {
const options = { const { shapeSvg, bbox, label } = await labelHelper(parent, node, getNodeClasses(node));
padding: node.padding ?? 0, const halfPadding = (node.padding ?? 0) / 2;
} as MindmapOptions;
return circle(parent, node, options); const iconConfig = getMindmapIconConfig('circle');
const baseRadius = bbox.width / 2 + halfPadding;
const baseDiameter = baseRadius * 2;
const dimensions = calculateMindmapDimensions(
node,
bbox,
baseDiameter,
baseDiameter,
halfPadding,
iconConfig
);
const radius = dimensions.width / 2;
node.width = dimensions.width;
node.height = dimensions.height;
label.attr('transform', `translate(${dimensions.labelOffset.x}, ${dimensions.labelOffset.y})`);
const circle = shapeSvg
.insert('circle', ':first-child')
.attr('r', radius)
.attr('class', 'basic label-container')
.attr('style', styles2String(node).nodeStyles);
shapeSvg.append(() => label.node());
if (node.icon) {
await insertMindmapIcon(shapeSvg, node, iconConfig);
}
updateNodeBounds(node, circle);
node.intersect = function (point) {
return intersect.circle(node, radius, point);
};
return shapeSvg;
} }

View File

@@ -2,8 +2,8 @@ import { labelHelper, updateNodeBounds, getNodeClasses, createPathFromPoints } f
import intersect from '../intersect/index.js'; import intersect from '../intersect/index.js';
import type { Node } from '../../types.js'; import type { Node } from '../../types.js';
import { styles2String, userNodeOverrides } from './handDrawnShapeStyles.js'; import { styles2String, userNodeOverrides } from './handDrawnShapeStyles.js';
import rough from 'roughjs';
import type { D3Selection } from '../../../types.js'; import type { D3Selection } from '../../../types.js';
import rough from 'roughjs';
/** /**
* Generates evenly spaced points along an elliptical arc connecting two points. * Generates evenly spaced points along an elliptical arc connecting two points.
@@ -91,13 +91,20 @@ export async function roundedRect<T extends SVGGraphicsElement>(
) { ) {
const { labelStyles, nodeStyles } = styles2String(node); const { labelStyles, nodeStyles } = styles2String(node);
node.labelStyle = labelStyles; node.labelStyle = labelStyles;
const { shapeSvg, bbox } = await labelHelper(parent, node, getNodeClasses(node)); const { shapeSvg, bbox, label } = await labelHelper(parent, node, getNodeClasses(node));
const labelPaddingX = node?.padding ?? 0; const labelPaddingX = node?.padding ?? 0;
const labelPaddingY = node?.padding ?? 0; const labelPaddingY = node?.padding ?? 0;
const w = (node?.width ? node?.width : bbox.width) + labelPaddingX * 2; const w = (node?.width ? node?.width : bbox.width) + labelPaddingX * 2;
const h = (node?.height ? node?.height : bbox.height) + labelPaddingY * 2; const h = (node?.height ? node?.height : bbox.height) + labelPaddingY * 2;
const labelXOffset = -bbox.width / 2;
if (node.icon) {
label.attr('transform', `translate(${labelXOffset}, ${-bbox.height / 2})`);
}
const radius = node.radius || 5; const radius = node.radius || 5;
const taper = node.taper || 5; // Taper width for the rounded corners const taper = node.taper || 5; // Taper width for the rounded corners
const { cssStyles } = node; const { cssStyles } = node;

View File

@@ -84,6 +84,7 @@ interface BaseNode {
radius?: number; radius?: number;
taper?: number; taper?: number;
stroke?: string; stroke?: string;
section?: number;
} }
/** /**

770
pnpm-lock.yaml generated

File diff suppressed because it is too large Load Diff