Skip to content

Conversation

@tbouffard
Copy link
Member

@tbouffard tbouffard commented Mar 27, 2025

This change better split responsibilities (reduce the amount of things done directly in Graph) and improves the tree-shaking for applications that don't use the fit method.

Passing parameters to Graph.fit is now simpler. The previous implementation used several positional parameters, which could be hard to follow and maintain.
This change:

  • Improves the readability of the method call.
  • Minimizes the need to pass many default values.
  • Aligns the API with more modern, maintainable patterns.

In addition, the implementation simplify min/max scale management.

BREAKING CHANGES: the AbstractGraph.fit method moved to FitPlugin, as well as the minFitScale and maxFitScale properties.
The method now accepts a single parameter, mainly to minimize the need to pass many default values.

Notes

The usage of a single parameter is inspired by #715 (comment)

Impacts on bundled application

For applications not using the FitPlugin and using the Graph class, there is no decrease. This is because FitPlugin is always loaded by the Graph class. This is what we see in js-example and ts-example.
The other examples use BaseGraph which doesn't load FitPlugin by default, only ts-example-selected-features loads it explicitely.
With BaseGraph, when not using FitPlugin, the decrease is about 1 kB

Example v0.20.0 PR #734
js-example 467.59 kB 467.61 kB
js-example-selected-features 390.40 kB 389.35 kB
js-example-without-default 325.44 kB 324.39 kB
ts-example 435.23 kB 435.27 kB
ts-example-selected-features 369.09 kB 369.12 kB
ts-example-without-default 309.18 kB 308.13 kB

Tasks

  • improve PR description
  • docs: update the mxGraph migration guide
  • docs: update changelog with breaking changes (moved method + single object parameter)
  • Measure impact on tree-shaking (use the 2 examples without defaults)
  • add reference to issue: covers Refactor Graph class and mixins to improve modularity and tree-shaking #762
  • rebase on main
  • manage PR review feedback
  • JSDoc and docs: update the since tag value
  • docs: revert change in mxgraph migration guide. This page is no longer updated
  • update the size of the examples

Summary by CodeRabbit

  • New Features

    • Introduced a dedicated FitPlugin with enhanced graph fitting options, including customizable margins, borders, and scaling constraints.
    • Added new options to control how the graph fits within its container, such as ignoring width/height and keeping the origin.
  • Refactor

    • Moved graph fitting functionality from the core graph class to the new FitPlugin for improved modularity and flexibility.
    • Updated user interface actions and stories to utilize the new FitPlugin for all fit-related operations.
  • Documentation

    • Updated the changelog to reflect the changes in graph fitting capabilities and plugin usage.

@tbouffard tbouffard added the refactor Code refactoring label Mar 27, 2025
@coderabbitai
Copy link

coderabbitai bot commented Mar 27, 2025

Walkthrough

The changes move the fit method and related properties from the AbstractGraph class to a new FitPlugin, updating all usages to call the plugin’s fit method instead. The changelog is updated, and affected stories and editor actions now use the plugin-based approach.

Changes

File(s) Change Summary
packages/core/src/view/AbstractGraph.ts Removed minFitScale and maxFitScale properties and the fit method from AbstractGraph, eliminating built-in fit functionality from the class.
packages/core/src/view/plugins/FitPlugin.ts Added a new FitOptions type and implemented the fit method in the FitPlugin class, including minFitScale and maxFitScale properties. The new method provides configurable graph fitting within the container.
packages/core/src/editor/Editor.ts Updated the 'fit' action in the editor to use the FitPlugin's fit method via the plugin system, with type annotation for FitPlugin.
packages/html/stories/ZoomAndFit.stories.ts Refactored to retrieve and cache the FitPlugin instance; all fit-related actions now use the plugin’s fit and fitCenter methods with options objects.
packages/html/stories/OrgChart.stories.js Updated the "Fit" menu item callback to use the FitPlugin's fit method via the plugin system with optional chaining.
CHANGELOG.md Added a "Breaking Changes" section under "Unreleased" documenting the move of the fit method and related properties to the FitPlugin, and the new single-parameter signature for the fit method.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant Editor
    participant Graph
    participant FitPlugin

    User->>Editor: Triggers 'fit' action
    Editor->>Graph: getPlugin('fit')
    Graph-->>Editor: FitPlugin instance
    Editor->>FitPlugin: fit(options)
    FitPlugin->>FitPlugin: Compute scale and apply fitting
    FitPlugin-->>Editor: scale
Loading

Possibly related issues

Possibly related PRs

Warning

