Skip to content

refactor: apply internal improvements to editor classes#726

Merged
tbouffard merged 4 commits intomainfrom
refactor/improve_editor_internals
Mar 25, 2025
Merged

refactor: apply internal improvements to editor classes#726
tbouffard merged 4 commits intomainfrom
refactor/improve_editor_internals

Conversation

@tbouffard
Copy link
Copy Markdown
Member

@tbouffard tbouffard commented Mar 25, 2025

Improve null management, types and JSDoc in Editor and EditorPopupMenu.
Also fix the default value in the JSDoc of CellStateStyle.segment.

Summary by CodeRabbit

  • Refactor
    • Enhanced the reliability of editor interactions and pop-up menus via improved condition checks, streamlined error handling, and updated type validations.
  • Documentation
    • Revised configuration defaults and parameter descriptions to offer clearer guidance, including updates to the segment property in CellStateStyle.
  • Style
    • Refined formatting and comment consistency for improved code readability and maintainability.

Improve null management, types and JSDoc in `Editor` and `EditorPopupMenu`.
Also fix the default value in the JSDoc of `CellStateStyle.segment`.
@tbouffard tbouffard added the refactor Code refactoring label Mar 25, 2025
@coderabbitai
Copy link
Copy Markdown

coderabbitai bot commented Mar 25, 2025

Walkthrough

This pull request updates core editor and type files to improve type safety and code clarity. It introduces the isNullish utility function for null checks, updates method signatures to use the MaxPopupMenu type, refines parameter and return types, and adjusts documentation comments. Variable declarations have been updated from var to const, and some control flow conditions have been streamlined, enhancing overall code consistency.

Changes

File(s) Change Summary
packages/.../editor/Editor.ts
packages/.../editor/EditorPopupMenu.ts
Updated method signatures and parameter documentation to use MaxPopupMenu and Cell. Replaced direct null checks with the isNullish utility, adjusted error handling and control flow, converted var declarations to const, and refined iteration and return types (e.g., in createConditions).
packages/.../types.ts Updated documentation for the segment property in CellStateStyle, changing the default reference from ENTITY_SEGMENT to EntityRelationConnectorConfig.segment.

Possibly related PRs

Suggested labels

documentation


📜 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 defc60f and 885c3da.

📒 Files selected for processing (1)
  • packages/core/src/editor/Editor.ts (61 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • packages/core/src/editor/Editor.ts
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: build (windows-2022)

🪧 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.
    • Generate unit testing code for this file.
    • 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 generate unit testing code for this file.
    • @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 generate unit testing code.
    • @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.

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 resolve resolve all the CodeRabbit review comments.
  • @coderabbitai plan to trigger planning for file edits and PR creation.
  • @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.

Copy link
Copy Markdown

@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: 1

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between ebac765 and 648d68d.

📒 Files selected for processing (3)
  • packages/core/src/editor/Editor.ts (37 hunks)
  • packages/core/src/editor/EditorPopupMenu.ts (11 hunks)
  • packages/core/src/types.ts (1 hunks)
🧰 Additional context used
🧬 Code Definitions (1)
packages/core/src/editor/Editor.ts (2)
packages/core/src/util/Utils.ts (1)
  • isNullish (60-61)
packages/core/src/view/cell/Cell.ts (1)
  • Cell (73-886)
🪛 Biome (1.9.4)
packages/core/src/editor/EditorPopupMenu.ts

[error] 197-197: eval() exposes to security risks and performance issues.

See the MDN web docs for more details.
Refactor the code so that it doesn't need to call eval().

(lint/security/noGlobalEval)


[error] 320-320: eval() exposes to security risks and performance issues.

See the MDN web docs for more details.
Refactor the code so that it doesn't need to call eval().

(lint/security/noGlobalEval)

🔇 Additional comments (26)
packages/core/src/types.ts (1)

656-656: JSDoc default value reference updated for segment property.

The JSDoc @default reference has been updated from ENTITY_SEGMENT to EntityRelationConnectorConfig.segment, which better represents the actual source of the default value.

packages/core/src/editor/Editor.ts (15)

60-61: Added proper type imports to improve type safety.

These imports support the PR's goal of improving type definitions, especially for the createPopupMenu method.


65-70: Improved documentation formatting.

The JSDoc comments have been reformatted for better readability by removing unnecessary colons and improving spacing.


1246-1251: Replaced direct null check with isNullish utility.

Using the isNullish function standardizes null checks across the codebase, improving code consistency and safety by checking for both null and undefined.


1254-1259: Replaced direct null check with isNullish utility.

Consistent with the pattern of using isNullish throughout the codebase for better null handling.


1262-1267: Improved null check logic with isNullish.

Note the slightly different logic here compared to the previous examples - this checks if (isNullish(editor.outline)) rather than negating the check, which aligns with the intended flow control.


2438-2440: Enhanced type safety for createPopupMenu method.

The method signature has been updated to use the MaxPopupMenu type instead of any, improving type safety.


2439-2439: Use of non-null assertion with popupHandler!.

The code assumes popupHandler is not null here. This is likely safe based on initialization in the constructor, but it would be worth verifying that this property is always initialized before this method is called.

Can you confirm that popupHandler is always initialized before createPopupMenu is called? You may want to check the constructor and any potential early calls to this method.


2488-2495: Simplified conditional expression using && for better readability.

The code now uses a cleaner chained logical AND expression which improves readability while maintaining the same logic.


2503-2511: Improved null checking in cycleAttribute method.

Replaced direct null check with isNullish utility for both the cycleAttributeName and the returned value from consumeCycleAttribute.


2524-2526: Simplified loop condition.

The loop condition has been simplified while maintaining the same functionality.


2528-2533: Use of nullish coalescing operator for cleaner code.

The code now uses the nullish coalescing operator (??=) which is more concise than an if-statement for providing a default value. The use of non-null assertion with ! on getGeometry() assumes this method never returns null for this object.


2536-2538: Improved conditional logic readability.

The condition has been simplified while maintaining the same functionality.


2542-2564: Enhanced null handling in state check.

The code now uses simplified conditional structure with better checking of potential null/undefined values.


2576-2578: Simplified conditional logic for parent handling.

The code has been simplified while maintaining the same behavior of setting the parent to the default parent.


2589-2593: Improved null check condition.

The code now uses a simplified check for the vertex being non-null before proceeding with operations on it.

packages/core/src/editor/EditorPopupMenu.ts (10)

26-26: Improved code quality with isNullish utility import

Adding the utility function for checking null/undefined values standardizes and centralizes this logic across the codebase, improving consistency and maintainability.


125-126: Documentation improvement

Correctly specifying the type as Cell in the JSDoc comment improves type clarity and documentation accuracy.


151-153: Better type documentation in JSDoc

The parameter documentation now correctly specifies MaxPopupMenu and Cell types, which aligns with the actual implementation and improves code understanding.


161-161: Enhanced null checking with isNullish utility

Replacing the direct null check with the isNullish utility improves code consistency and makes the null/undefined handling more robust.


171-174: Improved parameter documentation

The JSDoc comments now properly reference the correct types, which enhances documentation accuracy and helps developers understand the API better.


184-184: Enhanced type safety with Record<string, boolean>

Replacing the any type with a more specific Record<string, boolean> type improves type safety and code clarity, making it explicit what kind of data structure is expected.


194-194: Consistent null checking with isNullish

Using the isNullish utility function for all null checks across the codebase results in more consistent and maintainable code.

Also applies to: 202-202, 209-209


278-280: Improved null checking in clickHandler

Replacing the direct null check with the isNullish utility maintains consistency with the rest of the codebase.


296-296: Better type information with explicit return type

Adding an explicit return type Record<string, boolean> to the createConditions method provides better type information and makes the method's contract clearer.


317-326: Improved code readability with modern JavaScript constructs

Refactoring the iteration over condition nodes to use a for...of loop with Array.from improves code readability and maintainability. Using isNullish for the name check maintains consistency.

🧰 Tools
🪛 Biome (1.9.4)

[error] 320-320: eval() exposes to security risks and performance issues.

See the MDN web docs for more details.
Refactor the code so that it doesn't need to call eval().

(lint/security/noGlobalEval)

if (isNullish(condition) || conditions[condition]) {
let as = item.getAttribute('as')!;
as = Translations.get(as) || as;
const funct = eval(getTextContent(<Text>(<unknown>item)));
Copy link
Copy Markdown

@coderabbitai coderabbitai bot Mar 25, 2025

Choose a reason for hiding this comment

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

💡 Verification agent

🧩 Analysis chain

Security issue: Use of eval() poses security risks

The use of eval() to execute code from text content exposes the application to security risks and performance issues. This isn't a new issue introduced in this PR, but should be addressed in future work.

Consider refactoring to avoid using eval() by implementing a safer alternative like:

- const funct = eval(getTextContent(<Text>(<unknown>item)));
+ // Parse the function content safely or use a function registry approach
+ const functionContent = getTextContent(<Text>(<unknown>item));
+ const funct = new Function('editor', 'cell', 'evt', functionContent);

Note that even new Function() has security implications but is generally safer than eval(). A better approach would be to use a predefined function registry or a more structured configuration format that doesn't require dynamic code evaluation.

Also applies to: 320-320


🏁 Script executed:

#!/bin/bash
# Check for usage of eval() in the EditorPopupMenu.ts file around the reported lines (197 and 320)
rg -n "eval\(getTextContent" packages/core/src/editor/EditorPopupMenu.ts

Length of output: 220


Attention: Mitigate eval() Security Vulnerability in EditorPopupMenu.ts

It has been verified that eval() is used in two locations in packages/core/src/editor/EditorPopupMenu.ts:

  • Line 197:
    const funct = eval(getTextContent(<Text>(<unknown>item)));
  • Line 320:
    const funct = eval(getTextContent(<Text>(<unknown>condNode)));

The dynamic evaluation of code via eval() poses significant security and performance risks. While replacing eval() with new Function() is an improvement—since it avoids some of the pitfalls of eval()—it still carries inherent risks. A more robust solution would be to remove dynamic code execution entirely in favor of a predefined function registry or a structured configuration that safely handles dynamic behavior.

For example, consider refactoring as follows:

- const funct = eval(getTextContent(<Text>(<unknown>item)));
+ // Safely parse function content or use a function registry approach
+ const functionContent = getTextContent(<Text>(<unknown>item));
+ const funct = new Function('editor', 'cell', 'evt', functionContent);

(Apply a similar approach to the code at line 320.)

This issue remains critical and should be prioritized for future work to ensure the application’s security.

🧰 Tools
🪛 Biome (1.9.4)

[error] 197-197: eval() exposes to security risks and performance issues.

See the MDN web docs for more details.
Refactor the code so that it doesn't need to call eval().

(lint/security/noGlobalEval)

Copy link
Copy Markdown
Member Author

@tbouffard tbouffard Mar 25, 2025

Choose a reason for hiding this comment

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

For now, we are going to keep the "eval" call as the implementation is supposed to be loaded from a XML configuration.
This will be later review to see if it is possible to find alternatives. See #722 which tracks this problem.

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

@tbouffard I understand your decision to keep the eval() calls for now given the XML configuration loading requirements. This is a reasonable approach to handle the refactoring incrementally, focusing first on null management improvements. I'll make a note that finding alternatives to eval() is planned for future work.


✏️ Learnings added
Learnt from: tbouffard
PR: maxGraph/maxGraph#726
File: packages/core/src/editor/EditorPopupMenu.ts:197-197
Timestamp: 2025-03-25T14:13:25.214Z
Learning: The team has decided to keep using `eval()` in EditorPopupMenu.ts as the implementation is loaded from XML configuration. Finding alternatives to `eval()` for improved security is planned for future work.

Note: Learnings are effective only in the context of similar code segments. To apply general coding guidelines, please configure review instructions. You can manage existing learnings in the app.

@sonarqubecloud
Copy link
Copy Markdown

@tbouffard tbouffard merged commit 997db4a into main Mar 25, 2025
7 checks passed
@tbouffard tbouffard deleted the refactor/improve_editor_internals branch March 25, 2025 15:20
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