Skip to content

fix(keep-alive): ignore comment nodes - #6026

Open
amirkian007 wants to merge 12 commits into
vuejs:mainfrom
amirkian007:fix-KeepAlive-Comments
Open

amirkian007 wants to merge 12 commits into
vuejs:mainfrom
amirkian007:fix-KeepAlive-Comments

Conversation

@amirkian007

@amirkian007 amirkian007 commented May 29, 2022 •

Copy link
Copy Markdown

KeepAlive does not ignore comments and the compiler throws an error when a component and a comment are wrapped with KeepAlive, which is obviously a bug.

error reproduction :

sfc.vuejs.org

thanks.

Summary by CodeRabbit

  • Bug Fixes

    • KeepAlive now ignores comment nodes when validating children, producing more accurate warnings and behavior when multiple children are present.
  • Tests

    • Added tests covering combinations of real and comment children for KeepAlive to ensure stable output and warning behavior.

✏️ Tip: You can customize this high-level summary in your review settings.

@netlify

netlify Bot commented Jun 9, 2022

Copy link
Copy Markdown

❌ Deploy Preview for vuejs-coverage failed.

Name Link
🔨 Latest commit 77f5d44
🔍 Latest deploy log https://app.netlify.com/sites/vuejs-coverage/deploys/62a223332e6a04000831b817

@amirkian007

Copy link
Copy Markdown
Author

@tony19 hi can you re-review my new changes please ? the re-request review button not working...

@tony19 tony19 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

LGTM. Thanks for the updates!

@iwusong

iwusong commented Jun 22, 2022

Copy link
Copy Markdown
Contributor

Comments cannot be ignored directly

@iwusong

iwusong commented Jun 22, 2022

Copy link
Copy Markdown
Contributor

@amirkian007

Copy link
Copy Markdown
Author

https://staging-cn.vuejs.org/api/application.html#app-config-compileroptions

comments need final rendering on dom

yeah comments should be rendered on the dom and the same problem exists for other built-in components too like Transition ,Suspense and etc . i dont know if it is a bug or not. but if it is, i think the fix for that should be submitted in another pr , this one is to just fix the warning issue with the compiler

@edison1105 edison1105 added the 🔨 p3-minor-bug Priority 3: this fixes a bug, but is an edge case that only affects very specific usage. label Nov 24, 2025
@coderabbitai

coderabbitai Bot commented Nov 24, 2025 •

Copy link
Copy Markdown

Walkthrough

Filtering of COMMENT nodes was added to KeepAlive handling across compiler and runtime: the compiler validates using non-comment children and emits a DEV error for >1; runtime selects the first non-comment child. A new helper to locate the first non-comment child was added to BaseTransition and tests were added/updated.

Changes

Cohort / File(s) Summary
Tests
packages/compiler-core/__tests__/transforms/transformElement.spec.ts
Adds checkWarning helper to capture parser errors and adds tests covering single child, single component with comments, multiple children (warning), multiple components with comments, and a snapshot asserting comments are ignored.
Compiler: transformElement
packages/compiler-core/src/transforms/transformElement.ts
Filters out COMMENT nodes when validating <KeepAlive> children; uses filtered children for single-child detection and emits DEV-only X_KEEP_ALIVE_INVALID_CHILDREN when >1 non-comment child.
Runtime: KeepAlive
packages/runtime-core/src/components/KeepAlive.ts
Removes prior warn import/usage; changes rawVNode to let; delegates multi-child resolution to new helper to locate the first non-comment child; if none found sets current to null and returns children.
Runtime: BaseTransition helper
packages/runtime-core/src/components/BaseTransition.ts
Adds exported locateFirstNonCommentChild(children, warnMessage) that finds the first non-comment child and flags if multiple were found (emits a warn). Refactors findNonCommentChild to delegate to the new helper for multi-child cases.

Sequence Diagram(s)

