Repository navigation
Preserve matching prerendered DOM during interactive activation - #70270
ilonatommy wants to merge 18 commits into
Conversation
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
|
https://github.com/dotnet/aspnetcore/pull/70270/commits proposes a very simple version of all-or-nothing algorithm where each mismatch replaces the whole DOM. We could do better and reuse matching parts and replace only the parts that cannot be matched safely. We will call the improvement a v2. Node updateSSR: If interactive rendering changes only the span, v2 would replace Node removalSSR: If interactive rendering removed span, v2 would replace Node insertionSSR: If interactivity inserted a The algorithm:
|
Co-authored-by: Copilot App <223556219+copilot@users.noreply.github.com>
Share element insertion and attribute traversal, avoid redundant frame-map copies and text allocations, and centralize descendant-frame skipping. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Defer new markup element attachment until normal renderer traversal. Fall back to root replacement when DOM differences would invalidate retained scripts or custom elements. Add browser regressions and clarify planning and deferred-operation names. Co-authored-by: Copilot App <223556219+copilot@users.noreply.github.com>
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
|
Fixed in a9efc5d by adding the |
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Keep all distinct reconciliation scenarios with representative WebAssembly integration coverage and explicit Auto runtime-selection tests. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Remove generic WebAssembly smoke rows and the added Auto preservation tests. Keep shared scenarios on Server, the WebAssembly router smoke test, and distinct EditForm expectations. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Reduce the prerendered DOM browser matrix from 55 to 37 cases. Replace ten structural scenarios with fourteen unit cases using the production renderer and batch readers, remove eight overlapping cases, and simplify unused test fixtures. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Keep the reduced 37-case browser matrix without the added unit-test suite and custom render-batch serializer. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Consolidate positional scenarios, reuse Selenium interaction helpers, and retain one initializer replacement case. Remove coverage of SSR/interactive inconsistencies tracked in dotnet#70498 and clarify the highlighted-text test name. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
|
Additional info for v2. Multiple renders of one component in the initial batchScenario: parent-child components. Child requests the parent to call When render batch arrives to the browser its state is "final", it means no other renders can be appended to it, no matter if they are sync or async. Using this knowledge we could build the "final state" combining all the diffs from the batch and compare only interactive final state with SSR final state. However, each diff describes changes rather than a complete final tree. Comparing prerendered HTML with the batch’s final state would require tracking insertions, removals, moves and nested component updates, then attaching events and component references without replaying intermediate changes onto the adopted DOM. This would substantially expand the adoption algorithm and its maintenance burden. We reject this optimization to keep the v2 implementation conservative. When multiple renders of same component are detected, we fall back to the whole-root replacement. |
Share renderer helpers, remove redundant guards, and replace unused child counts with Boolean planning results and ordered operation lists. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
|
v2 When do we keep existing DOM?flowchart TD
ATTACH["Attach a root<br/>for interactivity"] --> END{"Does its prerendering<br/>information include<br/>an end comment?"}
END -- No --> NORMAL["When the root renders,<br/>clear its existing content<br/>and render normally"]
END -- Yes --> BEFORE{"Has this root been attached<br/>for interactivity before?"}
BEFORE -- Yes --> NORMAL
BEFORE -- No --> WAIT["Wait for the next<br/>completed batch"]
WAIT --> RENDER{"Does this batch include<br/>a render of this root?"}
RENDER -- No --> WAIT
RENDER -- Yes --> RESUME{"Did server-circuit resume<br/>cancel this root's attempt<br/>to keep its DOM?"}
RESUME -- Yes --> NORMAL
RESUME -- No --> MARKERS{"Are the start and end comments<br/>attached under<br/>the same parent?"}
MARKERS -- No --> NORMAL
MARKERS -- Yes --> PLAN["Compare root and child content<br/>using diagram 2"]
PLAN -- "Repeated component render<br/>or unhandled frame kind" --> NORMAL
PLAN -- "Comparison completed" --> LEFTOVER["Finish pending text<br/>and record removal<br/>of leftover root nodes"]
LEFTOVER --> INITIALIZER{"Would we change content<br/>while keeping a script,<br/>custom element or element<br/>with an is attribute?"}
INITIALIZER -- Yes --> NORMAL
INITIALIZER -- No --> APPLY["Apply the plan,<br/>then run normal rendering<br/>with the kept nodes"]
How do we compare the content?flowchart TD
COMPONENT["Inspect a root<br/>or child component"] --> REPEATED{"Did this component render<br/>more than once<br/>in this batch?"}
REPEATED -- Yes --> REJECT["Stop and return<br/>whole-root fallback<br/>to diagram 1"]
REPEATED -- No --> DIFF{"Does this component<br/>have a diff in this batch?"}
DIFF -- No --> RETURN["Return to the caller;<br/>for the root,<br/>return to diagram 1"]
DIFF -- Yes --> NEXT{"More expected frames<br/>in this list?"}
NEXT -- No --> RETURN
NEXT -- Yes --> KIND{"What kind of content<br/>is next?"}
KIND -- Element --> MATCH{"Does the current element match<br/>the tag, namespace, attributes<br/>and original form defaults?"}
MATCH -- Yes --> KEEP["Keep the element;<br/>compare its children<br/>recursively"]
KEEP --> NEXT
MATCH -- No --> REPLACE["Record replacement<br/>of this node and subtree,<br/>or insertion<br/>if no node is here"]
REPLACE --> NEXT
KIND -- Text --> TEXT["Add this piece to pending text;<br/>compare the combined text<br/>when the run ends"]
TEXT --> NEXT
KIND -- "Child component" --> COMMENT["Record its component-boundary<br/>comment"]
COMMENT --> COMPONENT
KIND -- Region --> REGION["Inspect the region's frames<br/>without adding a DOM wrapper"]
REGION --> NEXT
KIND -- "Raw HTML" --> RAW["Parse the HTML;<br/>record its boundary comment;<br/>compare parsed nodes<br/>recursively in order"]
RAW --> NEXT
KIND -- "Element reference<br/>or named event" --> SKIP["No DOM matching;<br/>normal rendering handles it"]
SKIP --> NEXT
KIND -- "Any other frame kind" --> REJECT
|
There was a problem hiding this comment.
🟡 Changes recommended
Active rendering issues can restore stale textarea content, crash updates to empty multiple-selects, and duplicate event handlers when scripts are reexecuted.
3 open issues
What changed in this PR
This PR reuses prerendered DOM during Blazor’s first interactive render to preserve browser state and avoid restarting media, animations, and other unchanged content.
Changes:
- Adds ordered DOM matching, positional replacement, and whole-root fallback for unsupported output or retained initializers affected by changes.
- Integrates DOM adoption with rendering, logical ownership, event handlers, and deferred form values.
- Adds browser coverage, supporting fixtures, namespace tests, and architecture documentation.
| File | Description |
|---|---|
src/Components/Web.JS/test/LogicalElements.test.ts |
Tests namespace classification without logical promotion. |
src/Components/Web.JS/src/Rendering/Renderer.ts |
Wraps component updates in batch planning and cleanup. |
src/Components/Web.JS/src/Rendering/RenderBatch/RenderBatch.ts |
Shares descendant-frame counting. |
src/Components/Web.JS/src/Rendering/PrerenderedDom.ts |
Plans DOM reuse, replacement, and logical reconstruction. |
src/Components/Web.JS/src/Rendering/LogicalElements.ts |
Adds logical adoption, reset, and namespace helpers. |
src/Components/Web.JS/src/Rendering/DomSpecialPropertyUtil.ts |
Retains deferred values for preserved controls. |
src/Components/Web.JS/src/Rendering/BrowserRenderer.ts |
Applies adoption plans through existing rendering paths. |
src/Components/test/testassets/TestContentPackage/PrerenderedDomPositionContent.razor |
Supplies positional mismatch and initializer scenarios. |
src/Components/test/testassets/TestContentPackage/PrerenderedDomPositionChild.razor |
Supplies nested-component and adjacent-text scenarios. |
src/Components/test/testassets/TestContentPackage/PrerenderedDomContent.razor |
Supplies browser-state preservation scenarios. |
src/Components/test/testassets/TestContentPackage/PrerenderedDomChild.razor |
Supplies a nested component for update tests. |
src/Components/test/testassets/Components.WasmMinimal/Pages/PrerenderedDomGlobal.razor |
Hosts global-interactivity and head-content coverage. |
src/Components/test/testassets/Components.TestServer/RazorComponents/Pages/PrerenderedDom.razor |
Hosts configurable Server and WebAssembly scenarios. |
src/Components/test/E2ETest/Tests/GlobalInteractivityTest.cs |
Tests preservation with an interactive router. |
src/Components/test/E2ETest/ServerRenderingTests/InteractivityTest.cs |
Tests preservation, replacement, and subsequent interaction. |
src/Components/ARCHITECTURE.md |
Documents activation matching and state-preservation boundaries. |
Review effort: Balanced
|
/review |
Normalize retained input defaults while preserving live browser state. Add Server and WebAssembly reset coverage and document raw-markup behavior. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
|
This can help with #70308. After it's merged, we should go back and simplify this fix so that OnFocusNavigate can be minimal. |
|
/review |
|
I don't have time to look at this in detail, sorry. But consider re-using the enhanced navigation diffing logic if you are not doing that. |
Thanks. Enhanced nav is comparing DOM to DOM when the current also is comparing DOM to render-batch frames (different representation). Building DOM out of render-barch frames is already present in Let's call it v3: 904467b |
Replace the custom frame matcher with an inert-document preview produced by BrowserRenderer and the existing DomSync algorithm used by enhanced navigation. Restore logical anchors and text boundaries, then attach handlers and references to the final nodes. Preserve live form edits when rendered defaults agree, initialize deferred-value bookkeeping without overwriting user state, and retain whole-root fallback for unsupported initial output. Enhanced-navigation behavior remains unchanged. Update browser tests and architecture notes for v3 preservation decisions, including retained initializer bindings and script execution when content is recreated. Validation: 23 activation Selenium cases and 3 navigation controls passed; 43 shared JavaScript tests passed. Full configuration-matrix and performance validation remain outstanding. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Keep v3's shared enhanced-navigation DOM diffing and integrate main's navigation-focus restoration. Restore navigation focus when activation removes tabindex from a retained node as well as when the node is replaced. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Normalize the inert preview in place instead of building a separate comparison tree. Remove unused helper extractions and condense the architecture documentation to one paragraph. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
|
/review |
| if (!preserveFormState && editableElementValue !== null) { | ||
| ensureEditableValueSynchronized(destination as Element, editableElementValue); |
| synchronizePrerenderedDom( | ||
| { startExclusive: descriptor.start, endExclusive: end }, | ||
| preview.root, | ||
| (destination, source) => { |
| function hasUnsupportedContent(node: Node): boolean { | ||
| if (node instanceof HTMLTemplateElement || | ||
| node instanceof Element && node.hasAttribute('data-permanent') || | ||
| isLogicalElement(node) && getLogicalRootDescriptor(toLogicalElement(node))) { | ||
| return true; |
PureWeen
left a comment
There was a problem hiding this comment.
Three activation issues remain at c0984de5: script execution, select reset defaults, and edits appearing against another row.
Informational checks, not approval blockers
Posted for informational purposes so the author can confirm the verifier didn't discard or leave unresolved a real finding; this item does not block agent-reviewed-approved.
- [UNRESOLVED] Custom-element callbacks: At
PrerenderedDom.ts:125, aconnectedCallbackthat replaces light-DOM children might detach a saved restoration anchor. The arm does not establish the necessary cross-document adoption and callback timing. This is not a confirmed activation failure. - [UNRESOLVED] Default-on behavior: One arm cannot establish default-on/opt-out approval from code. This is a process-information gap, not a code defect.
- Discarded checks: Source tracing rules out the proposed focus, preview event/property handling, restore-anchor invariant, frame-index, plan-lifetime, reload, and opaque-markup failures. The arms find no material test false-pass. Planning-cost concerns lack measured activation-latency evidence. The ordinary enhanced-navigation DOM-merge path stays gated separately from the script activation issue above.
- Documented intent: The PR explicitly preserves browser state without model synchronization or event replay. The added tests assert that boundary, so this review does not ask the author to confirm it again.
Untested coverage gaps
The arms identify gaps around changed/enhanced-navigation scripts, select reset, reordered rows, custom-element callbacks, and Auto/mixed-runtime activation. These gaps are not additional confirmed defects. Existing feedback already covers unsupported-root and sibling-root fallback coverage.
Validation: All three arms inspect frozen source only. The double-checks also use primary HTML contracts. No arm or double-check runs target code or browser tests.
Human-directed and GitHub Copilot-generated.
| const markupPlan = frameIndex === undefined ? undefined : this.framesForRendering.get(frameIndex); | ||
| const fragmentNodes = markupPlan?.nodes; | ||
| if (fragmentNodes) { | ||
| adoptLogicalChild(fragmentNodes[0], parent, childIndex); |
There was a problem hiding this comment.
[P2] Keep interactive markup scripts executable
A changed MarkupString script now updates the retained script text without executing its interactive payload. For example, prerender <script>window.phase='ssr'</script>, then render the same-position script with 'interactive' during activation. window.phase stays ssr even though the script text changes. Previously, parseMarkup created a fresh script and ran the interactive payload.
There is also a never-run case after enhanced navigation. NavigationEnhancement inserts HTML parsed with DOMParser, whose scripts are inert. This early return retains those scripts instead of creating executable nodes, so an unchanged initializer never runs at activation. This differs from the existing initializer comment, which covers a previously executed initializer whose target is replaced.
Keep unchanged scripts on a full load, but recreate changed scripts and scripts that never executed. A changed-text check alone misses the enhanced-navigation case.
| if (matchesFormDefaults(destination, source)) { | ||
| preservedFormState.add(destination); | ||
| if (destination instanceof HTMLSelectElement) { | ||
| destination.querySelectorAll('*').forEach(child => preservedFormState.add(child)); |
There was a problem hiding this comment.
[P2] Normalize preserved option reset defaults
StaticHtmlRenderer synthesizes selected on option B for <select value="b"><option value="a">A</option><option value="b">B</option></select>. These options enter preservedFormState, so DomSync skips their attribute synchronization. matchesFormDefaults removes selected only from comparison copies, and normalizeInputDefaults does not handle options.
After activation, native form reset therefore selects B. Ordinary interactive creation emits no selected attributes and sets only select.value, so reset selects A. This changes reset behavior even without a pre-activation edit. Normalize SSR-only option defaults while retaining the live selection, as the input path already does. This concerns successful single-select preservation, not the rejected multi-select path.
| preview.root, | ||
| (destination, source) => { | ||
| actual.set(source, destination); | ||
| if (matchesFormDefaults(destination, source)) { |
There was a problem hiding this comment.
[P2] Do not preserve an edit against a different row
Render rows [A(Qty=1), B(Qty=1)] with <li>@item.Name <input type="number" @bind="item.Qty" /></li>. Let the first interactive render reorder them to [B,A]. Type 5 into A before activation. DomSync pairs the same-tag rows by position and changes A's label to B. This check compares only the input defaults and attributes, so it preserves 5 under B and binds B's handler there.
The previous replacement path discarded the edit but did not display it against another item. @key does not prevent this because the physical DOM comparison cannot see it. Equal defaults and no distinguishing control attributes are sufficient to trigger it. Fall back for ambiguous control matches when surrounding content changes, rather than transferring the edit to another item.
|
Looks like this PR hasn't been active for some time and the codebase could have been changed in the meantime. |


Preserve matching prerendered DOM during the first interactive render, avoiding resets of input, focus, selection, scrolling, animations, and video playback.
Demo
Details
Before:
Before.mp4
After:
After.mp4
Design choices
DomSyncedit-script algorithm. Keep compatible nodes, update attributes and text, and insert or remove content where needed. Enhanced-navigation behavior is unchanged.Legitimate scenarios when the SSR and interactive DOM might differ
Details
RendererInfo.IsInteractiveorOperatingSystem.IsBrowser()for WebAssembly interactivity_handlerinput for a named form submission that interactive rendering doesn't produce. See example 3 below.<tbody>or remove a leading newline from<pre>or<textarea>, unlike interactive element/text creation. This depends on the generated frames. See example 4 below. It got logged as a bug: #70498example 1:
example 2:
example 3:
example 4:
This is a deeper rendering inconsistency issue that will not be fixed by this PR.
It happens because Blazor writes SSR as HTML text e.g.
<table><tr><td>Order #1042</td></tr></table>that is parsed by the browser as<table><tbody><tr><td>Order #1042</td></tr></tbody></table>and interactive rendering using DOM APIs. These APIs, for our table example, do:which produces
<table><tr><td>Order #1042</td></tr></table>. Such elements will be inherently different. Other affected elements:<tbody><table><tbody><tr><td>X</td></tr></tbody></table><table><tr><td>X</td></tr></table><pre>with dynamically supplied leading newline<pre>X</pre><pre>\nX</pre><textarea>with dynamically supplied leading newline<textarea>X</textarea><textarea>\nX</textarea>Fixes #42561