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 isRoot was not set correctly when set entity.parent #2597

Open
wants to merge 6 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

  • New Features

    • Introduced a unified approach for managing transitions between elements and scenes.
    • Enhanced tracking of modifications to parent-child relationships and sibling indices of entities.
  • Refactor

    • Streamlined the handling of element relationships, ensuring smoother updates when adding or removing components.
    • Improved consistency in updating active states during scene and parent changes.
    • Simplified logic for adding and removing entities from scenes.
  • Tests

    • Added new test cases to improve coverage for entity modification tracking and activation states.

Copy link

coderabbitai bot commented Mar 28, 2025

Walkthrough

The changes introduce a new static method _moveEntityTo in the Entity class that centralizes the logic for moving entities between parents and scenes. The parent setter, addChild, and removeChild methods were updated to leverage this new method, and redundant private parent management methods were removed. In the Scene class, methods handling root entities were simplified to use _moveEntityTo, reducing complexity in index handling and active state processing.

Changes

File(s) Summary
packages/core/.../Entity.ts Added static _moveEntityTo method; updated parent setter, addChild, and removeChild to use it; removed redundant private parent management methods.
packages/core/.../Scene.ts Modified createRootEntity, addRootEntity, and removeRootEntity to call _moveEntityTo, simplifying index handling and active state processing.
tests/src/core/.../Entity.test.ts Added tests for Entity class focusing on EntityModifyFlags, verifying behavior of addChild, activation states, and root entity status.

Possibly related PRs

  • Replace Transform #2464: The changes in the main PR, specifically the introduction of the _moveEntityTo method in the Entity class, are related to the modifications in the Scene class that also utilize this method for managing entity movements, indicating a direct connection at the code level.
  • Optimize the logic of remove and add entity. #1930: The changes in the main PR are related to those in the retrieved PR as both modify the Entity class's methods for managing parent-child relationships, specifically through the introduction of new static methods that streamline entity movement and management.
  • Fix the error when adapting the adaptation editor #2524: The changes in the main PR are related to the modifications in the Entity class, specifically the introduction of the _moveEntityTo method, while the retrieved PR focuses on changes to the _removeFromParent and _setParent methods in the same class, indicating a connection in their functionality regarding entity management.

Suggested labels

bug

Suggested reviewers

  • GuoLei1990
  • luzhuang

Poem

I'm a coding bunny, hopping with glee,
Entities now move as smooth as can be.
No more tangled logic in the code,
With _moveEntityTo lightening the load.
I nibble on carrots and bytes all day—
Celebrate the change in a rabbit's way!
🐰✨


📜 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 bfc77ab and e8319f0.

📒 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 (306-308)
  • parent (310-312)
  • scene (332-334)
  • Entity (21-812)
packages/core/src/Scene.ts (1)
  • Scene (27-491)
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: e2e (22.x)
🔇 Additional comments (4)
tests/src/core/Entity.test.ts (4)

1-1: LGTM: Import for EntityModifyFlags added.

The import line now correctly includes the EntityModifyFlags enum required for the new modify tests.


404-417: Good test case for fixing the isRoot flag issue.

This test properly verifies the fix for the issue where isRoot wasn't being set correctly when entity.parent was changed. It tests all important scenarios:

  1. Root entity added as a child (should lose root status)
  2. Child entity added back as a root (should regain root status)
  3. Entity movement between scene and parent hierarchies

The test accesses the private _isRoot property directly to verify the internal state, which is appropriate for unit testing.


419-514: Comprehensive test for entity activation state during hierarchy changes.

This test thoroughly verifies that entity activation states and lifecycle events work correctly when an entity is moved between:

  • Inactive parents (lines 457-471)
  • Active parents in the same scene (lines 472-492)
  • Different scenes (lines 493-513)

It properly tracks four distinct lifecycle events:

  • Component enable/disable (general activation)
  • Component enableInScene/disableInScene (scene-specific activation)

This is an excellent addition as it validates that the new _moveEntityTo method correctly maintains entity activation states.


531-588: Solid test for entity modification tracking.

This test verifies that the modification flags are properly triggered when:

  1. A child is added to a parent (lines 563-570)
  2. A child's sibling index changes (lines 572-578)
  3. A child is moved to a different parent (lines 580-586)

