Skip to content

feat: pass node shape configs to layout algo - #8016

Open
strowk wants to merge 13 commits into
mermaid-js:developfrom
strowk:feature/pass-node-metadata
Open

strowk wants to merge 13 commits into
mermaid-js:developfrom
strowk:feature/pass-node-metadata

Conversation

@strowk

@strowk strowk commented Aug 1, 2026 •

Copy link
Copy Markdown

📑 Allow layout algo to access complete node shape data

In the same way, that subgraphs partly do, this change passes complete node shape data in metadata field.

Resolves #8004

📏 Design Decisions

I used same word 'metadata' there since subgraphs pass it with same name.
Happy to change if needed.

📋 Tasks

Make sure you

  • 📖 have read the contribution guidelines
  • 💻 have added necessary unit/e2e tests.
  • 📓 have added documentation. Make sure MERMAID_RELEASE_VERSION is used for all new features.
  • 🦋 If your PR makes a change that should be noted in one or more packages' changelogs, generate a changeset by running pnpm changeset and following the prompts. Changesets that add features should be minor and those that fix bugs should be patch. Please prefix changeset messages with feat:, fix:, or chore:.

Summary

Passes complete regular node shape metadata into the layout pipeline via the metadata field, matching subgraph metadata behavior, and adds coverage for metadata escaping and propagation.

Changes

  • Adds FlowVertex.metadata?: Record<string, unknown> to carry raw user-input shape metadata.
  • Extends shared rendering node types with an optional metadata record so nodes can transport arbitrary key/value metadata.
  • Updates flowchart DB handling so @{}-parsed metadata is stored on vertices and propagated to layout nodes for both existing and newly created nodes.
  • Adds a FlowDB unit test verifying addVertex parses @{} metadata and exposes it on resulting layout nodes.
  • Adds a rendering regression test that renders flowchart metadata in JSDOM and verifies injection payloads do not appear as raw SVG/DOM content, including coverage for regular nodes and collapsed subgraph metadata.
  • Adds a minor changeset documenting support for passing arbitrary metadata from flowcharts to the layout algorithm.

@changeset-bot

changeset-bot Bot commented Aug 1, 2026 •

Copy link
Copy Markdown

🦋 Changeset detected

Latest commit: 04b2ee0

The changes in this PR will be included in the next version bump.

This PR includes changesets to release 1 package
Name Type
mermaid Minor

Not sure what this means? Click here to learn what changesets are.

Click here if you're a maintainer who wants to add another changeset to this PR

@netlify

netlify Bot commented Aug 1, 2026 •

Copy link
Copy Markdown

✅ Deploy Preview for mermaid-js ready!

Name Link
🔨 Latest commit 04b2ee0
🔍 Latest deploy log https://app.netlify.com/projects/mermaid-js/deploys/6a73988b4c9e040008fc1986
😎 Deploy Preview https://deploy-preview-8016--mermaid-js.netlify.app
📱 Preview on mobile
Toggle QR Code...

QR Code

Use your smartphone camera to open QR code link.
🤖 Make changes Run an agent on this branch

To edit notification comments on pull requests, go to your Netlify project configuration.

@github-actions github-actions Bot added the Type: Enhancement New feature or request label Aug 1, 2026
@coderabbitai

coderabbitai Bot commented Aug 1, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

Flowchart node metadata now has shared optional types, is stored on vertices, and is copied into rendered node data for existing and new nodes. JSDOM tests validate metadata handling across flowchart shapes and subgraphs.

Changes

Flowchart metadata propagation

Layer / File(s) Summary
Type and propagate node metadata
packages/mermaid/src/diagrams/flowchart/types.ts, packages/mermaid/src/rendering-util/types.ts, packages/mermaid/src/diagrams/flowchart/flowDb.ts, packages/mermaid/src/diagrams/flowchart/flowDb.spec.ts, docs/config/setup/mermaid/interfaces/LayoutData.md, .changeset/node-pass-metadata-to-layout.md
FlowVertex and shared node properties support arbitrary metadata. Parsed metadata is stored on vertices and copied into rendered node data for existing and new nodes. Tests verify the transferred metadata. Generated documentation links and the changeset reflect the update.
Validate metadata escaping
packages/mermaid/src/rendering-util/metadata-escaping.spec.ts
JSDOM tests cover documented shapes, subgraphs, dangerous elements, attributes, URLs, styles, and executable markup in rendered SVG.

Estimated code review effort: 3 (Moderate) | ~20 minutes

Possibly related PRs

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Linked Issues check ✅ Passed The PR fully implements issue #8004: nodes now expose metadata through the layout algorithm, matching subgraph behavior and enabling custom @{} properties.
Out of Scope Changes check ✅ Passed All changes directly support the core objective: metadata storage on vertices, type definitions, test coverage, and changeset documentation are in scope.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Title check ✅ Passed The title clearly describes the primary change: passing node shape data to the layout algorithm.
Description check ✅ Passed The description covers the change, design decision, issue, tests, and changeset; documentation is explicitly marked incomplete but is non-critical.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@pkg-pr-new

pkg-pr-new Bot commented Aug 1, 2026 •

Copy link
Copy Markdown

Open in StackBlitz

@mermaid-js/examples

npm i https://pkg.pr.new/@mermaid-js/examples@8016

mermaid

npm i https://pkg.pr.new/mermaid@8016

@mermaid-js/layout-elk

npm i https://pkg.pr.new/@mermaid-js/layout-elk@8016

@mermaid-js/layout-tidy-tree

npm i https://pkg.pr.new/@mermaid-js/layout-tidy-tree@8016

@mermaid-js/mermaid-zenuml

npm i https://pkg.pr.new/@mermaid-js/mermaid-zenuml@8016

@mermaid-js/parser

npm i https://pkg.pr.new/@mermaid-js/parser@8016

@mermaid-js/tiny

npm i https://pkg.pr.new/@mermaid-js/tiny@8016

