Skip to content

fix(custom-element): batch custom element prop patching #13478

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 2 commits into
base: main
Choose a base branch
from

Conversation

alex-snezhko
Copy link
Contributor

@alex-snezhko alex-snezhko commented Jun 15, 2025

close #12619

Applies prop updates on custom elements in batch before rendering instead of one at a time serially, resolving discrepancies in behavior compared to normal components.

Summary by CodeRabbit

  • New Features
    • Improved custom element update behavior to batch prop changes and defer updates until patching completes, resulting in more efficient and predictable rendering.
  • Bug Fixes
    • Ensured watchers on custom element props are triggered correctly and only when actual changes occur, including support for simultaneous prop updates.
  • Tests
    • Added tests to verify correct batching and watcher behavior for both synchronous and asynchronous custom elements.

Copy link

github-actions bot commented Jun 15, 2025

Size Report

Bundles

File Size Gzip Brotli
runtime-dom.global.prod.js 101 kB (+276 B) 38.5 kB (+87 B) 34.6 kB (+67 B)
vue.global.prod.js 159 kB (+276 B) 58.6 kB (+83 B) 52.2 kB (+35 B)

Usages

Name Size Gzip Brotli
createApp (CAPI only) 46.8 kB (+94 B) 18.3 kB (+38 B) 16.7 kB (+33 B)
createApp 54.7 kB (+94 B) 21.3 kB (+36 B) 19.5 kB (+37 B)
createSSRApp 59 kB (+94 B) 23.1 kB (+37 B) 21 kB (+36 B)
defineCustomElement 59.9 kB (+276 B) 23 kB (+95 B) 20.9 kB (+61 B)
overall 68.8 kB (+94 B) 26.5 kB (+39 B) 24.1 kB (+11 B)

Copy link

pkg-pr-new bot commented Jun 15, 2025

Open in StackBlitz

@vue/compiler-core

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

@vue/compiler-dom

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

@vue/compiler-sfc

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

@vue/compiler-ssr

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

@vue/reactivity

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

@vue/runtime-core

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

@vue/runtime-dom

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

@vue/server-renderer

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

@vue/shared

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

vue

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

@vue/compat

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

commit: 1354a62

Copy link

coderabbitai bot commented Jun 15, 2025

Walkthrough

This change introduces patching lifecycle hooks (_beginPatch and _endPatch) to Vue custom elements, updates the renderer to invoke these hooks during element patching, and modifies the custom element prop setting logic to batch and defer updates. New tests are added to verify correct watcher and prop update behavior.

Changes

Files/Paths Change Summary
packages/runtime-core/src/component.ts Added _beginPatch() and _endPatch() internal methods to ComponentCustomElementInterface.
packages/runtime-core/src/renderer.ts Updated processElement to call _beginPatch/_endPatch on Vue custom elements during patch.
packages/runtime-dom/src/apiCustomElement.ts Added _patching/_dirty flags and _beginPatch/_endPatch methods; batched prop updates.
packages/runtime-dom/__tests__/customElement.spec.ts Added tests verifying batched prop patching and watcher behavior for custom elements.

Sequence Diagram(s)

sequenceDiagram
    participant Renderer
    participant CustomElement (el)
    participant ComponentInstance

    Renderer->>CustomElement: _beginPatch()
    Renderer->>CustomElement: set multiple props
    CustomElement->>CustomElement: mark _dirty = true for changed props
    Renderer->>CustomElement: patchElement()
    Renderer->>CustomElement: _endPatch()
    CustomElement->>ComponentInstance: trigger update if _dirty and instance exists
Loading

Assessment against linked issues

