Skip to content

feat: complete usecase diagram integration & validation#7530

Open
Sudhanshu-Ambastha wants to merge 50 commits intomermaid-js:developfrom
Sudhanshu-Ambastha:develop
Open

feat: complete usecase diagram integration & validation#7530
Sudhanshu-Ambastha wants to merge 50 commits intomermaid-js:developfrom
Sudhanshu-Ambastha:develop

Conversation

@Sudhanshu-Ambastha
Copy link
Copy Markdown

@Sudhanshu-Ambastha Sudhanshu-Ambastha commented Mar 26, 2026

📑 Summary

Implements a dedicated Use Case Diagram renderer for Mermaid (usecaseDiagram), resolving the approved diagram request and addressing the curved path routing issue for include/extend relationships within system boundaries.

The implementation follows UML 2.x standards for correct element shapes, relationship types, and layout conventions.

Resolves #7414
Also closes #4628


📏 Design Decisions

  • Parser (usecaseDb.ts) — A text-based parser reads usecaseDiagram syntax directly.
  • Syntax Support — Supports actor, usecase, system {} boundary, external, collaboration, note, and 9 relationship types.
  • Validation — Relationship validity is enforced via an explicit allow-list based on UML 2.x rules. Invalid connections are skipped with a log.warn hint instead of causing runtime failures.
  • Renderer (usecaseRenderer.ts) — D3-based SVG renderer aligned with Mermaid’s rendering architecture.
  • Curved Routing — Internal relationships (include/extend/dependency) use quadratic Bézier curves routed along the boundary edge to eliminate zig-zag artifacts and improve readability.
  • External Connections — Straight-line routing with ellipse-edge intersection for precise arrow attachment.
  • Configuration (config.yaml) — Introduces UsecaseDiagramConfig into the global Mermaid configuration schema.
  • IntelliSense — Enables full editor support (e.g., VS Code) and aligns with Mermaid’s global config patterns.
  • Theming (usecaseStyles.ts) — Uses standard Mermaid theme variables (primaryColor, lineColor, etc.).
  • Style Validation (styles.spec.ts) — Adds automated tests (Vitest) to ensure consistent rendering across default themes.
  • Detector (usecaseDetector.ts) — Activates on usecaseDiagram or useCase keywords at the start of input.

Example Syntax

usecaseDiagram
    actor "Customer" as C
    actor "Technician" as T
    external "Bank Server" as S
    system "ATM System" {
        usecase "Withdraw Cash" as UC1
        usecase "Check Balance" as UC2
        usecase "Login" as UC3
    }
    note "Requires PIN" as N1
    C --> UC1; UC2
    T --> UC3
    include: UC1 --> UC3
    dependency: UC1 --> S
    generalization: T --> C
    anchor: N1 --> UC3

📝 Notes for Reviewers

Relationship Rules

  • Defined in usecaseDb.ts (ALLOWED table)
  • If any rule is missing or incorrect, please flag it or update directly
  • Each rule includes reasoning aligned with UML 2.x semantics

Invalid Relationships

  • Never fatal
  • Silently skipped with a log.warn hint for easier debugging

Rendering

  • Diagram renders correctly in deploy preview when manually tested
  • Curved routing resolves previously reported layout issues

Known Issue

  • The "Use Case" option is currently missing from the "Sample Diagrams" sidebar
  • Likely due to a registry/build sync issue in the monorepo
  • Please advise if additional registry files require updates

image even same in old pr [7519](https://github.com//pull/7519)

📋 Tasks

  • 📖 Read the contribution guidelines
  • 💻 Added unit/e2e tests (including style validation suite)
  • 📓 Added documentation
  • 🦋 Generated a changeset using pnpm changeset

@netlify
Copy link
Copy Markdown

netlify bot commented Mar 26, 2026

Deploy Preview for mermaid-js ready!

Name Link
🔨 Latest commit a378d72
🔍 Latest deploy log https://app.netlify.com/projects/mermaid-js/deploys/69df99ad882f310008da87e5
😎 Deploy Preview https://deploy-preview-7530--mermaid-js.netlify.app
📱 Preview on mobile
Toggle QR Code...

QR Code

Use your smartphone camera to open QR code link.

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

@changeset-bot
Copy link
Copy Markdown

changeset-bot bot commented Mar 26, 2026

🦋 Changeset detected

Latest commit: a378d72

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

This PR includes changesets to release 2 packages
Name Type
@mermaid-js/examples Patch
mermaid Patch

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

@pkg-pr-new
Copy link
Copy Markdown

pkg-pr-new bot commented Mar 26, 2026

Open in StackBlitz

@mermaid-js/examples

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

mermaid

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

@mermaid-js/layout-elk

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

@mermaid-js/layout-tidy-tree

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

@mermaid-js/mermaid-zenuml

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

@mermaid-js/parser

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

@mermaid-js/tiny

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

commit: ce48583

@codecov
Copy link
Copy Markdown

codecov bot commented Mar 27, 2026

Codecov Report

❌ Patch coverage is 1.58730% with 992 lines in your changes missing coverage. Please review.
✅ Project coverage is 3.30%. Comparing base (276b753) to head (a378d72).

Files with missing lines Patch % Lines
...es/mermaid/src/diagrams/usecase/usecaseRenderer.ts 0.18% 538 Missing ⚠️
packages/mermaid/src/diagrams/usecase/usecaseDb.ts 0.55% 180 Missing ⚠️
packages/mermaid/src/diagrams/usecase/parser.ts 1.21% 81 Missing ⚠️
...ages/mermaid/src/diagrams/usecase/usecaseStyles.ts 2.43% 40 Missing ⚠️
packages/parser/src/language/usecase/module.ts 4.76% 20 Missing ⚠️
packages/examples/src/examples/usecase.ts 6.25% 15 Missing ⚠️
...es/mermaid/src/diagrams/usecase/usecaseDetector.ts 8.33% 11 Missing ⚠️
...ges/mermaid/src/diagrams/usecase/usecaseDiagram.ts 10.00% 9 Missing ⚠️
packages/mermaid/src/themes/theme-base.js 0.00% 8 Missing ⚠️
packages/mermaid/src/themes/theme-dark.js 0.00% 8 Missing ⚠️
... and 16 more
Additional details and impacted files

Impacted file tree graph

@@            Coverage Diff             @@
##           develop   #7530      +/-   ##
==========================================
- Coverage     3.33%   3.30%   -0.04%     
==========================================
  Files          537     547      +10     
  Lines        56310   57318    +1008     
  Branches       821     835      +14     
==========================================
+ Hits          1877    1893      +16     
- Misses       54433   55425     +992     
Flag Coverage Δ
unit 3.30% <1.58%> (-0.04%) ⬇️

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

Files with missing lines Coverage Δ
packages/mermaid/src/config.type.ts 100.00% <ø> (ø)
packages/mermaid/src/themes/theme-default.js 95.62% <100.00%> (+0.08%) ⬆️
.build/jsonSchema.ts 0.00% <0.00%> (ø)
packages/mermaid/src/docs/.vitepress/config.ts 0.39% <0.00%> (-0.01%) ⬇️
packages/parser/src/language/index.ts 0.00% <0.00%> (ø)
packages/parser/src/language/usecase/index.ts 0.00% <0.00%> (ø)
packages/examples/src/index.ts 1.72% <0.00%> (-0.07%) ⬇️
...s/mermaid/src/diagram-api/diagram-orchestration.ts 0.00% <0.00%> (ø)
...ckages/parser/src/language/usecase/tokenBuilder.ts 0.00% <0.00%> (ø)
packages/parser/src/parse.ts 1.01% <0.00%> (-0.06%) ⬇️
... and 18 more
🚀 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
Copy link
Copy Markdown

argos-ci bot commented Apr 1, 2026

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

Build Status Details Updated (UTC)
default (Inspect) ⚠️ Changes detected (Review) 1 changed, 8 added, 2 failures Apr 15, 2026, 2:10 PM

@Restodecoca
Copy link
Copy Markdown

Hi, I looked through your PR and it already seems very well advanced. The main adjustment I can see is the parser side: since Mermaid is adopting Langium for new diagrams, it may make sense to migrate this from Jison to Langium to match the current repository standard.

Would you be open to a PR against your branch to help with that migration?

- Create usecase.langium with complete grammar
  - 8 statement types: Actor, External, System, Usecase, Collaboration, Note, Association, Relationship
  - Support for 8 relationship types: include, extend, generalization, dependency, realization, anchor, constraint, containment
  - Implement tokenBuilder.ts with keywords for diagram detection
  - Implement module.ts following Radar/Packet dependency injection pattern
  - Register grammar in langium-config.json
  - Import usecase module in parser language index

Follows the Langium 4.0.0 pattern used by Radar and Packet diagram types.
- Add lazy initializer for usecase parser via createUsecaseServices()
  - Add promise-based parse('usecase', text) overload
  - Update DiagramAST union type to include Usecase
  - Connects Langium grammar generator to central parser dispatcher

Parser now auto-loads usecase module on first diagram parse, following singleton pattern used by other diagram types.
- Implement parser.ts bridge between Langium AST and usecaseDb
  - populate(ast) function iterates AST statements and dispatches by \
  - Type-safe casts handle optional fields (label, alias, notes)
  - Supports all 8 relationship types with proper type validation
  - Replaces regex-based parsing in usecaseDb.ts

Bridge pattern separates concerns: grammar/generation → parser bridge → state management.
- Lines: 481 → 250 (48% reduction, focusing on state management)
  - Remove parseDiagram() and all regex-based parsing logic
  - Remove parseString() utility function
  - Keep all entity types, state structures, validation rules
  - Keep inferUseCases() type inference for edge cases
  - DB now acts as pure state container, parsing delegated to parser.ts bridge

Benefits:
  - Separation of concerns (parsing vs state management)
  - Type safety via Langium AST instead of regex captures
  - Easier to test and maintain
- Rewrite 22 tests to match new db interface (no parsing in db)
  - Tests focus on: entity creation, state management, relationship validation
  - Test system boundaries with nested usecases
  - Validate all 8 relationship types (include, extend, etc.)
  - Test inference logic and edge cases
  - All tests passing (22/22 in 44ms)

Tests now validate db contract independently of parser, enabling future parser refactors.
- Change regex from: /^\\s*usecase/i (too broad, false positives)
- To: /^\\s*(usecaseDiagram|useCase)\\b/i (specific keywords)
- Prevents misdetection of comments or other diagrams starting with 'use'

This fixes the core issue where usecase diagrams were undetectable or causing false positives in diagram auto-detection.
Aligns with Langium keywords: 'usecaseDiagram' (document start) and 'useCase' (entity definition).
- Remove ucDb.clear() call (now in parser bridge initialization)
  - Remove ucDb.parseDiagram(text) call (parsing delegated to parser.ts)
  - Renderer now directly calls getModel() assuming db is populated
  - Simplifies render lifecycle: parse → populate → render (3 clear phases)

Benefits:
  - Renderer focuses solely on SVG rendering
  - Parser logic isolated in parser.ts bridge
  - Enables easier testing of render logic independently
Update usecaseDiagram.ts to use new parser registration pattern with Langium-generated detector.
- Delete usecase.jison (dead code)
  - Jison implementation never invoked after migration to Langium
  - All parsing now handled by Langium grammar + parser bridge

Langium provides superior benefits:
  - Strict grammar validation at parse time
  - Type-safe AST generation
  - Better error reporting
  - Consistent with new diagram types (Radar, Packet)
- Change comment syntax from # to %% (Mermaid standard)
  - Fix diagrams 1, 3, 4 which had parsing errors
  - Langium is stricter about syntax than old Jison parser
  - All 4 demo diagrams now parse and render correctly

Demo updated to serve as reference for correct usecase syntax:
  1. Basic actors, systems, and usecases
  2. Generalization relationships and system boundary
  3. System with nested usecases
  4. Complex multi-system diagram with all relationship types
@Sudhanshu-Ambastha
Copy link
Copy Markdown
Author

Hi, I looked through your PR and it already seems very well advanced. The main adjustment I can see is the parser side: since Mermaid is adopting Langium for new diagrams, it may make sense to migrate this from Jison to Langium to match the current repository standard.

Would you be open to a PR against your branch to help with that migration?

Hi, thanks for taking the time out of your busy schedule to respond!
I’ll definitely start looking into the changes, and I am absolutely open to a PR against my branch for the Langium migration. Since Mermaid is moving in that direction, so I can will follow the standards for future contributions.

While testing my implementation, I noticed a behavior that matches the issue I recently raised in #7569. The diagram renders correctly when the code is explicitly typed in the editor, but it doesn't show up in the selection menu or samples list.

Since I faced this while implementing the Use Case diagram, I’d like to know if the migration to Langium will automatically resolve this registration in the Live Editor's UI, or if there is a separate configuration I should be updating alongside the parser to ensure full discovery by the UI components.

I'll reach out if I hit any roadblocks during the transition. Looking forward to your guidance!

@Restodecoca
Copy link
Copy Markdown

To answer your question about the Live Editor: no, the Langium migration alone won't automatically fix the Live Editor's sample menu discovery. Those are two separate things:

  1. Core Mermaid (what this PR fixes):

Diagram parsing and rendering ✅
Diagram type detection (usecaseDetector) ✅
The diagram works when you type the code manually
2. Live Editor sample menu (separate concern):

The samples list lives in a different repository: mermaid-live-editor
It needs its own PR to add the usecase entry to the examples/samples configuration
This is a small change, but in a separate codebase
So after we merge the Langium migration here, the usecase diagram will be fully functional in core Mermaid (CLI, JS API, docs). The Live Editor sample menu is a nice-to-have follow-up that either of us can do as a separate PR.

I already have the branch ready at gabriel/migrate-jison-langium on my fork and a open PR at your codebase.

@Sudhanshu-Ambastha
Copy link
Copy Markdown
Author

Sudhanshu-Ambastha commented Apr 15, 2026

To answer your question about the Live Editor: no, the Langium migration alone won't automatically fix the Live Editor's sample menu discovery. Those are two separate things:

  1. Core Mermaid (what this PR fixes):

Diagram parsing and rendering ✅
Diagram type detection (usecaseDetector) ✅
The diagram works when you type the code manually
2. Live Editor sample menu (separate concern):

The samples list lives in a different repository: mermaid-live-editor
It needs its own PR to add the usecase entry to the examples/samples configuration
This is a small change, but in a separate codebase
So after we merge the Langium migration here, the usecase diagram will be fully functional in core Mermaid (CLI, JS API, docs). The Live Editor sample menu is a nice-to-have follow-up that either of us can do as a separate PR.

I already have the branch ready at gabriel/migrate-jison-langium on my fork and a open PR at your codebase.

Ok I checked the pr I though so that was the reason even I asked from diff AIs they also said that we need to edit from editor side but I don't remember who said that it should auto show up on the editor side if done perfectly in backend ok I fix the backend + the editor code too
Ok if I have any other doubt i ask it here or continue here + i also have query with this if someone can be avilable for help i can do it for you i think if i am free + a member to guide related to connection 7556
And also if you or anyone don't have a problem I will add this issue with this pr so it can be merged in 1 go 7554

@Restodecoca
Copy link
Copy Markdown

I think the best approach is to keep this PR focused on the usecase migration only. #7556 would be a massive refactor and #7554 is a completely separate feature that deserves its own PR. Feel free to reference them here, but I wouldn't recommend merging them together. Let's get this one done first!

@Sudhanshu-Ambastha
Copy link
Copy Markdown
Author

Sudhanshu-Ambastha commented Apr 15, 2026

I think the best approach is to keep this PR focused on the usecase migration only. #7556 would be a massive refactor and #7554 is a completely separate feature that deserves its own PR. Feel free to reference them here, but I wouldn't recommend merging them together. Let's get this one done first!

Ok then i will merge them 1 by 1 as for now like for usecase is in my fork's main branch & cpm/pert in seprate + for the refactor part of repo i haven't started anything yet related to it + I need someone to help/guide me with it refactor thing as i don't want to end up breaking that so i haven't touched/started it yet

@Sudhanshu-Ambastha
Copy link
Copy Markdown
Author

Hey @Restodecoca! I've pushed the latest updates, but 2 tests are still failing in the E2E suite. It seems the parser is still struggling with quoted strings in certain contexts, which is causing the Argos visual tests to fail as well.

Also, the pkg-pr-new preview release is failing with a 413 error, but that looks like a package size limit issue rather than a code bug. Since you're working on the Langium migration, could you take a look at those two parser edge cases? Everything else is synced and ready!

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Diagram Proposal: Dedicated "Use Case Diagram" with Manual Pathing/Curving Add Use Case diagram type

2 participants