The test confirms both parent and child entities receive appropriate modification notifications, which is critical for maintaining the integrity of the entity hierarchy.

✨ 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 51.53846% with 63 lines in your changes missing coverage. Please review.

Project coverage is 68.91%. Comparing base (c5c86e9) to head (e8319f0).

Files with missing lines Patch % Lines
packages/core/src/Entity.ts 50.79% 62 Missing ⚠️
packages/core/src/Scene.ts 75.00% 1 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main    #2597      +/-   ##
==========================================
- Coverage   68.98%   68.91%   -0.07%     
==========================================
  Files         961      961              
  Lines      100339   100272      -67     
  Branches     8681     8662      -19     
==========================================
- Hits        69215    69101     -114     
- Misses      30864    30911      +47     
  Partials      260      260              
Flag Coverage Δ
unittests 68.91% <51.53%> (-0.07%) ⬇️

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)
packages/core/src/Entity.ts (2)

22-124: Consider splitting _moveEntityTo into smaller helper methods.
This method handles multiple operations—removal from old parent/scene, updating _isRoot, toggling active states, etc. Breaking it down into smaller functions could improve readability and maintainability. Also ensure thorough test coverage for all condition branches (e.g. old parent vs. new parent, old scene vs. new scene).

🧰 Tools
🪛 GitHub Check: codecov/patch

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


[warning] 31-32: packages/core/src/Entity.ts#L31-L32
Added lines #L31 - L32 were not covered by tests


[warning] 41-42: packages/core/src/Entity.ts#L41-L42
Added lines #L41 - L42 were not covered by tests


[warning] 55-56: packages/core/src/Entity.ts#L55-L56
Added lines #L55 - L56 were not covered by tests


[warning] 66-70: packages/core/src/Entity.ts#L66-L70
Added lines #L66 - L70 were not covered by tests


[warning] 77-123: packages/core/src/Entity.ts#L77-L123
Added lines #L77 - L123 were not covered by tests


532-538: Consider reusing _moveEntityTo in clearChildren.
Here, the code manually detaches and inactivates each child. For consistency, _moveEntityTo(child, null, null) could replicate the same steps in a standardized manner unless there's a specific need to handle it directly.

📜 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 8dd573a.

📒 Files selected for processing (2)
  • packages/core/src/Entity.ts (8 hunks)
  • packages/core/src/Scene.ts (3 hunks)
🧰 Additional context used
🧬 Code Definitions (1)
packages/core/src/Scene.ts (1)
packages/core/src/Entity.ts (1)
  • Entity (21-807)
🪛 GitHub Check: codecov/patch
packages/core/src/Scene.ts

[warning] 321-321: packages/core/src/Scene.ts#L321
Added line #L321 was not covered by tests

packages/core/src/Entity.ts

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


[warning] 31-32: packages/core/src/Entity.ts#L31-L32
Added lines #L31 - L32 were not covered by tests


[warning] 41-42: packages/core/src/Entity.ts#L41-L42
Added lines #L41 - L42 were not covered by tests


[warning] 55-56: packages/core/src/Entity.ts#L55-L56
Added lines #L55 - L56 were not covered by tests


[warning] 66-70: packages/core/src/Entity.ts#L66-L70
Added lines #L66 - L70 were not covered by tests


[warning] 77-123: packages/core/src/Entity.ts#L77-L123
Added lines #L77 - L123 were not covered by tests


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

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

302-302: Add test coverage for createRootEntity usage.
The new call to Entity._moveEntityTo(entity, null, this) is not covered by tests per static analysis. Please confirm or consider adding unit tests ensuring that isRoot is set correctly and that the entity’s state is properly initialized.


321-321: Verify index bounds in addRootEntity(index: number, entity: Entity).
_moveEntityTo() throws an error on out-of-bounds indices, which is correct. Consider adding a test that deliberately uses an invalid index to ensure proper error handling.

🧰 Tools
🪛 GitHub Check: codecov/patch

[warning] 321-321: packages/core/src/Scene.ts#L321
Added line #L321 was not covered by tests


323-323: Clean refactor for simple addition of root entities.
This direct _moveEntityTo call is consistent with the overall refactoring. No immediate concerns noted.


333-333: Consider coverage for entity removal from root.
Calling _moveEntityTo(entity) with no parent/scene detaches the entity from the scene. Please verify through tests that the entity no longer appears in _rootEntities and that isRoot is reset to false.

packages/core/src/Entity.ts (6)

310-310: Parent setter refactor confirmation.
Replacing internal parent logic with _moveEntityTo unifies entity movement. Confirm or add tests covering edge cases such as setting parent to null, reassigning the same parent, and cross-parent transfers.


451-454: Refactored addChild implementation.
This approach centralizes child addition logic under _moveEntityTo. It’s simpler to maintain, provided that tests confirm the new child’s siblingIndex and _parent references are set correctly.

🧰 Tools
🪛 GitHub Check: codecov/patch

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


462-464: Validation in removeChild.
Early-returning if the child’s _parent is different prevents unintended moves. The subsequent _moveEntityTo(child) detaches the child as expected. Please verify that removal flows are tested, including removing children from different hierarchies or lacking a valid parent link.


516-521: Unified flow in createChild.
Calling _moveEntityTo(child, this, this._scene) keeps all logic consistent. Make sure there are tests confirming that newly created children have the correct parent, scene, and active states right after creation.


638-639: Detach entity upon destroy.
Invoking _moveEntityTo(this) before setting this.isActive = false; neatly removes the entity from its parent or scene. Please confirm coverage so that tests verify the entity is fully detached and deactivated in the destruction workflow.


695-695: Refined _onParentChange hook.
This ensures the Transform updates appropriately whenever the parent changes. Confirm there’s adequate testing around transform updates in nested entity hierarchies.

@cptbtptpbcptdtptp
Copy link
Collaborator Author

cptbtptpbcptdtptp commented Mar 28, 2025

原先把逻辑收口在 _setParent ,但实际上 _setParent(null) 时,你无法区分此时 entity 是要被放逐到自由态还是被加入到根节点,因此,传入的参数应该包含 sceneparent,这样可以处理所有的情况:

  • 成为一个游离节点的子节点(scene == null, parent !== null)
  • 成为一个场景中节点的子节点(scene !== null, parent !== null)
  • 成为一个没有父节点的游离节点(scene == null, parent == null)
  • 成为根节点(scene !== null, parent == null)

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 (1)
packages/core/src/Entity.ts (1)

22-125:

❓ Verification inconclusive

Well-implemented centralized entity repositioning logic.

This new _moveEntityTo static method provides a centralized place for handling entity parent-scene relationships, which simplifies the code and ensures consistent behavior across different operations. It correctly handles the four scenarios mentioned in the PR comments:

  1. Becoming a child node of a free node (when scene is null and parent is not null)
  2. Becoming a child node within a scene (when both scene and parent are not null)
  3. Becoming a free node without a parent (when both scene and parent are null)
  4. Becoming a root node (when scene is not null and parent is null)

There's significant code duplication between the two main branches (when oldScene !== scene vs when oldScene === scene). Consider extracting common logic to reduce duplication and improve maintainability.

static _moveEntityTo(entity: Entity, parent: Entity = null, scene: Scene = null, index?: number): void {
  const { _parent: oldParent, _scene: oldScene } = entity;
-  if (oldScene !== scene) {
-    if (oldParent) {
-      Entity._removeFromChildren(oldParent._children, entity);
-      oldParent._dispatchModify(EntityModifyFlags.Child, oldParent);
-    } else if (oldScene) {
-      Entity._removeFromChildren(oldScene._rootEntities, entity);
-    }
-    // ...rest of the first block
-  } else {
-    if (oldParent !== parent) {
-      if (oldParent) {
-        Entity._removeFromChildren(oldParent._children, entity);
-        oldParent._dispatchModify(EntityModifyFlags.Child, oldParent);
-      }
-      // ...rest of the second block
-    } else {
-      !!parent && index !== undefined && (entity.siblingIndex = index);
-    }
-  }
+  // First handle the case when nothing changes except the index
+  if (oldParent === parent && oldScene === scene) {
+    !!parent && index !== undefined && (entity.siblingIndex = index);
+    return;
+  }
+  
+  // Remove from old parent or scene
+  if (oldParent) {
+    Entity._removeFromChildren(oldParent._children, entity);
+    oldParent._dispatchModify(EntityModifyFlags.Child, oldParent);
+  } else if (oldScene) {
+    Entity._removeFromChildren(oldScene._rootEntities, entity);
+  }
+  
+  // Then handle the remaining logic for cross-scene or same-scene movement
+  // ...rest of the method using common functions for active state changes
}

