Skip to content

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

    • Custom elements now batch prop updates during patch operations and defer reactions until patching completes, reducing redundant renders.
  • Bug Fixes

    • Watchers on custom element props fire only for actual changes and behave consistently when multiple props are updated together or partially.
  • Tests

    • Added sync and async tests validating batched prop updates, watcher invocation counts, and correct render updates during/after patching.

@github-actions
Copy link

github-actions bot commented Jun 15, 2025

Size Report

Bundles

File Size Gzip Brotli
runtime-dom.global.prod.js 102 kB (+276 B) 38.7 kB (+87 B) 34.8 kB (+76 B)
vue.global.prod.js 160 kB (+276 B) 58.8 kB (+89 B) 52.4 kB (+136 B)

Usages

Name Size Gzip Brotli
createApp (CAPI only) 46.8 kB (+94 B) 18.3 kB (+39 B) 16.8 kB (+35 B)
createApp 54.8 kB (+94 B) 21.3 kB (+37 B) 19.5 kB (+45 B)
createSSRApp 59 kB (+94 B) 23.1 kB (+40 B) 21 kB (+30 B)
defineCustomElement 60.3 kB (+276 B) 23.1 kB (+85 B) 21 kB (+74 B)
overall 68.9 kB (+94 B) 26.5 kB (+38 B) 24.2 kB (+11 B)

@pkg-pr-new
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: ab92d97

@coderabbitai
Copy link

coderabbitai bot commented Jun 15, 2025

Walkthrough

Adds internal patch lifecycle hooks to component interface, invokes those hooks from the renderer when patching existing Vue custom elements, implements patching/batching state in VueElement to defer and flush prop updates, and adds tests (sync and async) verifying batched prop updates and watcher behavior.

Changes

Cohort / File(s) Change Summary
Core interface
packages/runtime-core/src/component.ts
Added internal methods _beginPatch(): void and _endPatch(): void to ComponentCustomElementInterface.
Renderer
packages/runtime-core/src/renderer.ts
When patching an existing element vnode (n1), detect Vue custom element (_isVueCE) and call _beginPatch() before and _endPatch() after patchElement(), with _endPatch() ensured in a finally block.
Custom element runtime
packages/runtime-dom/src/apiCustomElement.ts
Added private flags _patching and _dirty to VueElement. During a patch, pass !this._patching as shouldUpdate to _setProp, mark _dirty when prop values change, and implement _beginPatch() / _endPatch() to batch/defer updates and flush a single update at patch end if needed.
Tests
packages/runtime-dom/__tests__/customElement.spec.ts
Added synchronous and async tests under defineCustomElement that patch multiple props together and assert watcher invocation counts and updated render output reflecting batched updates.

Sequence Diagram(s)

sequenceDiagram
    participant Renderer
    participant VueElement
    participant ComponentInstance

    Renderer->>VueElement: detect _isVueCE on existing element (n1.el)
    Renderer->>VueElement: _beginPatch()
    Note right of VueElement: _patching = true\n_dirty = false
    Renderer->>VueElement: resolve and set multiple props (shouldUpdate = false)
    VueElement->>VueElement: on prop change -> _dirty = true
    Renderer->>Renderer: patchElement()  %% vnode patch runs (component updates)
    Renderer->>VueElement: _endPatch()
    Note right of VueElement: _patching = false\nif _dirty -> schedule/trigger update
    VueElement->>ComponentInstance: trigger update (batched)
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related PRs

Assessment against linked issues

Objective Addressed Explanation
Ensure watchers in a custom element see the latest values of other props when multiple props are updated together. (#12619) Batched prop updates during patch ensure watchers observe consolidated/latest prop values after patch end.

Poem

🐇
I nibble bugs beneath the moonlit keys,
I begin the patch and quiet the breeze.
Dirty flags wait while props align,
End the patch — watchers see values fine.
Hoppity hop, the DOM's in time!

Pre-merge checks and finishing touches

✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title Check ✅ Passed The title clearly and concisely describes the primary change in this pull request, namely batching custom element prop patching to fix watcher behavior, and follows the conventional commit format without extraneous detail.
Linked Issues Check ✅ Passed The changes implement internal patch lifecycle hooks, adjust prop update logic to batch changes during patching, and add tests that confirm watchers observe the latest prop values, directly addressing the stale-prop issue described in issue #12619.
Out of Scope Changes Check ✅ Passed All modifications—including interface method additions, runtime-core hook integration, runtime-dom batching logic, and tests—are focused on implementing batched prop patching for custom elements and do not introduce unrelated functionality.
Docstring Coverage ✅ Passed No functions found in the changes. Docstring coverage check skipped.
✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment

📜 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 fb4e8c7 and ab92d97.

📒 Files selected for processing (3)
  • packages/runtime-core/src/component.ts (1 hunks)
  • packages/runtime-dom/__tests__/customElement.spec.ts (1 hunks)
  • packages/runtime-dom/src/apiCustomElement.ts (4 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • packages/runtime-dom/tests/customElement.spec.ts
🔇 Additional comments (6)
packages/runtime-core/src/component.ts (1)

1273-1280: LGTM! Clean interface additions for patch lifecycle.

The addition of _beginPatch() and _endPatch() internal methods to the ComponentCustomElementInterface follows the existing pattern of internal lifecycle hooks and enables custom elements to batch prop updates during renderer patch operations.

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

232-233: Well-chosen flags for batching state.

The _patching and _dirty flags clearly track the batching lifecycle: _patching indicates an active batch session, while _dirty tracks whether any props changed during that session. Both default to false, which is correct for the initial state.


473-478: Correct integration of batching in property setter.

The property setter now passes !this._patching as the shouldUpdate parameter to _setProp, which correctly defers updates during patching while still reflecting attributes. When not patching, updates trigger immediately as before.


510-511: Proper dirty flag tracking.

Setting _dirty = true when a prop value changes ensures that a single update is triggered at patch end only if props actually changed during the batch, avoiding unnecessary updates when props remain unchanged.


706-709: Clean patch session initialization.

The _beginPatch() method correctly starts a patch session by enabling batching mode and resetting the dirty flag to track changes within the new batch.


714-719: Renderer lifecycle guarantees exception safety and no nested patches

  • try/finally around patchElement always calls _endPatch() (exception safety)
  • _beginPatch()/_endPatch() invoked once per patch cycle per instance (no nested calls)

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.

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

@edison1105
Copy link
Member

/ecosystem-ci run

@vuejs vuejs deleted a comment from edison1105 Sep 1, 2025
@vue-bot
Copy link
Contributor

vue-bot commented Sep 1, 2025

📝 Ran ecosystem CI: Open

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

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