Skip to content

Block Editor: Stop duplicate controllers from taking the selection - #82706

Merged
jeryj merged 30 commits into
trunkfrom
fix/duplicate-block-scroll
Dec 3, 2026
Merged

jeryj merged 30 commits into
trunkfrom
fix/duplicate-block-scroll

Conversation

@jeryj

@jeryj jeryj commented Sep 9, 2026 •

Copy link
Copy Markdown
Contributor

What?

Closes #79096

When two blocks render the same entity — two Navigation blocks using the same menu, or two Post Content blocks in "Show template" mode — editing one made the other take the selection, scrolling the canvas to it and pulling the caret out of the block being typed in. In the Site Editor the caret snapped back after every keystroke, so typed text came out reversed, and each character became its own undo level.

Why?

Each inner block controller keeps private clones of its entity's blocks, but every controller of the same entity maps the same external IDs. When one of them is edited, the others receive the change as an incoming value, re-clone their whole subtree, and then restore the entity's recorded selection onto their own clones. Each of them recognizes that selection as its own, so the last one to sync steals it.

The re-clone on every keystroke also caused the rest: replacing the duplicate's blocks between two keystrokes broke the isUpdatingSameBlockAttribute chain in the persistence reducer, so every character became its own undo level.

How?

Three changes, one per layer:

  1. Selection guard, useBlockSync. After syncing an incoming value, skip restoring the recorded selection when the block-editor's current selection already sits inside a different controller, found with getBlockParents. The selected block counts as well as its parents, since adding a link to a Navigation block can leave that Navigation block selected. A selection anywhere inside this controller is its own, even one inside a controller nested in it, such as a synced pattern inside Post Content, so undo still moves the caret out of it. Outside it, only a controller of the same block type counts as another copy, since a copy of one entity is always rendered by the same kind of block: a Template Part around Post Title renders a different entity, so it does not stop an undo from moving the caret back into Post Content. A selection in the root block list belongs to no controller, so it never blocks a restore, and a selection this controller just destroyed by re-cloning is still repaired.
  2. In-place update, useBlockSync. When the incoming value has the same structure as the current clones (same external IDs in the same order, all the way down) and differs from them in attributes only, apply only the changed attributes to the existing clones as one history-ignored update instead of re-cloning. The mapping, the mounted components and the selection all stay valid between keystrokes. As after a re-clone, the next undo can still restore its recorded selection, even when it is the one restored last time, as on undo, type, undo. Structural changes still re-clone, and so do a change to any other block field, such as the innerContent that the Custom HTML block edits with updateBlock, and a removed attribute. Removing an attribute can change more than the attribute: a Navigation block whose ref an undo removes no longer controls its inner blocks, so they have to come from the incoming value, and the in-place update leaves the inner blocks of a controller alone. The reducer that derives block editing modes also treats a metadata attribute that is present but undefined as removed. It used to count only a truthy metadata, so when an earlier version of this PR set a removed metadata to undefined in place, undoing the creation of an unsynced pattern left its blocks locked.
  3. Persistence reducer. A history-ignored change that leaves the blocks of the previous action untouched no longer resets the "last action", so a typing run survives the duplicate's mirror update. A change that does touch those blocks, such as an undo that resets them or updates them in place, still starts a new level: the undo manager appends staged edits to the previous level, so the first keystroke after a reset has to stay persistent.

Why copies are found by block type

On #79929, youknowriad suggested that each controller register the entity it renders in the block-editor store, so that the guard can tell exactly which controllers are copies of each other. This PR counts any controller of the same block type as a copy instead, as a first step that can move to a registered entity later if needed:

  • It is simpler. The check is about 15 lines in useBlockSync and uses existing selectors. It needs no new store state, no new API and no changes to the controller blocks.
  • It is safer if it is wrong. The guard can only skip a restore; it never moves the selection. Where the block type gets it wrong, such as two Template Parts on different slugs or two Navigation blocks on different menus, the caret stays where the user put it. With core blocks alone that can't be seen today, since undo never moves the caret into a nested entity (see "Out of scope"). It can with a plugin block that shows another post's Post Content: type in the current post, click into the other post's content and undo, and the text reverts but the caret stays in the other post.
  • It is easy to replace. It is internal to the hook, so a registered entity can take its place without breaking anything: that only narrows what counts as a copy. Block Editor: Find duplicate controllers by what they render #87777 is that alternative: it records the entity each controller renders, and its e2e tests include the plugin case above.

An earlier version also changed useMarkPersistent, so that a change reaching an unselected field could not end the typing run in the other container. Trunk has since removed that hook in #86007 and starts undo levels from a field's own change handler, which a change arriving from another container never calls, so that change was dropped when rebasing.

Credit

Similar to @ramonjd's approach from #79422 and #79929.

Testing Instructions

  1. In the Site Editor, add two Navigation blocks that use the same menu, with enough content between them that the second is off screen.
  2. Click into a menu item label in the first block and type.
  3. The text appears in the order typed, the selection stays in the first block, and the canvas does not scroll to the duplicate.
  4. Select a menu item in the first block, then add a page with the block's "+" button. The selection stays in the first block.
  5. Press undo. The whole typed run is removed at once and the caret stays in the first block.
  6. Repeat with a page and its template in "Show template" mode, with one Post Content at the template root and another inside a Template Part.

Automated

E2e tests added:

  • site-editor/navigation-selection-sync.spec.ts (new) — the reproduction: with two Navigation blocks using one menu, editing a menu item leaves the caret and selection in the edited block. It records every selection entering the duplicate rather than asserting on the final selection: the steal is often momentary, and the canvas scrolls as soon as it happens even when the selection recovers. A final-state assertion passed 4 runs in 5.
  • editor/various/post-content-focus-mode.spec.js, all with "Show template" on:
    • typing in one of two Post Content instances leaves the caret and selection in that instance;
    • undo moves the caret between blocks of one Post Content;
    • undo, type, undo brings the caret back to where the typing started;
    • undo moves the caret back into Post Content from Post Title in the same Template Part;
    • undo of creating an unsynced pattern makes its blocks editable again, as ramonjd found in review.
    • undo of choosing a menu for a Navigation block brings back the block's inline links. An earlier version of the in-place update lost them: it removed the ref but kept the menu's links, and the block then picked the menu again.
    • The undo tests wait until the canvas reports Post Content as visible before typing. Until then, it reads the post asynchronously and can miss a quick type-then-undo, which leaves its blocks out of sync with the post. Each undo is then expected to revert exactly one edit.
  • site-editor/undo.spec.js — in a container duplicated from one entity, typing keeps every character, undo removes the whole typed run, and one redo brings it back in both containers. A test.fixme pins the pre-existing gap described under "Out of scope".
  • editor/various/undo.spec.js — undo restores the caret to the undone block even when another block is selected, so the selection recorded with the undo level wins over the current one.
  • site-editor/template-part-focus-mode.spec.js — the Template Part is selected again after returning from editing it. The theme setup moved from beforeAll to beforeEach, since the theme is restored after every test.

Existing coverage constrains the guard from being too broad: forcing it to always skip fails patterns.spec.js → "should restore selection after navigating back from pattern editing", which restores a selection inside the Post Content controller.

Unit tests:

  • use-block-sync — the in-place update, and a re-clone after a structural change, a reorder, a change to a field other than attributes or a removed attribute; typing in one copy staying in one undo level while another copy mirrors it; the selection guard with a duplicate controller, with a duplicate controller's own block selected, with a controller nested inside this one and with a controller of another type; an undo returning to the selection restored before.
  • store/test/reducer.ts — the rule for ignored changes to other blocks, a new undo level after an ignored change resets or updates the edited block, and typing in a second block staying in one undo level. An update that sets metadata to undefined removes an unsynced pattern's editing modes, and one that leaves metadata out keeps them.
npm run test:unit -- packages/block-editor/src/components/provider/test/use-block-sync.jsdom.test.tsx packages/block-editor/src/store/test/reducer.ts
npm run test:e2e -- test/e2e/specs/site-editor/navigation-selection-sync.spec.ts
npm run test:e2e -- test/e2e/specs/editor/various/post-content-focus-mode.spec.js
npm run test:e2e -- test/e2e/specs/site-editor/undo.spec.js
npm run test:e2e -- test/e2e/specs/editor/various/undo.spec.js
npm run test:e2e -- test/e2e/specs/site-editor/template-part-focus-mode.spec.js
npm run test:e2e -- test/e2e/specs/editor/various/patterns.spec.js

Out of scope

  • Undo does not move the caret into a nested entity, with or without duplicates. A controller records its selection against its own entity, but the only consumer of a recorded selection reads the root record. Pre-existing and unrelated to duplicates; worth its own issue. Pinned as a test.fixme in site-editor/undo.spec.js.
  • The guard cannot tell two entities of the same block type apart. The current post's Post Content and another post's Post Content shown by a plugin block count as copies of each other, so an undo in the current post leaves the caret in the other post's content. Two Template Parts with different slugs count as copies too; once the gap above is fixed, the guard would also stop an undo in one of them from moving the caret back while it sits in the other. Telling them apart needs each controller to register its entity in the store, as Block Editor: Find duplicate controllers by what they render #87777 does; see "Why copies are found by block type".

🤖 Generated with Claude Code

https://claude.ai/code/session_017RtcwXT84eF6zLdQXK9e1W
https://claude.ai/code/session_01UpQLN4sQKUDBA45FqsyUQY

@jeryj
jeryj requested a review from ellatrix as a code owner September 9, 2026 21:09
@github-actions github-actions Bot added the [Package] Block editor /packages/block-editor label Sep 9, 2026
@github-actions

github-actions Bot commented Sep 9, 2026 •

Copy link
Copy Markdown

🤖 PR meta 🤖

🎉 Props

If you're merging code through a pull request on GitHub, copy and paste the following into the bottom of the merge commit message.