Several branches in this method aren't covered by tests according to code coverage reports. Run the following script to identify the missing test coverage:


🏁 Script executed:

#!/bin/bash
# Check which lines in _moveEntityTo aren't covered by tests

# List uncovered lines in the method
echo "Uncovered lines in _moveEntityTo method:"
ast-grep --pattern '$$$static _moveEntityTo$$$' | xargs rg -n "warning" "packages/core/src/Entity.ts#L" --with-filename

Length of output: 278


Please verify that all code branches in _moveEntityTo are covered by tests and consider refactoring duplicated logic.

The centralized entity repositioning logic is well implemented and correctly supports the four scenarios (free node child, scene child, free node without parent, and root node). However, there remains significant code duplication across the branches handling cross-scene versus same-scene changes. This redundancy not only affects maintainability but also makes it harder to be fully confident that all cases are exercised by tests.

Actionable points:

  • Code duplication: Consider extracting the common logic (for example, the removal from the old parent/scene and processing of active state changes) into helper functions to reduce duplication.
  • Test coverage: The automated script intended to identify uncovered lines did not produce conclusive output. Please manually verify that tests exercise all branches of this method, especially:
    • The transition of an entity between different scenes.
    • Parent changes within the same scene.
    • Updates where only the sibling index is modified.
static _moveEntityTo(entity: Entity, parent: Entity = null, scene: Scene = null, index?: number): void {
  const { _parent: oldParent, _scene: oldScene } = entity;
-  if (oldScene !== scene) {
-    if (oldParent) {
-      Entity._removeFromChildren(oldParent._children, entity);
-      oldParent._dispatchModify(EntityModifyFlags.Child, oldParent);
-    } else if (oldScene) {
-      Entity._removeFromChildren(oldScene._rootEntities, entity);
-    }
-    // ...rest of the first block
-  } else {
-    if (oldParent !== parent) {
-      if (oldParent) {
-        Entity._removeFromChildren(oldParent._children, entity);
-        oldParent._dispatchModify(EntityModifyFlags.Child, oldParent);
-      }
-      // ...rest of the second block
-    } else {
-      !!parent && index !== undefined && (entity.siblingIndex = index);
-    }
-  }
+  // First, if only the sibling index changes, update it and return early.
+  if (oldParent === parent && oldScene === scene) {
+    !!parent && index !== undefined && (entity.siblingIndex = index);
+    return;
+  }
+
+  // Remove from the old parent or scene
+  if (oldParent) {
+    Entity._removeFromChildren(oldParent._children, entity);
+    oldParent._dispatchModify(EntityModifyFlags.Child, oldParent);
+  } else if (oldScene) {
+    Entity._removeFromChildren(oldScene._rootEntities, entity);
+  }
+
+  // Handle remaining logic for repositioning and active state updates...
+  // (consider extracting common routines here to reduce duplication)
}

Note: The automated check for uncovered lines did not yield clear output, so please ensure via manual verification or an updated testing strategy that each branch (especially those handling different activation states) is adequately covered.

🧰 Tools
🪛 GitHub Check: codecov/patch

[warning] 29-30: packages/core/src/Entity.ts#L29-L30
Added lines #L29 - L30 were not covered by tests


[warning] 32-33: packages/core/src/Entity.ts#L32-L33
Added lines #L32 - L33 were not covered by tests


[warning] 44-45: packages/core/src/Entity.ts#L44-L45
Added lines #L44 - L45 were not covered by tests


[warning] 58-59: packages/core/src/Entity.ts#L58-L59
Added lines #L58 - L59 were not covered by tests


[warning] 67-71: packages/core/src/Entity.ts#L67-L71
Added lines #L67 - L71 were not covered by tests


[warning] 78-124: packages/core/src/Entity.ts#L78-L124
Added lines #L78 - L124 were not covered by tests

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between c008ebf and 501f044.

📒 Files selected for processing (2)
  • packages/core/src/Entity.ts (9 hunks)
  • tests/src/core/Entity.test.ts (2 hunks)
🧰 Additional context used
🧬 Code Definitions (1)
tests/src/core/Entity.test.ts (2)
packages/core/src/Entity.ts (4)
  • scene (332-334)
  • Entity (21-812)
  • parent (306-308)
  • parent (310-312)
packages/core/src/Scene.ts (1)
  • Scene (27-491)
🪛 GitHub Check: codecov/patch
packages/core/src/Entity.ts

[warning] 29-30: packages/core/src/Entity.ts#L29-L30
Added lines #L29 - L30 were not covered by tests


[warning] 32-33: packages/core/src/Entity.ts#L32-L33
Added lines #L32 - L33 were not covered by tests


[warning] 44-45: packages/core/src/Entity.ts#L44-L45
Added lines #L44 - L45 were not covered by tests


[warning] 58-59: packages/core/src/Entity.ts#L58-L59
Added lines #L58 - L59 were not covered by tests


[warning] 67-71: packages/core/src/Entity.ts#L67-L71
Added lines #L67 - L71 were not covered by tests


[warning] 78-124: packages/core/src/Entity.ts#L78-L124
Added lines #L78 - L124 were not covered by tests


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


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

🔇 Additional comments (11)
packages/core/src/Entity.ts (8)

311-311: LGTM! Simplified parent setter uses the new centralized method.

The parent setter now delegates to the _moveEntityTo method, which ensures _isRoot is properly set based on the parent-scene relationship.


347-354: Improved sibling index handling.

The code now properly considers whether the entity is a root entity (in a scene) or a child entity (has a parent) when setting the sibling index.

🧰 Tools
🪛 GitHub Check: codecov/patch

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


455-460: Simplified addChild method using the centralized approach.

The addChild method now consistently uses _moveEntityTo to handle the parent-child relationship, ensuring proper _isRoot property setting.

🧰 Tools
🪛 GitHub Check: codecov/patch

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


467-470: Added safety check for removeChild operation.

Good defensive programming with the check if (child._parent !== this) return; which prevents unnecessary operations when removing a child that doesn't belong to this entity.


526-526: Consistent usage of _moveEntityTo in createChild.

The createChild method now uses the centralized _moveEntityTo method to ensure consistency in how entities are added to the hierarchy.


538-544: Improved clearChildren implementation with explicit active state handling.

The updated implementation ensures proper handling of active state flags and scene owner during children clearing.


644-644: Simplified entity cleanup during destruction.

Using _moveEntityTo with no arguments effectively detaches the entity from its parent and scene, which is the correct behavior during destruction.


701-704: Simplified _onParentChange method.

The method is now streamlined to just handle transform parent changes and dispatch modify events, since the _isRoot setting is handled by _moveEntityTo.

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

469-524: Great test for entity modification flags.

This test thoroughly verifies that entity modification events are properly dispatched when:

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

It ensures the modification tracking system works correctly with the new _moveEntityTo method.


526-621: Comprehensive test for entity activation states.

This test covers complex scenarios involving:

  1. Free entities (without scene or parent)
  2. Entities with parent but no scene
  3. Entities in a scene
  4. Entities moved between scenes

It verifies that enable/disable events are properly triggered, which is critical when changing an entity's parent or scene.


623-636: Direct test for the isRoot property handling.

This test specifically validates the fix described in the PR - ensuring _isRoot is set correctly when:

  1. An entity is added as a root entity to a scene (_isRoot = true)
  2. An entity is set as a child of another entity (_isRoot = false)
  3. An entity is re-added as a root entity to a scene (_isRoot = true)

The test confirms that all the logic related to maintaining the _isRoot property is working correctly.

Copy link
Contributor

@jtabibito jtabibito left a comment

Choose a reason for hiding this comment

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

+1

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Bug Something isn't working
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
2 participants