Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix Entity._isRoot error and Entity modify error #2598

Open
wants to merge 3 commits into
base: main
Choose a base branch
from

Conversation

cptbtptpbcptdtptp
Copy link
Collaborator

@cptbtptpbcptdtptp cptbtptpbcptdtptp commented Mar 28, 2025

Please check if the PR fulfills these requirements

  • The commit message follows our guidelines
  • Tests for the changes have been added (for bug fixes / features)
  • Docs have been added / updated (for bug fixes / features)

What kind of change does this PR introduce? (Bug fix, feature, docs update, ...)

What is the current behavior? (You can also link to an open issue here)

What is the new behavior (if this is a feature change)?

Does this PR introduce a breaking change? (What changes might users need to make in their application due to this PR?)

Other information:

Summary by CodeRabbit

  • Enhancements
    • Improved management of entity relationships, ensuring accurate updates and notifications for hierarchy changes.
  • Tests
    • Expanded test coverage to verify root status, activation state handling, and modification event triggering.
    • Removed an outdated test to focus on more relevant scenarios.

Copy link

coderabbitai bot commented Mar 28, 2025

Walkthrough

The pull request refactors the Entity class in the core package to improve the management of sibling indices and parent-child relationships. It adjusts the logic in the setter for sibling indices to differentiate between root and non-root entities, ensures modification notifications are sent from the relevant parent, and updates the constructor behavior for parent assignment. Additionally, several new tests have been added to cover these behaviors, while an outdated test case has been removed.

Changes

File(s) Change Summary
packages/core/src/Entity.ts Refactored the sibling index setter to distinguish between root and non-root entities; updated _removeFromParent to dispatch modifications from the old parent; adjusted the constructor to mark entities as non-root when a parent is assigned.
tests/src/core/Entity.test.ts Added tests for the isRoot property, activation state changes, and parent-child modification tracking; removed the addChildAfterDestroy test to refocus coverage.

Sequence Diagram(s)

sequenceDiagram
    participant E as Entity
    participant P as Parent
    participant S as Scene

    E->>E: Set siblingIndex
    alt Entity is root
        E->>S: Update _rootEntities list
    else Entity is non-root
        E->>P: Retrieve parent and update _children list
        P->>P: Invoke _dispatchModify(EntityModifyFlags.Child)
    end

    note over E,P: Similar flow when removing from a parent
Loading

Possibly related PRs

Suggested labels

bug

Suggested reviewers

  • gz65555
  • GuoLei1990

Poem

Hop along, dear coder, in fields of change so bright,
I’m a bunny with a hop and a skip in pure delight.
Entity flows streamlined, from sibling to parent's call,
Tests bloom like carrots, ensuring balance for all.
A tale of careful tweaks – in code, we’ve made it right!
🐇🌻


📜 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 40c6b8a and 4f4b786.

📒 Files selected for processing (1)
  • tests/src/core/Entity.test.ts (3 hunks)
🧰 Additional context used
🧬 Code Definitions (1)
tests/src/core/Entity.test.ts (2)
packages/core/src/Entity.ts (4)
  • parent (201-203)
  • parent (205-207)
  • scene (227-229)
  • Entity (21-834)
packages/core/src/Scene.ts (1)
  • Scene (27-542)
🔇 Additional comments (4)
tests/src/core/Entity.test.ts (4)

404-417: Well-structured test for validating entity root status behavior

This test effectively verifies that the _isRoot property is correctly managed when an entity changes its hierarchy position. It tests three key scenarios:

  1. Initial creation as a root entity
  2. Assignment as a child (no longer root)
  3. Re-addition as a root entity after being a child

419-514: Comprehensive test for entity activation state management

This test thoroughly covers entity activation behavior across different hierarchy and scene contexts. It properly tracks all four event types (enable, disable, enableInScene, disableInScene) through various entity state transitions.

The test verifies important edge cases:

  • Initial activation state
  • Activation in detached hierarchies
  • Moving between different parents in the same scene
  • Moving between different scenes
  • Scene manager interactions

531-588: Good validation of entity modification notification system

This test effectively verifies that modification events are correctly dispatched when:

  1. A child is added to a parent
  2. A child's sibling index is modified
  3. A child is moved from one parent to another

The test confirms that notifications are sent to the appropriate entities with the correct modification flags, validating the fix for the entity modification error mentioned in the PR.


1-1: Properly imported the EntityModifyFlags enum

The addition of EntityModifyFlags to the imports supports the new test case for entity modification, ensuring proper type checking for the modification flags used in tests.

✨ Finishing Touches
  • 📝 Generate Docstrings

🪧 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

codecov bot commented Mar 28, 2025

Codecov Report

Attention: Patch coverage is 77.77778% with 2 lines in your changes missing coverage. Please review.

Project coverage is 68.99%. Comparing base (c5c86e9) to head (40c6b8a).

Files with missing lines Patch % Lines
packages/core/src/Entity.ts 77.77% 2 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main    #2598      +/-   ##
==========================================
+ Coverage   68.98%   68.99%   +0.01%     
==========================================
  Files         961      961              
  Lines      100339   100345       +6     
  Branches     8681     8687       +6     
==========================================
+ Hits        69215    69234      +19     
+ Misses      30864    30851      -13     
  Partials      260      260              
Flag Coverage Δ
unittests 68.99% <77.77%> (+0.01%) ⬆️

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

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

🚀 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.

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: 0

🧹 Nitpick comments (2)
tests/src/core/Entity.test.ts (2)

404-417: Added test for _isRoot property behavior

This test ensures that an entity's root status is correctly updated when:

  1. It's created as a root entity
  2. It's added as a child to another entity (no longer a root)
  3. It's added back to the scene as a root entity

This directly tests the fix for the Entity._isRoot error mentioned in the PR title.

Consider avoiding direct access to internal properties with @ts-ignore. Instead, you could test the behavior indirectly by checking if the entity is in scene._rootEntities or has a parent:

-      // @ts-ignore
-      expect(child._isRoot).eq(true);
+      expect(child.parent).eq(null);
+      expect(scene.getRootEntities().includes(child)).eq(true);

531-588: Added test for entity modification notifications

This test verifies the fix for the Entity modify error by ensuring:

  1. Parent entities receive Child modification notifications when children are added/removed
  2. Parent entities receive Child modification notifications when a child's sibling index changes
  3. Both old and new parents receive appropriate notifications when a child moves between parents

This directly tests the modifications to the _dispatchModify behavior in the Entity class.

Similar to the isRoot test, consider avoiding direct access to internal methods with @ts-ignore. You could potentially expose a public test method or test the behavior indirectly by observing the effects of the modifications.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between c5c86e9 and 40c6b8a.

📒 Files selected for processing (2)
  • packages/core/src/Entity.ts (3 hunks)
  • tests/src/core/Entity.test.ts (3 hunks)
🧰 Additional context used
🧬 Code Definitions (2)
tests/src/core/Entity.test.ts (2)
packages/core/src/Entity.ts (4)
  • parent (201-203)
  • parent (205-207)
  • scene (227-229)
  • Entity (21-834)
packages/core/src/Scene.ts (1)
  • Scene (27-542)
packages/core/src/Entity.ts (1)
packages/core/src/index.ts (1)
  • EntityModifyFlags (42-42)
🪛 GitHub Check: codecov/patch
packages/core/src/Entity.ts

[warning] 244-244: packages/core/src/Entity.ts#L244
Added line #L244 was not covered by tests


[warning] 630-630: packages/core/src/Entity.ts#L630
Added line #L630 was not covered by tests

⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: e2e (22.x)
🔇 Additional comments (5)
packages/core/src/Entity.ts (3)

695-695: Fixed _isRoot flag setting when parent is assigned

Explicitly setting _isRoot = false when a parent is assigned ensures that an entity can't be both a root entity and have a parent simultaneously, which resolves the Entity._isRoot error mentioned in the PR title.


243-249:

❓ Verification inconclusive

Enhanced siblingIndex setter logic to correctly handle root vs non-root entities

This change properly differentiates between root and non-root entities when setting the sibling index. For root entities, it correctly uses the scene's root entities collection, while for non-root entities it uses the parent's children collection and notifies the parent of the modification.


🏁 Script executed:

#!/bin/bash
# Verify test coverage for the siblingIndex setter
ast-grep --pattern $'set siblingIndex(value: number) {
  $$$
  if (this._isRoot) {
    $$$
  } else {
    $$$
  }
  $$$
}'

Length of output: 123


Below is an updated review comment reflecting our current findings. Note that the automated script using ast‑grep did not yield output, so please verify manually that the code snippet below indeed starts at line 243 in packages/core/src/Entity.ts:

Enhanced siblingIndex Setter – Verify Manual Test Coverage

  • The code now properly distinguishes between root and non‑root entities:

    • For root entities, it updates via the scene’s _rootEntities collection.
    • For non‑root entities, it updates using the parent’s _children collection and notifies the parent via _dispatchModify.
  • Since our automated search via ast‑grep produced no output, please confirm the snippet manually. You can use the following command to display lines 240–260:

    sed -n '240,260p' packages/core/src/Entity.ts

If the snippet matches the expected logic, the changes appear correctly implemented.

🧰 Tools
🪛 GitHub Check: codecov/patch

[warning] 244-244: packages/core/src/Entity.ts#L244
Added line #L244 was not covered by tests


630-630:

✅ Verification successful

Improved modification notification in _removeFromParent

Changed from this._dispatchModify to oldParent._dispatchModify, ensuring that the parent entity dispatches the modification notification when a child is removed, maintaining consistency with the overall entity notification model.


🏁 Script executed:

#!/bin/bash
# Verify test coverage for the _removeFromParent method
ast-grep --pattern $'_removeFromParent(): void {
  $$$
  oldParent._dispatchModify(EntityModifyFlags.Child, oldParent);
  $$$
}'

Length of output: 129


Action Required: Verify _removeFromParent Notification Change

The change to call oldParent._dispatchModify(EntityModifyFlags.Child, oldParent) (instead of this._dispatchModify) aims to ensure the parent entity dispatches the modification notification correctly. However, our initial ast-grep check produced no output, so please run the above rg command and manually verify that the intended change is present and correct in the _removeFromParent method.

  • File under review: packages/core/src/Entity.ts
  • Line of interest: 630 (or the corresponding block in _removeFromParent)
  • Code snippet to confirm:
        oldParent._dispatchModify(EntityModifyFlags.Child, oldParent);

Once the output confirms that this modification exists as expected within the _removeFromParent method, you can approve the changes.


🏁 Script executed:

#!/bin/bash
# Using rg to verify the _removeFromParent method usage and ensure that
# the change to use oldParent._dispatchModify(EntityModifyFlags.Child, oldParent) is present in the file.
rg -n '_removeFromParent' packages/core/src/Entity.ts

Length of output: 245


Action Required: Manual Verification of Notification Change

The previous verification using rg -n '_removeFromParent' did not confirm the presence of the updated notification call. Please run the above script, then manually verify that within the _removeFromParent method the modified call:

oldParent._dispatchModify(EntityModifyFlags.Child, oldParent);

is indeed present. This change is intended to ensure the proper dispatch to the parent entity rather than the child entity. If the updated call is present as expected, you can approve the changes.


🏁 Script executed:

#!/bin/bash
# Using rg to search for the modification notification in the _removeFromParent method.
rg -n 'oldParent\._dispatchModify' packages/core/src/Entity.ts

Length of output: 259


Final Verification: Modification Notification Updated Correctly

The change where the parent entity dispatches the modification notification (i.e., using oldParent._dispatchModify(EntityModifyFlags.Child, oldParent); instead of this._dispatchModify) in the _removeFromParent method has been verified in packages/core/src/Entity.ts at line 630. No additional changes are required.

🧰 Tools
🪛 GitHub Check: codecov/patch

[warning] 630-630: packages/core/src/Entity.ts#L630
Added line #L630 was not covered by tests

tests/src/core/Entity.test.ts (2)

1-1: Added EntityModifyFlags import

Correctly added the EntityModifyFlags import required for the new tests.


419-514: Added comprehensive test for entity activation states

This test thoroughly verifies entity activation behavior when:

  • Adding/removing entities from different parents
  • Moving entities between scenes
  • Checking the event counts for enable/disable/enableInScene/disableInScene

The test ensures that activation state changes trigger the appropriate callbacks and updates internal state correctly.

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.

Infinite Loop in parent.destroy() When Setting parent Property Due to Unset _isRoot Flag
1 participant