Objective Addressed Explanation
Ensure that in Vue custom elements, when a watcher observes a prop, accessing other props in the listener yields their latest values. (#12619)

Suggested reviewers

  • edison1105

Poem

🐇
In the garden of code, a patching breeze,
Props now update with elegant ease.
Watchers awake, no longer confused,
All values are fresh, no longer misused.
With a hop and a test, the bug is gone—
Custom elements, code on!
🌱✨

✨ 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-dom/src/apiCustomElement.ts (2)

231-233: Consider clarifying lifecycle flags & guarding against stale _dirty

_patching + _dirty are clear, but after an out-of-patch _update() call (e.g. prop changed via DOM API), _dirty stays true.
While harmless, a permanently-true flag is misleading when inspecting instances and invites future misuse.

private _update() {
  const vnode = this._createVNode()
  if (this._app) vnode.appContext = this._app._context
  render(vnode, this._root)
+  // reset bookkeeping when we are outside a batched patch cycle
+  if (!this._patching) this._dirty = false
}

A one-liner reset keeps semantics tight.


494-502: Minor: avoid redundant _dirty = true when immediate update fires

When shouldUpdate is true and _update() is called synchronously, there is no benefit in keeping _dirty flagged.

if (val !== this._props[key]) {
-  this._dirty = true
+  // mark dirty only when the render will be deferred
+  if (!shouldUpdate || this._patching) this._dirty = true

Keeps the flag strictly associated with deferred work.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between c91afec and d54f6c8.

📒 Files selected for processing (4)
  • packages/runtime-core/src/component.ts (1 hunks)
  • packages/runtime-core/src/renderer.ts (1 hunks)
  • packages/runtime-dom/__tests__/customElement.spec.ts (1 hunks)
  • packages/runtime-dom/src/apiCustomElement.ts (4 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (1)
packages/runtime-core/src/renderer.ts (1)
packages/runtime-dom/src/apiCustomElement.ts (1)
  • VueElement (202-710)
🔇 Additional comments (4)
packages/runtime-core/src/component.ts (1)

1273-1280: Custom-element patch-lifecycle hooks exposed – looks good

The addition of _beginPatch() / _endPatch() in the ComponentCustomElementInterface aligns with the renderer changes and the concrete implementation in VueElement.
No issues spotted – signature and visibility (@internal) are appropriate.

packages/runtime-dom/src/apiCustomElement.ts (2)

460-468: shouldUpdate computation may skip updates if instance not yet mounted

Inside the generated setter we pass !this._patching to _setProp.
During pre-mount cycles (e.g. attributes parsed before connectedCallback), this._instance is still null, so _setProp will:

  1. mark _dirty,
  2. evaluate shouldUpdate === true,
  3. not call _update() because this._instance is falsy,
  4. leave _dirty set to true.

If the element mounts without going through a renderer patch cycle (_beginPatch/_endPatch), the first render happens with stale props.

Please double-check that all early attribute/property writes are followed by either _beginPatch/_endPatch or a later setter invocation so an update is eventually fired.


676-693: Great addition – batching hook integrates cleanly with renderer

The _beginPatch / _endPatch pair is straightforward and the finally{} invocation on the renderer side guarantees symmetry even on thrown errors – well done.

packages/runtime-dom/__tests__/customElement.spec.ts (1)

477-565: Solid coverage for batched prop patching

The two new test blocks exercise both sync and async scenarios and verify:

• DOM output
• watcher invocation counts
• no redundant updates on identical prop sets

This should reliably catch regressions in the new batching logic. 👍

Also applies to: 566-660

@edison1105
Copy link
Member

/ecosystem-ci run

@vue-bot
Copy link
Contributor

vue-bot commented Jun 16, 2025

📝 Ran ecosystem CI: Open

suite result latest scheduled
language-tools success success
radix-vue success success
primevue success success
nuxt success success
router success success
pinia success success
quasar success success
test-utils success success
vuetify success success
vant success success
vueuse success success
vue-simple-compiler success success
vite-plugin-vue success success
vue-i18n success success
vue-macros failure success
vitepress success success

slotScopeIds,
optimized,
)
if (n1.el && (n1.el as VueElement)._isVueCE) {
Copy link
Member

Choose a reason for hiding this comment

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

Can be changed to const isVueCE = !!(n1.el && (n1.el as any)._isVueCE) patchElement may cause n1 to be unmounted, but n1.el still has a value after patchElement

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Change applied

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Actually just tweaked slightly to something that I think is clearer and also has fewer casts, let me know what you think

@edison1105 edison1105 added ready to merge The PR is ready to be merged. 🔨 p3-minor-bug Priority 3: this fixes a bug, but is an edge case that only affects very specific usage. scope: custom elements labels Jun 16, 2025
@alex-snezhko alex-snezhko force-pushed the custom-element-batch-prop-patch branch from f695bc3 to 1354a62 Compare June 16, 2025 03:13
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/runtime-core/src/renderer.ts (1)

624-627: Remove redundant !! and duplicate casts for clearer intent

customElement is derived solely to hold either the element reference or null; the double-negation adds no value and forces an unnecessary boolean conversion.
Inlining the element reference also eliminates the repeated as VueElement cast.

-      const customElement = !!(n1.el && (n1.el as VueElement)._isVueCE)
-        ? (n1.el as VueElement)
-        : null
+      const el = n1.el as VueElement | null
+      const customElement = el && el._isVueCE ? el : null

This aligns with the Biome lint recommendation and slightly improves readability.

🧰 Tools
🪛 Biome (1.9.4)

[error] 624-624: Avoid redundant double-negation.

It is not necessary to use double-negation when a value will already be coerced to a boolean.
Unsafe fix: Remove redundant double-negation

(lint/complexity/noExtraBooleanCast)

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between f695bc3 and 1354a62.

📒 Files selected for processing (1)
  • packages/runtime-core/src/renderer.ts (1 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (1)
packages/runtime-core/src/renderer.ts (1)
packages/runtime-dom/src/apiCustomElement.ts (1)
  • VueElement (202-710)
🪛 Biome (1.9.4)
packages/runtime-core/src/renderer.ts

[error] 624-624: Avoid redundant double-negation.

It is not necessary to use double-negation when a value will already be coerced to a boolean.
Unsafe fix: Remove redundant double-negation

(lint/complexity/noExtraBooleanCast)

⏰ Context from checks skipped due to timeout of 90000ms (4)
  • GitHub Check: Redirect rules
  • GitHub Check: Header rules
  • GitHub Check: Pages changed
  • GitHub Check: test / unit-test-windows

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. ready to merge The PR is ready to be merged. scope: custom elements
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Using watch to observe a prop in a vue custom element, the other props accessed in the listener are the old values.
3 participants