Co-authored-by: jeryj <jeryj@git.wordpress.org>
Co-authored-by: youknowriad <youknowriad@git.wordpress.org>
Co-authored-by: ramonjd <ramonopoly@git.wordpress.org>
Co-authored-by: Mustafabharmal <mustafabharmal@git.wordpress.org>
Co-authored-by: talldan <talldanwp@git.wordpress.org>

To understand the WordPress project's expectations around crediting contributors, please review the Contributor Attribution page in the Core Handbook.


Props Bot commands

You can trigger Props Bot actions by commenting on this PR:

  • @propsbot add <username> to give props to a GitHub or WordPress.org user. Requires write access.
  • @propsbot remove <username> to leave a user out of the props. Requires write access.
  • @propsbot refresh to refresh this list. Adding the props-bot label works too.

Updated as activity occurs, without notifying anyone named here. Add the props-bot label to refresh.

📦 Bundle size

Size Change: +184 B (0%)

Total Size: 8.85 MB

📦 View Changed
Filename Size Change
build/scripts/block-editor/index.min.js 563 kB +336 B (+0.06%)
build/scripts/components/index.min.js 358 kB -152 B (-0.04%)

0b8e439 Run

⚡ Performance

Show the results

Client side metrics exclude the server response time.

front-end-block-theme

Metric c9c905d trunk % Change
timeToFirstByte 46.75 ms +3.42% -1.28% 46.1 ms +3.25% -3.58% 1.41%
largestContentfulPaint 76 ms +7.89% -5.26% 74 ms +8.11% -2.7% 2.7%
lcpMinusTtfb 27.8 ms +23.92% -7.37% 26.8 ms +17.91% -6.16% 3.73%
wpBeforeTemplate 23.77 ms +5.34% -2.78% 22.85 ms +6.65% -1.88% 4.03%
wpTemplate 19.37 ms +2.94% -3.87% 18.43 ms +9.5% -1.47% 5.1%
wpTotal 43.31 ms +3.12% -2.38% 42.33 ms +3.87% -3.66% 2.32%
wpMemoryUsage 7.76 MB +0% -0% 7.72 MB +0% -0% 0.45%
wpDbQueries 16 +0% -0% 16 +0% -0% 0%

front-end-classic-theme

Metric c9c905d trunk % Change
timeToFirstByte 38.65 ms +7.24% -3.23% 38.1 ms +5.51% -1.84% 1.44%
largestContentfulPaint 70 ms +5.71% -2.86% 68 ms +5.88% -0% 2.94%
lcpMinusTtfb 31.1 ms +6.91% -4.5% 30.4 ms +6.58% -3.95% 2.3%
wpBeforeTemplate 20.54 ms +5.5% -3.6% 20.55 ms +10.17% -2.58% -0.05%
wpTemplate 14.6 ms +5.34% -7.26% 14.38 ms +5.91% -2.78% 1.53%
wpTotal 35.56 ms +6.13% -4.42% 35.28 ms +5.13% -2.61% 0.79%
wpMemoryUsage 6.44 MB +0% -0% 6.41 MB +0% -0% 0.56%
wpDbQueries 13 +0% -0% 13 +0% -0% 0%

media-processing

Metric c9c905d trunk % Change
mediaProcessingJpeg 363.17 ms +1.2% -3.85% 360.46 ms +0.59% -0.27% 0.75%
mediaProcessingAvif 5341.56 ms +0.63% -0.85% 5340.6 ms +0.13% -0.61% 0.02%
mediaProcessingJpegToAvif 3603.57 ms +0.91% -0.67% 3623.55 ms +0.29% -1.1% -0.55%

media-upload

Metric c9c905d trunk % Change
jpegUploadProcessing 1493.46 ms +1.68% -1.66% 1460.52 ms +0.48% -0.47% 2.26%
pngUploadProcessing 247.46 ms +1.72% -8.33% 241.43 ms +2.72% -2.36% 2.5%
largeJpegUploadProcessing 1450.72 ms +0.47% -0.44% 1445.73 ms +0.1% -0.1% 0.35%
multipleImageUploadProcessing 1527.75 ms +1.29% -1.8% 1557.65 ms +1.14% -1.66% -1.92%

post-editor