There were issues while running some tools. Please review the errors and either fix the tool's configuration or disable the tool if it's a critical failure.

🔧 ESLint

If the error stems from missing dependencies, add them to the package.json file. For unrecoverable errors (e.g., due to private dependencies), disable the tool in the CodeRabbit configuration.

npm warn config production Use --omit=dev instead.
npm error Exit handler never called!
npm error This is an error with npm itself. Please report this error at:
npm error https://github.com/npm/cli/issues
npm error A complete log of this run can be found in: /.npm/_logs/2025-05-19T17_42_52_553Z-debug-0.log

Note

⚡️ AI Code Reviews for VS Code, Cursor, Windsurf

CodeRabbit now has a plugin for VS Code, Cursor and Windsurf. This brings AI code reviews directly in the code editor. Each commit is reviewed immediately, finding bugs before the PR is raised. Seamless context handoff to your AI code agent ensures that you can easily incorporate review feedback.
Learn more here.


Note

⚡️ Faster reviews with caching

CodeRabbit now supports caching for code and dependencies, helping speed up reviews. This means quicker feedback, reduced wait times, and a smoother review experience overall. Cached data is encrypted and stored securely. This feature will be automatically enabled for all accounts on May 16th. To opt out, configure Review - Disable Cache at either the organization or repository level. If you prefer to disable all data retention across your organization, simply turn off the Data Retention setting under your Organization Settings.
Enjoy the performance boost—your workflow just got faster.


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 5fad3ad and b557a6a.

📒 Files selected for processing (6)
  • CHANGELOG.md (1 hunks)
  • packages/core/src/editor/Editor.ts (2 hunks)
  • packages/core/src/view/AbstractGraph.ts (0 hunks)
  • packages/core/src/view/plugins/FitPlugin.ts (4 hunks)
  • packages/html/stories/OrgChart.stories.js (1 hunks)
  • packages/html/stories/ZoomAndFit.stories.ts (2 hunks)
💤 Files with no reviewable changes (1)
  • packages/core/src/view/AbstractGraph.ts
🚧 Files skipped from review as they are similar to previous changes (5)
  • packages/html/stories/OrgChart.stories.js
  • CHANGELOG.md
  • packages/html/stories/ZoomAndFit.stories.ts
  • packages/core/src/editor/Editor.ts
  • packages/core/src/view/plugins/FitPlugin.ts
✨ Finishing Touches
  • 📝 Generate Docstrings

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
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@sonarqubecloud
Copy link

@tbouffard tbouffard marked this pull request as ready for review April 17, 2025 13:11
Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 2

♻️ Duplicate comments (1)
packages/core/src/view/plugins/FitPlugin.ts (1)

107-125: Typo in JSDoc @param description

The text still says “Optional number” although the parameter is an object:

- * @param options Optional number that specifies the border.
+ * @param options Optional object to tweak fitting behaviour.

Minor, but surfaces in IDE tooltips.

🧹 Nitpick comments (4)
packages/core/src/editor/Editor.ts (2)

62-63: Import path may break tree‑shaking

FitPlugin is imported from '../view/plugins', which relies on the barrel file re‑exporting the symbol.
If a future optimisation removes the re‑export (very common when aiming for tree‑shakable bundles), this line will break while the local module path ('../view/plugins/FitPlugin') would still work.

-import type { FitPlugin } from '../view/plugins';
+import type { FitPlugin } from '../view/plugins/FitPlugin';

Consider importing directly from the concrete module (or keep the barrel but add an explicit re‑export and a unit‑test that guards it).


1031-1033: Graceful degradation if the plugin is absent

The optional‑chaining guards against a missing plugin, but from a UX standpoint silently doing nothing can confuse end‑users (the “Fit” toolbar button appears broken).

Recommend emitting a warning when getPlugin('fit') returns undefined so developers immediately notice a missing plugin registration:

- editor.graph.getPlugin<FitPlugin>('fit')?.fit();
+const fit = editor.graph.getPlugin<FitPlugin>('fit');
+if (fit) {
+  fit.fit();
+} else if (process.env.NODE_ENV !== 'production') {
+  // eslint-disable-next-line no-console
+  console.warn('[Editor] FitPlugin not registered – "fit" action skipped.');
+}

(This can be stripped in production builds by dead‑code‑elimination.)

packages/core/src/view/plugins/FitPlugin.ts (2)

21-23: keep2digits introduces unnecessary string allocation

Number(value.toFixed(2)) allocates an intermediate string each time.
For hot paths you can avoid this with simple arithmetic rounding:

-function keep2digits(value: number): number {
-  return Number(value.toFixed(2));
-}
+function keep2digits(value: number): number {
+  return Math.round(value * 100) / 100;
+}

Small, but measurable in very large graphs that call fitCenter frequently.


179-217: Round applied scale for deterministic re‑fits

fitCenter ends with keep2digits, but fit applies newScale directly.
Because of floating‑point artefacts successive fit() calls can accumulate tiny translation errors that move the diagram.

Consider re‑using keep2digits here as well:

-          view.scaleAndTranslate(newScale, x0, y0);
+          view.scaleAndTranslate(keep2digits(newScale), x0, y0);

Keeps the behaviour symmetrical with fitCenter and eliminates pixel‑creep.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 7cac321 and 5fad3ad.

📒 Files selected for processing (7)
  • CHANGELOG.md (1 hunks)
  • packages/core/src/editor/Editor.ts (2 hunks)
  • packages/core/src/view/Graph.ts (0 hunks)
  • packages/core/src/view/plugins/FitPlugin.ts (4 hunks)
  • packages/html/stories/OrgChart.stories.js (1 hunks)
  • packages/html/stories/ZoomAndFit.stories.ts (2 hunks)
  • packages/website/docs/usage/migrate-from-mxgraph.md (1 hunks)
💤 Files with no reviewable changes (1)
  • packages/core/src/view/Graph.ts
🔇 Additional comments (6)
packages/html/stories/OrgChart.stories.js (1)

287-288: Updated to use the new FitPlugin API correctly.

The code now properly accesses the fit functionality through the plugin system using graph.getPlugin('fit')?.fit() instead of directly calling graph.fit(). This aligns with the architectural changes where the fit method was moved from Graph to FitPlugin.

CHANGELOG.md (1)

12-14: Good documentation of breaking changes.

The changelog clearly documents that:

  1. The Graph.fit method has been moved to FitPlugin
  2. The minFitScale and maxFitScale properties have also been moved
  3. The method signature has been updated to accept a single parameter object

This provides users with clear information about what has changed and how it impacts their code.

packages/website/docs/usage/migrate-from-mxgraph.md (1)

359-367: Comprehensive migration guidance for the fit functionality.

The documentation accurately explains:

  1. The fit() method has moved to FitPlugin
  2. It now accepts a single parameter object instead of multiple positional parameters
  3. The minFitScale and maxFitScale properties have also moved to FitPlugin

This clear guidance will help users migrate their code to the new API structure.

packages/html/stories/ZoomAndFit.stories.ts (3)

76-77: Good practice: stored plugin reference for reuse.

Storing the FitPlugin reference in a variable is more efficient than calling getPlugin() multiple times, especially when the plugin is used in multiple places.


89-99: Successfully migrated to the new options-based API.

The code now correctly uses the new fit and fitCenter methods with option objects, passing the margin parameter and other configuration options like ignoreHeight and ignoreWidth. This approach is more flexible and maintainable compared to positional arguments.


17-17: Import properly updated to include FitPlugin type.

The import statement has been updated to include the FitPlugin type, which is necessary for proper TypeScript typing when getting the plugin with getPlugin<FitPlugin>('fit').

@tbouffard tbouffard marked this pull request as draft April 18, 2025 05:33
This change better split responsibilities (reduce the amount of things done directly in Graph) and will improve the tree-shaking in the future.

Passing parameters to `Graph.fit` is now simpler. The previous implementation used several positional parameters, which could be hard to follow and maintain.
This change:
  - Improves the readability of the method call.
  - Minimizes the need to pass many default values.
  - Aligns the API with more modern, maintainable patterns.

In addition, the implementation simplify min/max scale management

BREAKING CHANGES: the `AbstractGraph.fit` method moved to `FitPlugin`, as well as the `minFitScale` and `maxFitScale` properties.
The method now accepts a single parameter, mainly to minimize the need to pass many default values.
@tbouffard tbouffard force-pushed the refactor/move_Graph.fit_in_FitPlugin branch from 5fad3ad to b557a6a Compare May 19, 2025 17:32
@sonarqubecloud
Copy link

@tbouffard tbouffard changed the title refactor!: move Graph.fit to FitPlugin refactor!: move AbstractGraph.fit to FitPlugin May 19, 2025
@tbouffard tbouffard marked this pull request as ready for review May 19, 2025 17:41
@tbouffard tbouffard merged commit 0e6d8e2 into main May 19, 2025
8 checks passed
@tbouffard tbouffard deleted the refactor/move_Graph.fit_in_FitPlugin branch May 19, 2025 17:46
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

refactor Code refactoring

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant