Skip to content

Block Editor: Restore a selection only in the controller that recorded it - #87845

Closed
jeryj wants to merge 32 commits into
trunkfrom
try/duplicate-controller-selection-tag
Closed

jeryj wants to merge 32 commits into
trunkfrom
try/duplicate-controller-selection-tag

Conversation

@jeryj

@jeryj jeryj commented Dec 2, 2026 •

Copy link
Copy Markdown
Contributor

What?

Second alternative to #82706, for #79096, beside #87777, which is parked.

This is #82706 with the recorded selection saying which controller recorded it. #82706 and #87777 both find the other copies of an entity when a controller syncs, by block type or by a registered source, and skip the restore while the caret sits in one of them. Here, when the controller that recorded the selection is on the canvas, only that controller restores it. #82706's guard still decides for a selection that names no controller on the canvas.

Why?

Every inner block controller that renders an entity maps that entity's blocks, so each of them takes a selection recorded in those blocks for its own. That ambiguity is what makes a copy take the selection. Recording the controller removes it for the selections that controllers record, where the guards in #82706 and #87777 work around it:

  • No knowledge of what a controller renders. For a selection a controller recorded, two Post Content blocks of different posts, or two Template Parts on different slugs, are never confused, with no store state, no new option and no changes to the controller blocks.
  • Undo goes back to the copy that was edited. The guard asks where the caret is now, so an undo with the caret in another copy leaves it there (Block Editor: Stop duplicate controllers from taking the selection #82706, Block Editor: Find duplicate controllers by what they render #87777). With the caret outside every copy, the first copy takes it, and on trunk the last one does. Here it goes to the copy the undone edit was made in, the way undo works elsewhere.

How?

Everything in #82706 stays: the in-place update of a copy's clones, the persistence reducer rule, the unsynced pattern fix and the selection guard. Then, in useBlockSync:

  1. Recording. When an inner block controller reports a selection, through onChangeSelection or with an onChange, it adds its own client ID as controllerClientId. A new optional field on BlockSelectionState. The editor stores the selection as given, so it comes back with undo.
  2. Restoring. When the selection names a controller on the canvas, only that controller restores it, wherever the caret is. Otherwise, a controller that maps the block restores it unless the caret is in another copy, as Block Editor: Stop duplicate controllers from taking the selection #82706's guard decides. Several writers record a selection without the field: 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 selection recorded by a controller that has since remounted names a client ID that is gone.

The guard moves from the call site of the restore into its ownership check: 38 lines added and 27 removed in use-block-sync.ts compared with #82706, mostly comments. Compare with #82706.

An earlier version of this PR used the field alone, and restored a selection that named no controller on the canvas in any copy, as trunk does. That brought the steal back for the selections above, so the guard decides for those now.

Why the in-place update stays

I tried this without the in-place update too. With two Post Content blocks rendering the same post, each undo then removes one typed character, as on trunk: the reducer rule alone does not keep the typing run there. The existing tests only cover a typing run in duplicated Template Parts, which the reducer rule does keep. The new test below catches it.

Testing Instructions

The manual steps from #82706 apply. Also:

  1. Open a page with its template in "Show template" mode, with one Post Content at the template root and another inside a Template Part.
  2. Type in the first, click into the second, and undo.
  3. The typing is removed in both, and the caret is back in the first. With Block Editor: Stop duplicate controllers from taking the selection #82706 and Block Editor: Find duplicate controllers by what they render #87777 it stays in the second.

Automated

All of the tests from #82706, plus:

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/editor/various/post-content-focus-mode.spec.js
npm run test:e2e -- test/e2e/specs/site-editor/navigation-selection-sync.spec.ts
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

Locally, these pass, as do the Navigation and Template Part specs, with two known flakes. "Synced pattern › can be inserted after refresh" in patterns.spec.js types into the slash inserter as soon as a new post loads, about 100 ms before the new pattern is available. It failed in every full run of the version that used the field alone, and passed in the latest one; it also fails about 1 run in 3 on #87777 when run alone. "Template Part › doesn't throw a block error when clicking on a link" fails about 1 run in 3, also on #82706: it types the URL before the link input takes focus, in the Template Part editor, where no inner block controller is involved.

Out of scope

  • Undo does not move the caret into a nested entity, as in Block Editor: Stop duplicate controllers from taking the selection #82706. The only consumer of a recorded selection reads the root record. Pinned as a test.fixme in site-editor/undo.spec.js.
  • Real-time collaboration. With collaboration on, core-data also restores a selection from the shared document on undo, outside useBlockSync and without the new field. I haven't tested duplicated containers with collaboration on.

🤖 Generated with Claude Code

jeryj and others added 28 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
The nearest controlled ancestor of the selected block is its holder. The store already has an ascending parent list, so use that instead of walking the tree by hand.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01UpQLN4sQKUDBA45FqsyUQY
Two fixes to the duplicate controller guard and in-place update.

The guard skipped restoring the selection whenever the nearest
controlled ancestor of the selected block was not this controller. A
controller nested inside this one, such as a synced pattern inside Post
Content, is still part of this copy, so an undo in Post Content no
longer moved the caret back while it sat in the pattern. A selection
anywhere inside this controller now counts as its own.

The in-place update compared only attributes, so a change to any other
block field never reached the clones. The Custom HTML block keeps its
markup in innerContent and edits it with updateBlock: undoing that edit
in a container left the new markup on screen, and the next edit there
wrote it back into the entity. A value whose blocks differ in any field
other than attributes and inner blocks now re-clones, as before.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The in-place update and its tests were written in JavaScript before
useBlockSync moved to TypeScript on trunk. Give the helpers and the test
harness their types so the dev project type checks.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Trunk now requires new end-to-end spec files to be TypeScript.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Two regressions against trunk in how a controller restores the
selection after an incoming change.

The in-place update left the record of the last restored selection in
place, so an undo handing back that same selection object skipped the
restore. That happens on undo, type, undo: typing without moving the
caret first records the selection the first undo restored. Clear it
after an in-place update, as re-cloning does.

The guard took any controller above the selected block for another
copy of this entity. A Template Part holding Post Title and Post
Content then stopped an undo in Post Content from moving the caret
back while it sat on Post Title. Another copy is always a block of the
same type, so only count controllers of this controller's block type.

Also trims the changelog entry to what changes for users of the
package, and names duplicate Post Content blocks in it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Two end-to-end tests for the selection restore fixed in the previous
commits, both with the page's template shown:

- With Post Title and Post Content in one Template Part, an undo in Post
  Content brings the caret back from Post Title.
- On undo, type, undo, the second undo brings the caret back to where
  the typing started.

Both fail without those fixes. Each first types a second after the
editor loads: the first typing after loading does not always get an
undo level of its own, on trunk too, which made the tests flaky.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The guard counts any controller of the same block type as a copy, so two
Template Parts on different slugs count as copies of each other too.
Say so next to the guard, and in the undo test pinned as fixme, which
the guard would also block once its other cause is fixed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Until the canvas reports Post Content as visible, a moment after it
renders, the block reads the post asynchronously. Typing then undone
quickly is missed altogether, leaving its blocks with the typing while
the post no longer has it. Wait for that state instead of a timeout,
and undo once per typing now that no undo can go missing.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Like the other two undo tests, this one typed before Post Content was
reported visible, so the first undo could be missed. An undo-until
loop absorbed that, but it would equally have accepted the two edits
being merged into one undo level. Wait for visibility instead, and
check that each undo reverts exactly one edit.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
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>
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>
…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>
…d it

Inner block controllers rendering the same entity all map its blocks, so
each of them took a recorded selection for its own. The guard that
stopped a copy from taking it compared block types to find the other
copies, and only looked at where the caret was when the copy synced.

Record the client ID of the controller that reports a selection with
it, and let only that controller restore it. Copies are told apart
without knowing what they render, and an undo returns the caret to the
copy that was edited, even while it sits in another copy. A selection
recorded by a controller that is no longer on the canvas, such as one
that remounted, still restores in any controller that maps it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Undo returns the caret to the Post Content instance that was typed in,
even when it has since moved into the other instance. A caret in the
Post Content of another post, which a test block features, doesn't
stop an undo in the current post from moving it back either. The test
block comes from the alternative in #87777.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@jeryj jeryj added [Package] Block editor /packages/block-editor [Package] E2E Tests /packages/e2e-tests labels Dec 2, 2026
@jeryj jeryj added the [Type] Bug An existing feature does not function as intended label Dec 2, 2026
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@github-actions

github-actions Bot commented Dec 2, 2026

Copy link
Copy Markdown

🤖 PR meta 🤖

Preview in WordPress Playground Preview in Storybook

jeryj and others added 2 commits December 2, 2026 12:31
…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>
…er-selection-tag

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

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…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>
@jeryj jeryj closed this Dec 2, 2026
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>
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 [Package] E2E Tests /packages/e2e-tests [Type] Bug An existing feature does not function as intended

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant