Skip to content

feat(runtime-core): add unwrapFragment to flatten nested Fragment nodes in vnode arrays #13546

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

Open
wants to merge 1 commit into
base: main
Choose a base branch
from

Conversation

baozjj
Copy link

@baozjj baozjj commented Jul 1, 2025

Background

In Vue 3, when a slot returns multiple root nodes, Vue automatically wraps them in a Fragment. When slot content is passed through multiple layers of components, this leads to multiple levels of nested Fragment nodes.

This nesting creates practical issues in real-world applications, especially in component libraries. For example, in Tencent's open source component library TDesign, components like Alert internally inspect slot content to determine whether to display "expand/collapse" buttons based on vnode count. However, when these components are wrapped and slots are passed down, the slot content becomes wrapped in deeply nested Fragments, leading to incorrect logic.

Vue currently does not provide an official utility to flatten such vnode structures.


This PR

This PR introduces a new internal helper: unwrapFragment(vnodes: VNode[] | undefined): VNode[], which recursively flattens all Fragment nodes in a vnode array, exposing the "real" slot content.

This improves:

  • Accuracy of vnode inspection (e.g. checking slot length, types)
  • Component reusability when slots are forwarded through layers
  • Debuggability and DOM structure clarity in developer tools

Example Use Case

const flattened = unwrapFragment(slots.default?.())
// Use flattened.length or inspect flattened[i].type safely


<!-- This is an auto-generated comment: release notes by coderabbit.ai -->

## Summary by CodeRabbit

* **New Features**
  * Introduced a utility to flatten arrays of virtual nodes by unwrapping nested fragment nodes.
  * Added a method to identify fragment virtual nodes.
  * Exposed the new unwrapping utility for external use.

* **Tests**
  * Added comprehensive tests to verify correct unwrapping of fragment nodes in various scenarios.

<!-- end of auto-generated comment: release notes by coderabbit.ai -->

Copy link

coderabbitai bot commented Jul 1, 2025

Walkthrough

A new utility function, unwrapFragment, is introduced to flatten arrays of virtual nodes by recursively unwrapping all fragment nodes. Accompanying this, a type guard isFragmentVNode is added. The new utility is exported from the main index, and a comprehensive test suite is provided to verify its behavior in various scenarios.

Changes

File(s) Change Summary
packages/runtime-core/src/unwrapFragment.ts Added unwrapFragment utility to recursively flatten fragment nodes in vnode arrays.
packages/runtime-core/src/vnode.ts Added isFragmentVNode function to check if a vnode is a fragment.
packages/runtime-core/src/index.ts Exported unwrapFragment from the main runtime-core index.
packages/runtime-core/tests/unwrapFragment.spec.ts Introduced tests covering all main behaviors and edge cases for unwrapFragment.

Sequence Diagram(s)

sequenceDiagram
    participant Caller
    participant unwrapFragment
    participant isFragmentVNode

    Caller->>unwrapFragment: unwrapFragment(vnodes)
    alt vnodes is undefined or empty
        unwrapFragment-->>Caller: []
    else For each vnode in vnodes
        unwrapFragment->>isFragmentVNode: isFragmentVNode(vnode)
        alt vnode is fragment
            unwrapFragment->>unwrapFragment: unwrapFragment(vnode.children)
            unwrapFragment-->>unwrapFragment: ...flattened children
        else vnode is not fragment
            unwrapFragment-->>unwrapFragment: vnode
        end
    end
    unwrapFragment-->>Caller: flattened array
Loading

Poem

In the warren of code, a new path appears,
Fragments unwrapped, flattening our fears.
VNodes assemble, no nesting to hide—
Now children emerge, all side by side.
With tests to ensure it’s perfectly right,
The rabbit hops on, code shining bright! 🐇✨

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

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

🧹 Nitpick comments (2)
packages/runtime-core/src/unwrapFragment.ts (1)

4-5: Use English comments for consistency.

The codebase uses English comments throughout. Please translate the Chinese comment to English for consistency.

-/**
- * 展开 vnode 数组中所有 Fragment 节点,将它们的子节点平铺出来。
- */
+/**
+ * Recursively flatten all Fragment nodes in a vnode array, expanding their children.
+ */
packages/runtime-core/__tests__/unwrapFragment.spec.ts (1)

4-48: Comprehensive test suite with good coverage.

The test suite covers the main use cases well and follows proper testing patterns. Consider adding a test case for fragments with non-array children to ensure the function handles edge cases gracefully.

Consider adding this test case to cover edge cases:

+  it('handles Fragment with non-array children gracefully', () => {
+    // Create a fragment with string children (edge case)
+    const fragmentVNode: VNode = h(Fragment, null, 'text content')
+    const input = [fragmentVNode]
+    const result = unwrapFragment(input)
+    // Should not crash and handle gracefully
+    expect(result).toEqual([fragmentVNode])
+  })
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between ba391f5 and 582f16a.

📒 Files selected for processing (4)
  • packages/runtime-core/__tests__/unwrapFragment.spec.ts (1 hunks)
  • packages/runtime-core/src/index.ts (1 hunks)
  • packages/runtime-core/src/unwrapFragment.ts (1 hunks)
  • packages/runtime-core/src/vnode.ts (1 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (1)
packages/runtime-core/src/vnode.ts (1)
packages/runtime-core/src/index.ts (2)
  • VNode (252-252)
  • Fragment (113-113)
⏰ Context from checks skipped due to timeout of 90000ms (3)
  • GitHub Check: Redirect rules
  • GitHub Check: Header rules
  • GitHub Check: Pages changed
🔇 Additional comments (2)
packages/runtime-core/src/vnode.ts (1)

390-392: LGTM! Well-implemented type guard function.

The isFragmentVNode function correctly implements a type guard following Vue's established patterns. It safely checks for a truthy vnode before accessing the type property and correctly compares against the Fragment symbol.

packages/runtime-core/src/index.ts (1)

128-128: Export placement looks correct.

The unwrapFragment export is appropriately positioned and follows Vue's export conventions.

const result: VNode[] = []
for (const vnode of vnodes) {
if (isFragmentVNode(vnode)) {
result.push(...unwrapFragment(vnode.children as VNode[]))
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Fix unsafe type assertion.

The type assertion vnode.children as VNode[] is unsafe. Fragment children can be of type VNodeNormalizedChildren which includes string | VNodeArrayChildren | RawSlots | null. This could cause runtime errors if fragment children are not an array.

Apply this fix to handle the type safely:

-      result.push(...unwrapFragment(vnode.children as VNode[]))
+      const children = vnode.children
+      if (Array.isArray(children)) {
+        result.push(...unwrapFragment(children))
+      }

This ensures we only recurse when children is actually an array, preventing runtime errors.

🤖 Prompt for AI Agents
In packages/runtime-core/src/unwrapFragment.ts at line 11, the code unsafely
asserts vnode.children as VNode[], which can cause runtime errors since children
may be other types like string or null. Fix this by adding a type check to
confirm vnode.children is an array before spreading and recursing, ensuring
unwrapFragment is only called on arrays to prevent errors.

@edison1105
Copy link
Member

This is considered adding a new API and needs to go through the RFC process to gather feedback from community first.

@edison1105 edison1105 added 🛑 on hold This PR can't be merged until other work is finished need discussion and removed 🛑 on hold This PR can't be merged until other work is finished labels Jul 1, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants