Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings
/corePublic

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 ourterms of service andprivacy statement. We’ll occasionally send you account related emails.

Already on GitHub?Sign in to your account

Open
baozjj wants to merge1 commit intovuejs:main
base:main
Choose a base branch
Loading
frombaozjj:feat/runtime-core-unwrap-fragment

Conversation

baozjj
Copy link

@baozjjbaozjj commentedJul 1, 2025
edited by coderabbitaibot
Loading

Background

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

This nesting creates practical issues in real-world applications, especially in component libraries. For example, inTencent's open source component library TDesign, components likeAlert 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 toflatten such vnode structures.


This PR

This PR introduces a new internal helper:unwrapFragment(vnodes: VNode[] | undefined): VNode[], which recursively flattens allFragment 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

constflattened=unwrapFragment(slots.default?.())// Use flattened.length or inspect flattened[i].type safely<!--Thisisanauto-generatedcomment:releasenotesbycoderabbit.ai-->##SummarybyCodeRabbit***NewFeatures***Introducedautilitytoflattenarraysofvirtualnodesbyunwrappingnestedfragmentnodes.*Addedamethodtoidentifyfragmentvirtualnodes.*Exposedthenewunwrappingutilityforexternaluse.***Tests***Addedcomprehensiveteststoverifycorrectunwrappingoffragmentnodesinvariousscenarios.<!-- end of auto-generated comment: release notes by coderabbit.ai -->

@coderabbitaicoderabbitai
Copy link

coderabbitaibot commentedJul 1, 2025
edited
Loading

Walkthrough

A new utility function,unwrapFragment, is introduced to flatten arrays of virtual nodes by recursively unwrapping all fragment nodes. Accompanying this, a type guardisFragmentVNode 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.tsAddedunwrapFragment utility to recursively flatten fragment nodes in vnode arrays.
packages/runtime-core/src/vnode.tsAddedisFragmentVNode function to check if a vnode is a fragment.
packages/runtime-core/src/index.tsExportedunwrapFragment from the main runtime-core index.
packages/runtime-core/tests/unwrapFragment.spec.tsIntroduced tests covering all main behaviors and edge cases forunwrapFragment.

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

  • 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 oursupport 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 togenerate 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 theconfiguration 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 ourDocumentation for detailed information on how to use CodeRabbit.
  • Join ourDiscord Community to get help, request features, and share feedback.
  • Follow us onX/Twitter for updates and announcements.

Copy link

@coderabbitaicoderabbitaibot 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 betweenba391f5 and582f16a.

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

TheisFragmentVNode function correctly implements a type guard following Vue's established patterns. It safely checks for a truthy vnode before accessing thetype property and correctly compares against theFragment symbol.

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

128-128:Export placement looks correct.

TheunwrapFragment 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[]))

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 assertionvnode.children as VNode[] is unsafe. Fragment children can be of typeVNodeNormalizedChildren which includesstring | 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 unsafelyasserts vnode.children as VNode[], which can cause runtime errors since childrenmay be other types like string or null. Fix this by adding a type check toconfirm vnode.children is an array before spreading and recursing, ensuringunwrapFragment 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.

shenjunjian reacted with thumbs up emoji

@edison1105edison1105 added 🛑 on holdThis PR can't be merged until other work is finished need discussion and removed 🛑 on holdThis PR can't be merged until other work is finished labelsJul 1, 2025
@baozjj
Copy link
Author

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

I've opened a corresponding RFC forunwrapFragment as suggested:
👉vuejs/rfcs#787

Sign up for freeto join this conversation on GitHub. Already have an account?Sign in to comment
Reviewers

@coderabbitaicoderabbitai[bot]coderabbitai[bot] left review comments

Assignees
No one assigned
Projects
None yet
Milestone
No milestone
Development

Successfully merging this pull request may close these issues.

2 participants
@baozjj@edison1105

[8]ページ先頭

©2009-2025 Movatter.jp