sequenceDiagram
    participant DevTemplate as Template Source
    participant Compiler as Compiler Transform
    participant Validator as KEEP_ALIVE Validator
    participant Runtime as KeepAlive Runtime
    participant BaseTrans as BaseTransition Helper
    participant DOM as Rendered Output

    DevTemplate->>Compiler: Parse <KeepAlive> with children
    Compiler->>Validator: Provide children list
    Validator->>Validator: Filter out COMMENT nodes
    alt >1 non-comment child (DEV)
        Validator-->>Compiler: Emit DEV error (X_KEEP_ALIVE_INVALID_CHILDREN)
        Compiler-->>DOM: Report validation error
    else <=1 non-comment child
        Validator-->>Compiler: Valid
        Compiler->>Runtime: Compile node (children preserved)
        Runtime->>BaseTrans: locateFirstNonCommentChild(children, warnMsg)
        alt multiple non-comment found
            BaseTrans-->>Runtime: return first non-comment (hasFound=true) + warn
        else single or none
            BaseTrans-->>Runtime: return child or none (hasFound=false)
        end
        Runtime->>DOM: Render selected child or none
    end
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

  • Pay special attention to:
    • packages/runtime-core/src/components/BaseTransition.ts — new exported API and warn behavior.
    • packages/compiler-core/src/transforms/transformElement.ts — correctness of COMMENT filtering and error location mapping.
    • packages/runtime-core/src/components/KeepAlive.ts — handling when no non-comment child exists and SSR branches.
    • Tests in packages/compiler-core/__tests__/transforms/transformElement.spec.ts — ensure they accurately capture warnings and snapshots.

Poem

🐰 I hop through nodes where comment breezes play,
Sniffing out the first real child to stay.
If many chatter, I nudge with a gentle peep,
Else I cradle the lone one safe and keep. 🥕

Pre-merge checks and finishing touches

❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstrings to improve docstring coverage.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title 'fix(keep-alive): ignore comment nodes' directly and clearly describes the main change across all modified files—handling of comment nodes within KeepAlive components.
✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment

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

Comment @coderabbitai help to get the list of available commands and usage tips.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

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/compiler-core/src/transforms/transformElement.ts (1)

147-169: LGTM! Comment filtering for KeepAlive is correctly implemented.

The compiler correctly filters comment nodes when processing <KeepAlive> and uses the filtered children for validation and error reporting. The validation only triggers in __DEV__ mode when multiple non-comment children are detected.

Minor: The comment on line 158 could be more precise:

-        //filter out potential comment nodes
+        // Filter out comment nodes for validation
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 2214f7a and e7f7b11.