commit: 04b2ee0

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@packages/mermaid/src/diagrams/flowchart/flowDb.ts`:
- Line 1075: Update the existing-node branch in the node registration logic to
preserve metadata by copying vertex.metadata onto the already-registered node,
alongside its existing style/class updates. Ensure repeated IDs retain the
latest subgraph metadata instead of dropping it.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 6619358b-e8c4-44ad-bbee-5afdef661579

📥 Commits

Reviewing files that changed from the base of the PR and between 19563d8 and 08e60c5.

📒 Files selected for processing (3)
  • packages/mermaid/src/diagrams/flowchart/flowDb.ts
  • packages/mermaid/src/diagrams/flowchart/types.ts
  • packages/mermaid/src/rendering-util/types.ts

Comment thread packages/mermaid/src/diagrams/flowchart/flowDb.ts
@codecov

codecov Bot commented Aug 1, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 71.42857% with 2 lines in your changes missing coverage. Please review.
✅ Project coverage is 78.76%. Comparing base (19563d8) to head (04b2ee0).
⚠️ Report is 88 commits behind head on develop.

Files with missing lines Patch % Lines
packages/mermaid/src/diagrams/flowchart/flowDb.ts 71.42% 2 Missing ⚠️
Additional details and impacted files

Impacted file tree graph

@@             Coverage Diff             @@
##           develop    #8016      +/-   ##
===========================================
+ Coverage    77.61%   78.76%   +1.14%     
===========================================
  Files          567      568       +1     
  Lines        74906    74999      +93     
  Branches     14619    12750    -1869     
===========================================
+ Hits         58141    59070     +929     
+ Misses       15768    15074     -694     
+ Partials       997      855     -142     
Flag Coverage Δ
e2e 70.60% <33.33%> (+0.01%) ⬆️
unit 78.14% <71.42%> (+3.14%) ⬆️

Flags with carried forward coverage won't be shown. Click here to find out more.

Files with missing lines Coverage Δ
packages/mermaid/src/diagrams/flowchart/flowDb.ts 86.06% <71.42%> (+0.19%) ⬆️

... and 58 files with indirect coverage changes

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@argos-ci

argos-ci Bot commented Aug 1, 2026 •

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Argos notifications ↗︎

Build Status Details Updated (UTC)
default (Inspect) ✅ No changes detected - Aug 5, 2026, 8:29 PM

Comment thread packages/mermaid/src/rendering-util/types.ts
Comment thread packages/mermaid/src/diagrams/flowchart/types.ts
@pbrolin47

Copy link
Copy Markdown
Collaborator

Hi @strowk,
Thanks for this PR. If the content in this PR can be helpful for further development of Mermaid, it's all good.

The metadata is a new field that nothing in the existing codebase reads. It gets stored on layout nodes but no existing layout algorithm touches it — so the raw user values sit there inert. There's no current code path from metadata to any DOM/SVG sink.

The theoretical future risk: a layout algorithm written later could naively read node.metadata.someKey and stick it into an .attr() or .html() call without sanitizing. That would be a problem at that point, not today.

So, I recommend:

  1. Add comments in code as suggested above.
  2. Add a cheap regression test asserting that arbitrary metadata values (e.g. {"x": ""}") don't appear unescaped in rendered SVG output for current shapes. This costs little and immediately fails the day someone adds a naive consumer — turning the "theoretical future risk" into something CI actually catches, rather than relying on a future reviewer remembering this thread.
  3. Some additional things to adress below.

[sisyphos-bot]


What's working well

🎉 Exactly follows the established pattern. The PR mirrors how subgraphs already pass metadata (same metadata field name, same spread approach), which makes the implementation immediately
understandable for anyone familiar with the codebase.

🎉 Both vertex-to-node branches are covered. The existing-node mutation path (node.metadata = vertex.metadata, flowDb.ts:1043) and the new-node object literal path (metadata: vertex.metadata,
flowDb.ts:1067) both thread the field through. No half-propagation.

🎉 Optional typing is correct. metadata?: Record<string, unknown> keeps all existing nodes valid without any migration burden.


Things to address

🟡 [important] Missing changeset

metadata is added to BaseNode → Node, which is exported as part of the public LayoutData.Node API from mermaid.ts. Optional additions to public types are additive and non-breaking, but they still
need a minor changeset so they appear in the changelog and downstream consumers are notified.

Run pnpm changeset, select mermaid, bump minor, and prefix the description with feat:.


🟡 [important] No unit test

The behavioral change — that @{ key: value } properties in flowchart syntax now propagate to the layout-node's metadata field — has no test. There's already a flowDb test infrastructure (e.g.,
packages/mermaid/src/diagrams/flowchart/flowDb.spec.ts) where a case like this fits naturally:

it('should pass @{} metadata to layout nodes', () => {
// Parse a vertex with metadata
flowDb.addVertex('A', { text: 'Node', type: 'rect' }, ...);
flowDb.setNodeShapeData('A', /* doc with custom field */ { myProp: 'hello', w: 100 });

const nodes = flowDb.getVertices();
expect(nodes['A'].metadata).toMatchObject({ myProp: 'hello', w: 100 });

});

(Adjust to match the actual FlowDB method signatures — the key thing is coverage for the vertex.metadata accumulation path.)


Nit / Suggestion

💡 metadata contains all @{} properties, including the ones Mermaid handles explicitly (shape, label, w, h, icon, pos, img, constraint).

vertex.metadata = { ...vertex.metadata, ...doc };
// → metadata = { shape: "rect", label: "Node", w: 100, myCustom: "hello", ... }

This works fine for the stated use case, and it's simpler than maintaining an exclusion list. Worth being aware of: layout algorithms reading metadata will see both Mermaid-controlled keys and truly
custom ones mixed together. If this ever becomes confusing for layout algorithm authors, a follow-up could separate them (e.g., keep only unknown keys in metadata, rename the full set to shapeData
or similar). Not a problem for this PR.


@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@packages/mermaid/src/rendering-util/metadata-escaping.spec.ts`:
- Around line 68-100: Update the render test setup in the metadata-escaping spec
so the temporary global MutationObserver override is saved before being set to
undefined and restored in the finally block alongside window and document. Use
the existing render helper around mermaidAPI.initialize and mermaidAPI.render as
the scope for the fix, and keep the current DOM cleanup behavior unchanged.
🪄 Autofix

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: c0f91c08-0a81-4976-b2cf-79aa8d2a53c1

📥 Commits

Reviewing files that changed from the base of the PR and between aada5cc and 1d1fe57.

📒 Files selected for processing (5)
  • .changeset/node-pass-metadata-to-layout.md
  • packages/mermaid/src/diagrams/flowchart/flowDb.spec.ts
  • packages/mermaid/src/diagrams/flowchart/types.ts
  • packages/mermaid/src/rendering-util/metadata-escaping.spec.ts
  • packages/mermaid/src/rendering-util/types.ts
🚧 Files skipped from review as they are similar to previous changes (2)
  • packages/mermaid/src/diagrams/flowchart/types.ts
  • packages/mermaid/src/rendering-util/types.ts

Comment thread packages/mermaid/src/rendering-util/metadata-escaping.spec.ts
@strowk

strowk commented Aug 5, 2026 •

Copy link
Copy Markdown
Author

@pbrolin47 , hey, thanks for reviewing!

Added comments:
8c6eec3

I decided to put test validating that html content can't reach output via metadata unescaped in a separate metadata-escaping.spec.ts file and it covers both subgraph and node metadata as well.
8bb3517

While trying to make these tests fail to check whether they test what they should, I have noticed that subgraph metadata is not actually passed down all the way, so fixed that as well with same comments.
2b4d089

Both cases now also have unit tests (for node and for subgraph) and I have added a changeset too.
19cb15a
1d1fe57

Not quite sure if I shall change anything in docs, not seeing anything in particular about layout algo development there.

@strowk
strowk requested a review from pbrolin47 August 5, 2026 20:28
@pbrolin47

Copy link
Copy Markdown
Collaborator

Hi @strowk,
Thanks for fixing the issues. Run a review

[sisyphos-bot]


What changed since round 1

🎉 Issue 1 fixed: Missing changeset
.changeset/node-pass-metadata-to-layout.md added with a minor bump — correct, since BaseNode.metadata? is a public LayoutData field.

🎉 Issue 2 fixed: Missing unit test
Three tests added:

  • flowDb.spec.ts — unit test verifying @{} foo: bar metadata flows through to layout nodes
  • subgraph.spec.js — verifies subgraph @{custom: 'value', another: 123} propagates correctly
  • metadata-escaping.spec.ts — 250-line security tripwire covering every documented flowchart shape

🎉 JSDoc added everywhere it matters
BaseNode.metadata, FlowVertex.metadata, and NodeMetaData.[key: string]: unknown all carry the "Raw @{}... Sanitize before writing to any DOM/SVG sink." warning. This is exactly the right
documentation strategy for a deferred-sanitization field.


Security

The XSS sub-agent confirmed:

  • No shape handler in rendering-util/rendering-elements/ currently reads node.metadata (grep returns only a comment)
  • Existing sinks for tooltip (DOMPurify at .html() time), link (formatUrl), and img (pre-existing @{} pattern, unrelated to this PR) are unaffected
  • metadata-escaping.spec.ts runs with securityLevel: 'loose' — intentionally the worst case (no DOMPurify backstop). Tests pass trivially today because nothing reads metadata, but the tripwire is
    real: any future shape handler that writes node.metadata to a DOM sink without sanitization will fail these tests immediately

The "tripwire, not a fix verification" framing in the spec header is exactly right.


@strowk

strowk commented Aug 11, 2026

Copy link
Copy Markdown
Author

Anything else I should fix here, @pbrolin47 ?

@pbrolin47
pbrolin47 added this pull request to the merge queue Aug 18, 2026
@github-merge-queue
github-merge-queue Bot removed this pull request from the merge queue due to failed status checks Aug 18, 2026
@pbrolin47

Copy link
Copy Markdown
Collaborator

Hi @strowk ,
Had a look at the PR, and saw you adressed the comment, so I set it yo approved and tried to merge, but it failed in the merge queue. Can you do a sync against develop, and I'll do a new merge if all good. Thanks in advance

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Type: Enhancement New feature or request

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Let layout algorithms read arbitrary node @{} metadata

2 participants