Metric c9c905d trunk % Change
serverResponse 338.71 ms +1.98% -6.66% 329.36 ms +2.29% -6.36% 2.84%
firstPaint 384.78 ms +6.36% -18.16% 333.07 ms +9.9% -9.32% 15.53%
domContentLoaded 705.98 ms +1.54% -2.06% 661.21 ms +2.39% -2.04% 6.77%
loaded 707.64 ms +1.53% -2.08% 662.55 ms +2.39% -2.05% 6.81%
firstContentfulPaint 392.64 ms +6.14% -1.5% 366.96 ms +3.15% -0.59% 7%
firstBlock 1910.64 ms +3.11% -3.09% 1788.66 ms +1.38% -2.56% 6.82%
type 15.7 ms +5.73% -3.12% 15.26 ms +4.85% -12.52% 2.88%
typeWithoutInspector 16.09 ms +11.37% -3.79% 15.85 ms +3.28% -6.69% 1.51%
typeWithTopToolbar 21.17 ms +3.97% -3.92% 20.61 ms +7.47% -2.72% 2.72%
typeContainer 7.31 ms +7.25% -8.48% 7.1 ms +14.51% -4.65% 2.96%
focus 94.32 ms +4.12% -2.12% 81.3 ms +9.53% -5.25% 16.01%
firstFocus 227.99 ms +0% -0% 207.38 ms +0% -0% 9.94%
selectAll 321.58 ms +2.96% -0.42% 320.18 ms +1.78% -5.27% 0.44%
undo 27.52 ms +2.58% -4.94% 25.02 ms +1.68% -3.96% 9.99%
listViewOpen 33.25 ms +7.31% -2.5% 32.25 ms +5.09% -8.71% 3.1%
inserterOpen 32.54 ms +16.63% -5.13% 31.86 ms +5.56% -3.11% 2.13%
inserterHover 9.05 ms +8.51% -3.31% 8.7 ms +17.47% -3.79% 4.02%
inserterSearch 7.16 ms +3.07% -4.89% 7.12 ms +3.79% -4.07% 0.56%
loadPatterns 509.79 ms +2.57% -3.42% 498.81 ms +2.34% -1.95% 2.2%
wpTotal 329.64 ms +2.15% -6.8% 320.67 ms +2.06% -6.49% 2.8%
wpMemoryUsage 14.80 MB +0% -0% 14.76 MB +0% -0% 0.25%
wpDbQueries 55 +0% -0% 55 +0% -0% 0%

site-editor

Metric c9c905d trunk % Change
serverResponse 246.03 ms +1.01% -8.95% 274.75 ms +2.41% -8.26% -10.45%
firstPaint 287.16 ms +2.69% -15.88% 333.02 ms +1.17% -0.98% -13.77%
domContentLoaded 513.85 ms +5.24% -2.91% 588.01 ms +1.3% -0.73% -12.61%
loaded 514.87 ms +5.23% -2.92% 589.26 ms +1.31% -0.72% -12.62%
firstContentfulPaint 292.12 ms +8.84% -1.26% 334.02 ms +1.05% -0.4% -12.54%
firstBlock 1588.97 ms +0.45% -0.97% 1814.28 ms +0.08% -0.79% -12.42%
type 11.83 ms +2.96% -5.66% 17.26 ms +14.6% -14.6% -31.46%
navigate 77.34 ms +7.86% -1.54% 83.71 ms +8.72% -4.26% -7.61%
loadPatterns 1158.61 ms +4.25% -3.98% 1196.56 ms +4.2% -14.79% -3.17%
loadPages 920.52 ms +0.91% -1.9% 922.32 ms +1.18% -0.54% -0.2%
wpTotal 239.76 ms +1.07% -9.13% 267.99 ms +2.46% -8.43% -10.53%
wpMemoryUsage 12.84 MB +0% -0% 12.80 MB +0% -0% 0.28%
wpDbQueries 45 +0% -0% 45 +0% -0% 0%

0b8e439 Run