⛔ Files ignored due to path filters (1)
  • packages/compiler-core/__tests__/transforms/__snapshots__/transformElement.spec.ts.snap is excluded by !**/*.snap
📒 Files selected for processing (3)
  • packages/compiler-core/__tests__/transforms/transformElement.spec.ts (1 hunks)
  • packages/compiler-core/src/transforms/transformElement.ts (3 hunks)
  • packages/runtime-core/src/components/KeepAlive.ts (1 hunks)
🧰 Additional context used
🧬 Code graph analysis (2)
packages/runtime-core/src/components/KeepAlive.ts (2)
packages/runtime-core/src/vnode.ts (1)
  • Comment (70-70)
packages/runtime-core/src/index.ts (1)
  • Comment (113-113)
packages/compiler-core/src/transforms/transformElement.ts (1)
packages/compiler-core/src/errors.ts (1)
  • createCompilerError (24-38)
🔇 Additional comments (8)
packages/compiler-core/src/transforms/transformElement.ts (1)

185-186: Single-child optimization correctly uses filtered children.

The single-child path now correctly uses the children variable (filtered for KEEP_ALIVE) instead of node.children, ensuring comments don't prevent the optimization.

packages/compiler-core/__tests__/transforms/transformElement.spec.ts (5)

1386-1401: Well-designed test helper.

The checkWarning helper correctly captures compiler errors via the onError callback and validates warning behavior based on the shouldWarn flag.


1403-1410: LGTM!

Test correctly verifies that <KeepAlive> with a single child does not trigger a warning.


1412-1421: LGTM! Critical test for the PR fix.

This test correctly verifies that <KeepAlive> with one component child and multiple comments does not trigger a warning, confirming that comments are properly ignored during validation.


1423-1443: LGTM! Negative test cases are correctly implemented.

These tests verify that:

  1. Multiple component children correctly trigger a warning (lines 1423-1431)
  2. Comments don't suppress warnings when multiple component children are present (lines 1433-1443)

1445-1456: LGTM! Snapshot test provides regression protection.

The snapshot test verifies that the generated code correctly handles comments within <KeepAlive>, ensuring stable output and preventing future regressions.

packages/runtime-core/src/components/KeepAlive.ts (2)

103-108: Verify if SSR comment handling in KeepAlive causes hydration issues.

The SSR path (lines 103-108) returns all children without filtering comments, while the client-side render function explicitly filters out comments when selecting the cached component (lines 280-287). No SSR-specific tests exist for KeepAlive with comment children.

This difference may be intentional (SSR is a simple pass-through since caching doesn't apply), but it's unclear whether returning comments in the SSR output causes hydration mismatches or other issues when the client-side rendering filters them. Please verify:

  1. Whether SSR should also filter comments for consistency
  2. If this behavior has been tested or documented
  3. Whether excluding this filtering causes any hydration or rendering issues in practice

278-292: Verify the all-comments edge case handling is intentional.

The code at lines 289-292 returns the children array when all children are comments, while the single-child path at lines 299-300 returns rawVNode directly. This inconsistency lacks test coverage—no runtime test validates the all-comments scenario. Confirm this behavior is correct or consider returning null or the first comment vnode to align with the single-child pattern.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

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/runtime-core/src/components/BaseTransition.ts (1)

273-305: Comment-aware child selection helper looks correct; consider clarifying empty / no-match semantics

The helper correctly:

  • Selects the first non-comment child in both DEV and prod.
  • Emits the existing <transition> multi-child warning only when there are 2+ non-comment children, ignoring pure comments.
  • Keeps prior behavior for single-child and all-comment arrays via the default child = children[0].

Minor, optional API nits:

  • locateFirstNonCommentChild assumes children.length > 0 (via children[0]). That’s true for all current call sites here (and, per the PR summary, likely for KeepAlive’s usage in multi-child paths), but it might be worth documenting this invariant in a short comment or asserting early in DEV to prevent accidental misuse.
  • Since the function returns { child, hasFound }, callers should treat hasFound as the authoritative flag for “found a non-comment vnode”. To avoid future misuse, you could either (a) make the return type child: VNode | undefined when hasFound is false, or (b) add a brief JSDoc noting that child may still be a comment (or undefined if children is empty) when hasFound is false.

Overall, the change cleanly centralizes the "ignore comment children but still warn on multiple real children" behavior and looks good.

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between e7f7b11 and b612a5e.

📒 Files selected for processing (3)
  • packages/compiler-core/src/transforms/transformElement.ts (2 hunks)
  • packages/runtime-core/src/components/BaseTransition.ts (1 hunks)
  • packages/runtime-core/src/components/KeepAlive.ts (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • packages/compiler-core/src/transforms/transformElement.ts
  • packages/runtime-core/src/components/KeepAlive.ts
🧰 Additional context used
🧬 Code graph analysis (1)
packages/runtime-core/src/components/BaseTransition.ts (1)
packages/runtime-core/src/vnode.ts (2)
  • VNode (160-257)
  • Comment (70-70)

@pkg-pr-new

pkg-pr-new Bot commented Nov 24, 2025

Copy link
Copy Markdown

Open in StackBlitz

@vue/compiler-core

npm i https://pkg.pr.new/@vue/compiler-core@6026

@vue/compiler-dom

npm i https://pkg.pr.new/@vue/compiler-dom@6026

@vue/compiler-sfc

npm i https://pkg.pr.new/@vue/compiler-sfc@6026

@vue/compiler-ssr

npm i https://pkg.pr.new/@vue/compiler-ssr@6026

@vue/reactivity

npm i https://pkg.pr.new/@vue/reactivity@6026

@vue/runtime-core

npm i https://pkg.pr.new/@vue/runtime-core@6026

@vue/runtime-dom

npm i https://pkg.pr.new/@vue/runtime-dom@6026

@vue/server-renderer

npm i https://pkg.pr.new/@vue/server-renderer@6026

@vue/shared

npm i https://pkg.pr.new/@vue/shared@6026

vue

npm i https://pkg.pr.new/vue@6026

@vue/compat

npm i https://pkg.pr.new/@vue/compat@6026

commit: b612a5e

@github-actions

Copy link
Copy Markdown

Size Report

Bundles

File Size Gzip Brotli
runtime-dom.global.prod.js 103 kB (+110 B) 39 kB (+54 B) 35.1 kB (+48 B)
vue.global.prod.js 161 kB (+139 B) 58.9 kB (+42 B) 52.4 kB (+68 B)

Usages

Name Size Gzip Brotli
createApp (CAPI only) 46.9 kB 18.3 kB 16.8 kB
createApp 55 kB 21.4 kB 19.6 kB
createSSRApp 59.3 kB 23.1 kB 21.1 kB
defineCustomElement 60.6 kB 23.1 kB 21.1 kB
overall 69.4 kB (+110 B) 26.7 kB (+55 B) 24.3 kB (+11 B)

@edison1105 edison1105 changed the title fix(compiler-core): KeepAlive should ignore comments fix(keep-alive): ignore comment nodes Nov 24, 2025
@amirkian007

Copy link
Copy Markdown
Author

@edison1105
Hello
Any chance this could be merged? It would be greatly appreciated , Thanks!

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

🔨 p3-minor-bug Priority 3: this fixes a bug, but is an edge case that only affects very specific usage. scope: keep-alive

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[keep-alive] recognized comment as elements

5 participants