// belongs and there is no need to walk the tree for it.
if (
idMappingRef.current.internalToExternal.has( currentStartClientId )
) {

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.

I'll get back to this later, but my guess is that this PR probably breaks undo/redo selection restoration when you do multiple consecutive changes within the same controlled container. Basically an undo call might ask for the selection to move to another block within that same controlled container but the current PR will prevent it from happening.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

I'm at my EOD and had my agent write a test to try to cover this. I'll be back tomorrow to give it another try if it is an issue.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

I tested this out and pushed more Claude Fable work. It's testing well but I'm unsure about the direction without diving deeply into it since I'm not familiar with this part of the code. I've got it pushed up and will start going through it. I've tested it, and it is in a better state than trunk. Here's the current state:

  • Fixes duplicate container stealing the block selection
  • Doesn't cause the "backwards typing" bug
  • Does not cause an undo regression. There is already an issue on trunk with undo in a container not appropriately selecting and moving the caret to the correct location. I'll file that issue shortly.

Fable's summary of the fixes:

  1. Selection guard, useBlockSync. After a sync, skip restoring the entity's recorded selection when the current selection already sits in a different controller. Stops the other copy taking the caret.
  2. In-place update, useBlockSync. When the incoming value has the same structure as the current clones, apply the changed attributes to them as one history-ignored update instead of re-cloning and replacing. Removes the per-keystroke rebuild that caused every symptom. Structural changes still rebuild.
  3. Persistence reducer. A history-ignored change that leaves the typed block untouched no longer resets the "last action", so a typing run survives the other copy's mirror update. An undo still ends it.
  4. useMarkPersistent. Read the live RichText record via getValue instead of the render-time one, which is a change behind when the html changes from outside. Otherwise an external text change is mistaken for a formatting change and ends the run.

jeryj added a commit that referenced this pull request Sep 9, 2026
Per review on #82706: check that an undo can still move the selection
from one block of a controlled container to another. Post Content is an
inner block controller, so two of its blocks exercise that path.

Passes identically with the guard enabled and disabled, five runs each.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017RtcwXT84eF6zLdQXK9e1W
@ramonjd

ramonjd commented Sep 9, 2026

Copy link
Copy Markdown
Member

Thanks for driving this forward @jeryj! 🍺

I had another rando draft open to try to solve the undo conundrum here too:

I ran out of time to look at this, so I'll close that in favour of this one.

There's also a contributor PR that hasn't moved much #79097

jeryj added a commit that referenced this pull request Oct 15, 2026
Per review on #82706: check that an undo can still move the selection
from one block of a controlled container to another. Post Content is an
inner block controller, so two of its blocks exercise that path.

Passes identically with the guard enabled and disabled, five runs each.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017RtcwXT84eF6zLdQXK9e1W
@jeryj
jeryj force-pushed the fix/duplicate-block-scroll branch from 70180df to 13b223b Compare October 15, 2026 16:33
jeryj added a commit that referenced this pull request Nov 24, 2026
…nc fix

Remove the `useBlockSync` early return for a block that is gone and no longer controlled, and the detach step that let go of the controlled inner blocks so the early return could tell a detach apart. Both only kept the typing that converts a Page List in one undo step.

The cleanup between two keystrokes now starts a new undo step again, so typing a new label takes two undos to bring the Page List back. #82706 fixes this: its undo grouping keeps a typing run across a change outside the history that leaves the typed block alone. The e2e test for it is pinned with `test.fixme` until then.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@jeryj
jeryj force-pushed the fix/duplicate-block-scroll branch from acbbdb3 to ab749f7 Compare November 24, 2026 14:32
jeryj added a commit that referenced this pull request Nov 24, 2026
Per review on #82706: check that an undo can still move the selection
from one block of a controlled container to another. Post Content is an
inner block controller, so two of its blocks exercise that path.

Passes identically with the guard enabled and disabled, five runs each.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017RtcwXT84eF6zLdQXK9e1W
@jeryj
jeryj force-pushed the fix/duplicate-block-scroll branch from b20be87 to 57d7e4f Compare November 24, 2026 19:56
jeryj added a commit that referenced this pull request Nov 24, 2026
Per review on #82706: check that an undo can still move the selection
from one block of a controlled container to another. Post Content is an
inner block controller, so two of its blocks exercise that path.

Passes identically with the guard enabled and disabled, five runs each.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017RtcwXT84eF6zLdQXK9e1W
@ramonjd
ramonjd requested a balanced review from Copilot November 25, 2026 00:15

Copilot AI 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.

Copilot was unable to review this pull request because the user who requested the review has insufficient remaining quota. Try requesting a review at a lower effort level.

@ramonjd ramonjd added the [Type] Bug An existing feature does not function as intended label Nov 25, 2026

@ramonjd ramonjd left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

I ran some e2e scenarios locally on this and found no side effects, except the navigation blocks menu bug, outlined below.

Test cases:

Case Trunk PR
Issue’s own steps: add a menu item to Navigation A while B uses the same menu Selection went A → B and the canvas scrolled 1657 px Stayed in A, no scroll
Press Enter in one of two Post Content blocks Selection went A → B Stayed in A
Type in A, click into B, undo Text reverted. Selection went B → A → B Text reverted. Selection stayed in B
Redo with a duplicate Text correct. Selection went back and forth between A and B 6 times Text correct. Selection stayed in A
Two menus (one per Navigation block): type in A, click B, undo A reverted, selection stayed in B Same as trunk
One Navigation block, no duplicate: type, undo, redo Text correct. Selection was cleared and restored on every undo and redo Text correct. Selection never cleared

I also tested manually again, concentrating on undo/redo.

redo-3456x1944.mp4

Some ideas for further test coverage (optional)

  • Adding a menu item doesn’t move the selection into the duplicate
  • Undo then redo in a duplicated container (Both nav containers show changes, then all restored by a single redo)

I guess the question is whether @youknowriad's store-based version in #79929 is preferred?

For the record, I hammered undo/redo and didn't see anything strange.

*
* @return Whether the updated blocks are untouched.
*/
function leavesBlocksUntouched(

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Nit and 100% optional. Going by the function name alone, I'm not sure what it does.

Without consulting an agent, my meat brain is trying piece together the puzzle of "on update block attributes" and "block list ids match previous block ids state"

How to turn that into something comprehensible though 🤔

* @param clone Its clone in the block-editor store.
* @return Whether the blocks have the same fields.
*/
function hasSameFields( block: Block, clone: Block ): boolean {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Same here. It could be just me, but I think the function name is missing what it acts upon, e.g., areBlock[Keys|Fields]Equal

await editor.canvas
.locator( `[data-block="${ rootParagraph }"]` )
.click();

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Maybe Post Content hasn't finished loading 🤷🏻

Do we also need to use waitForPostContentVisible here too?

// Two controllers of one type that render different entities, such
// as Template Parts on different slugs, count as copies too: telling
// them apart would need each controller to record its entity.
const parents = getBlockParents( currentStartClientId );

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

So this only searches the selected block’s parents... do we need to include the block itself?

So a selection on another Navigation block, for example, counts?

I think I found a bug.

  1. Click a link in the header menu ("Visit us"), so the link itself is selected.
  2. Click the header menu's "Add page" button.

The search popover opens in the header, but the selection moves to the footer's "Visit us"

nav-add-3456x1944.mp4

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Nice find!

jeryj and others added 9 commits December 1, 2026 08:35
Adds failing coverage for #79096 and regression guards for the behaviour
a fix must not break.

Two blocks rendering the same entity (two Navigation blocks on one menu,
two Post Content instances) each clone that entity's blocks privately but
build identical external-to-internal ID maps. In useBlockSync's
restoreSelection, ownership is decided by whether the external ID appears
in that map, which every such controller answers true to, so an edit in
one instance is followed by the other claiming the selection.

Failing (the defects):
- editing a menu item leaves the caret and selection in the edited block
- undoing a menu edit returns the caret to the block that made it
- undo moves the caret back into the Navigation block when the caret has
  moved outside it
- typing in one Post Content instance leaves the caret and selection in
  that instance

The last two are a second, separate gap: a nested controller records its
selection against its own entity, but the only consumer of a recorded
selection reads the root record, so cross-controller undo never restores
the caret.

Passing (guards for existing behaviour):
- undo restores the caret to the undone block when another block is
  selected
- selection is restored after returning from a template part

The duplicate tests record every selection entering the other instance
rather than asserting on the final selection: the steal is often
momentary, and the canvas scrolls as soon as it happens even when the
selection recovers. A final-state assertion passed 4 runs in 5.

The Navigation spec is adapted from
#79929.

Also makes Template Part Focus mode activate its theme per test; the
theme was restored after each test but only activated in beforeAll, so
any second test in the file ran against the wrong theme.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017RtcwXT84eF6zLdQXK9e1W
Fixes #79096.

Two blocks can render the same entity — two Navigation blocks using one
menu, a Post Content block at a template root and another inside a
template part. Each is an inner block controller holding private clones,
but both clone the same blocks, so both build the same
external-to-internal ID mapping and both recognise the entity's
selection as their own.

An edit in one instance therefore reaches the other as an incoming
entity change. That controller re-clones and calls restoreSelection,
which converts the external ID to its own copy and dispatches
resetSelection. The canvas scrolled to the duplicate and the caret left
the block being typed in, reliably enough to reorder characters.

Guard the restoreSelection call instead: when the selection already sits
inside a different inner block controller, this sync is a consequence of
an edit made there, so leave it alone. The controller that made the edit
takes the outgoing branch and never reaches this code, so a selection
held by another controller is always one that has been dealt with. A
selection held by the root block list belongs to no controller and still
restores as before, which is what keeps entity navigation and undo
working.

The guard sits at the call site rather than inside restoreSelection: the
question is about the sync that just happened, not about the selection
object, and restoreSelection keeps its existing contract.

This reuses getBlockParents and areInnerBlocksControlled, already
selected in this hook, so there is no new store state, no new action or
selector, and nothing persisted into entity data or collaborative state.

Revives the approach in #79422 by @ramonjd, which asked the same question
with the same selectors and was closed by its author in favour of #79097.
Two differences: the check moved to the call site, and the WeakMap
remembering the last controller to hold the selection is left out.

Also removes two tests added with the failing coverage. They asserted
that undo returns the caret to the block whose edit was undone. Trunk
does not do that for any nested entity, with or without duplicates: a
controller records its selection against its own entity, but the only
consumer of a recorded selection reads the root record. That is a
separate, pre-existing gap and out of scope here.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017RtcwXT84eF6zLdQXK9e1W
…root

getBlockParents collects every ancestor up to the document root and is
memoized on state.blocks.parents, which changes on each re-clone, so the
memo never hits on this path. The answer is almost always the immediate
parent, since a menu item sits directly inside its Navigation block.

Walk up with getBlockRootClientId instead, stopping at the first
controller, and short-circuit on the controller's own mapping when the
selected block is one of its clones.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017RtcwXT84eF6zLdQXK9e1W
The existing comment describes restoreSelection, so it belongs inside the
guard rather than above it. Also records why the guard is checked after
the blocks are set.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017RtcwXT84eF6zLdQXK9e1W
Per review on #82706: check that an undo can still move the selection
from one block of a controlled container to another. Post Content is an
inner block controller, so two of its blocks exercise that path.

Passes identically with the guard enabled and disabled, five runs each.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017RtcwXT84eF6zLdQXK9e1W
Two Template Parts pointing at the same entity are both inner block
controllers synced from one record. These pin the two behaviours that
matter when typing into one of them.

The first passes: every typed character survives, in both copies. That is
the behaviour the preceding commits on this branch fixed, and it
regresses silently, so it is worth holding down.

The second fails. One undo removes a single character rather than the
whole typed run, because each keystroke makes the *duplicate* run
setControlledBlocks() and dispatch replaceInnerBlocks. That action lands
between keystrokes and breaks the isUpdatingSameBlockAttribute merge
chain, so every character becomes its own undo level. Marking the change
not-persistent does not help: any intervening action on another block
breaks the chain regardless. restoreSelection is not involved — the
existing guard keeps it from firing during typing.

Both tests type at a human cadence on purpose. An instant
keyboard.type() outruns the re-sync and passes, so the delay is
load-bearing rather than incidental.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01UTowaGipHSMef7nUQAnnJJ
Two containers rendering one entity, such as two Template Parts on the
same slug, are both inner block controllers. Typing in one edits the
entity, and the other mirrors the edit onto its own clones as a change
ignored by history. The persistence reducer still recorded that change
as the last action, so the next keystroke no longer looked like a
continuation of the run and was filed as a new undo level. Undo then
removed one character at a time.

A history-ignored change that leaves the last-updated block's entry and
attributes untouched now keeps the previous last action, so the run
continues across it. A change that does replace that block, such as the
reset after an undo, still starts a new level.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01A6LxkvDuGJg68a7c8KJKry
…tes change

An inner block controller rebuilt its whole subtree whenever its entity
changed: it cleared the ID mapping, cloned every block under a fresh
client ID and replaced the inner blocks. With two containers rendering
one entity, that happened on every keystroke made in the other one. Each
keystroke tore down and remounted every block and rich text in the
duplicate, briefly left it without a selection, and dispatched a block
replacement into the store between two keystrokes.

When the incoming value has the same structure as the current clones,
the same external IDs in the same order, the controller now applies the
changed attributes to the existing clones as one history-ignored update.
The mapping, the mounted components and the selection stay valid. A
structural change still takes the rebuild path.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01A6LxkvDuGJg68a7c8KJKry
An undo that reverts an edit in one Template Part while the caret sits in
another should bring the caret back to the reverted block, as it does at
the root of the document. It does not yet: a nested controller only
restores the selection recorded on the root record, which an undo of its
own entity never changes. The test is marked fixme to document the gap.

The duplicated-container tests now also delete saved templates when they
finish, since a leftover saved index template made their setup fail.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01A6LxkvDuGJg68a7c8KJKry
jeryj and others added 4 commits December 1, 2026 08:36
Two checks had no test that fails without them:
- a reorder of the same blocks must re-clone, or each clone stays
  mapped to the block that used to be in its place, and an edit to one
  is reported as an edit to another;
- an undo that updates the edited block in place must start a new undo
  level for the next typing, or the next undo also takes back the edit
  before it.

Also correct comments that still describe a duplicate re-cloning
between keystrokes, drop a claim that the selection guard has to run
after the blocks are set (either order restores the selection), and
name the nested-controller re-clone case for what it covers.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The hook ignores changes to the clones of a controller that has no
block in the store, so the check that an in-place update is not
reported back passed whatever the hook did. With a host block, it
fails when the hook stops marking the update as incoming.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Three conditions had no test that fails without them:
- a copy's in-place mirror of another copy's keystroke must be ignored
  by history, or each keystroke starts an undo level of its own;
- the reducer rule must apply only to changes history ignores, or
  typing in a second block splits into one level per keystroke;
- the nested-controller selection test must take the in-place path
  when it says it does.

Also correct a reducer test comment that credited the block entry for
what its attributes catch, and reuse the Post Content text helper.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@jeryj
jeryj force-pushed the fix/duplicate-block-scroll branch from 57d7e4f to 907e332 Compare December 1, 2026 14:38
jeryj and others added 3 commits December 1, 2026 13:37
Rename hasSameFields to areBlockFieldsEqual and leavesBlocksUntouched
to areLastUpdatedBlocksUnchanged, so that each name says what it
compares, as suggested in review.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…lection

The selection guard checked only the parents of the selected block, so
a selection on another copy's own block did not count. Adding a link to
a Navigation block can leave that Navigation block selected, and review
caught the duplicate then restoring the previous link onto its own
clone, pulling the selection into it. Count the selected block as well
as its parents.

Also say in the guard why it counts copies by block type rather than by
a registered entity.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
One redo must bring the whole typed run back, in both containers.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

Copilot AI 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.

🟢 Approval recommended

No active review issues were identified in the duplicate-controller selection and undo behavior changes.

No open issues 🎉

Review effort: Balanced

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Another round of testing caught something else.

Basically, undoing an unsynced pattern creation removes the container's metadata but the inner blocks still have contentOnly restrictions (at least on the toolbars).

I think it should be fixed in this PR, given the changes to set controlled blocks.

I've run it on trunk to confirm.

How to reproduce:

  1. Use a block theme and turn on View → "Show template". Without "Show template" the post's blocks load through a different code path and the bug doesn't happen.
  2. Insert a Group containing two paragraphs. Don't give the Group a custom name first: a name is stored in metadata, and then the metadata isn't empty after Undo, so the reducer handles it correctly.
  3. Click a child paragraph. Note its toolbar and its Block inspector. On my run the toolbar had "Select parent block: Group", "Align block" and "Align text", and the inspector listed Typography, Background, Dimensions, Borders, Elements and Advanced.
  4. Select the Group, then Options → Create pattern, turn Synced off, and click Add.
  5. Click Undo once.
  6. Click the same child paragraph again. Bug: the toolbar has lost those three buttons, and the inspector shows only Typography. Step 3 is what you should see.
  7. Reloading the page brings the full controls back.
2026-12-02.10.14.56.mov

I tested a fix locally that works.

A property presence check lets an explicit metadata: undefined clear the old restrictions while an update that omits metadata preserves them.

Object.hasOwn( attributes, 'metadata' ) &&

…ts metadata

When a container updates its inner blocks in place, an undo that removes
the metadata of an unsynced pattern arrives as `metadata: undefined`. The
derived editing modes only treated a truthy `metadata` as a change, so the
pattern's blocks stayed content only until the page was reloaded. Count
`metadata` as changed whenever the update includes it.

Reported by ramonjd in review, with the fix.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…removed

Removing an attribute can change more than the attribute. A Navigation
block whose `ref` an undo removes no longer controls its inner blocks, so
they have to come from the incoming value. The in-place update leaves the
inner blocks of a controller alone, so the block kept the menu's links,
lost its own, and then picked the menu again.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
jeryj added a commit that referenced this pull request Dec 2, 2026
…er-selection-tag

Brings in #82706's re-clone when an attribute is removed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
jeryj added a commit that referenced this pull request Dec 2, 2026
…roller

Several writers record a selection without `controllerClientId`: core-data,
when a collaborator's edit shifts the caret, and the post and site editors,
when they restore the selection on returning from editing a pattern or a
template part. A controller that remounted leaves a client ID that is gone.
Every copy restored those, as on trunk, so the steal came back for them.

When the selection names a controller on the canvas, only that controller
restores it. Otherwise, the guard from #82706 decides.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Moves the changelog entry to Unreleased, since trunk released 20.2.0.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

@ramonjd ramonjd left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Thanks for taking care of this @jeryj

🍺

I left a small suggestion to fix a flaky test, other than that, I think we've tested the guts out of this one between us!! 🙇🏻

Comment on lines +881 to +882
const [ clientId ] = getBlocksByName( 'core/post-content' );
return __unstableGetVisibleBlocks().has( clientId );

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Suggested change
const [ clientId ] = getBlocksByName( 'core/post-content' );
return __unstableGetVisibleBlocks().has( clientId );
const visible = __unstableGetVisibleBlocks();
const clientIds = getBlocksByName( 'core/post-content' );
return (
clientIds.length > 0 &&
clientIds.every( ( clientId ) => visible.has( clientId ) )
);

I ran this test locally and it's flaky the same way it was on the CI.

https://github.com/WordPress/gutenberg/actions/runs/45475581103/job/138736443713#step:8:54

The fix seems to be to make the helper wait for every Post Content.

I ran it 25 times in a row with no fails. Before I had a couple.

name: 'core/paragraph',
attributes: { content: 'Shared' },
} );
await postContentFocusMode.enableShowTemplate();

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Suggested change
await postContentFocusMode.enableShowTemplate();
await postContentFocusMode.enableShowTemplate();
await postContentFocusMode.waitForPostContentVisible();

Related to below.

jeryj and others added 2 commits December 3, 2026 08:06
…tion

"Show template" mounts the nested Post Content after the root one. When
it mounts after the test clears the selection, it restores the post's
selection into its own copy, and that copy's block toolbar covers the
root paragraph the test then clicks. Wait for both instances and for
both to be visible, as ramonjd suggested in review.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
draganescu added a commit that referenced this pull request Dec 3, 2026
Undo from the other Navigation block now expects the caret back in the
edited block, and redo too. The undo across two Template Parts is no longer
a fixme; it only clicks into the second part, since typing there is not
recorded as an undo level of its own, on trunk as well. Adds the Post
Content case from #87845, and waits for every Post Content to be visible,
as suggested on #82706.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@jeryj
jeryj merged commit 61fcd7a into trunk Dec 3, 2026
87 checks passed
@jeryj
jeryj deleted the fix/duplicate-block-scroll branch December 3, 2026 14:30
@github-actions github-actions Bot added this to the Gutenberg 24.7 milestone Dec 3, 2026
draganescu added a commit that referenced this pull request Dec 3, 2026
Trunk now has #82706, which this branch already builds on, so its
side of the conflicts in useBlockSync, its tests and the e2e specs is
kept. From trunk's later #82706 test commit, the Post Content spec also
waits for both instances before clearing the selection. Also types the
focused element in blurFocusedField, which failed the type check.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
draganescu added a commit that referenced this pull request Dec 3, 2026
#82706 is in trunk with its own entry for the typing fixes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

[Package] Block editor /packages/block-editor [Type] Bug An existing feature does not function as intended

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Adding an item to a duplicate Navigation Block scrolls the second one into view

4 participants