Skip to content

PT-4885: Keep the caret host intact through paste, undo, blur and the keyboard - #33

Merged
timothy-mccormack merged 4 commits into
mainfrom
pt-4885-caret-host-hardening
Oct 27, 2026
Merged

timothy-mccormack merged 4 commits into
mainfrom
pt-4885-caret-host-hardening

Conversation

@timothy-mccormack

@timothy-mccormack timothy-mccormack commented Oct 26, 2026 •

Copy link
Copy Markdown
Contributor

Prerequisite for PT-4885. The PT-4885 fix (stacked PR to follow) keeps the transient caret host alive between two empty verses, which is where most empty verses in a blank chapter sit. Today that only happens for an empty verse at the end of a paragraph, or past a trailing collapsed note. These are bugs in the host machinery that already show up in those places, and PT-4885 would make them common.

What was wrong

The host is a placeholder-only text node (one zero-width space) that gives the caret something to render in. It was recognized only by the key one guard instance tracked, and its placeholder was stripped by content, so:

  • Paste: Lexical merged pasted text with the host, carrying the placeholder into saved Scripture under the pasted node's key.
  • Word breaks: stripping removed every zero-width space from text that landed in the host, so a Thai or Khmer word break typed or pasted there was lost. With all three guards mounted (as the platform editor does), a second instance stripped again.
  • Undo: a host that undo brought back was untracked, so text typed into it kept the placeholder.
  • Blur: removing the host wrote the DOM selection back, which pulled focus back into the editor. It could also leave the caret inside a collapsed note that ends a char span.
  • Delete/Backspace: both saw only the host's text offsets, so Delete stopped arming the next verse and simply removed the placeholder instead.
  • Delta ops: the fast path diffed the host's raw placeholder, so the first keystroke into it emitted a delete for whatever followed it, such as the next verse embed.

What changed (transientCaretHost.ts, plus small changes elsewhere)

  • Host mark: hosts carry a node-state mark (isCaretHost). The mark is what recognizes a host, across undo and across guard instances, and it also keeps Lexical from merging neighboring text into one.
  • Stripping: only marked nodes are stripped, removed or adopted, and only the host's own placeholder is removed, where its position is known. Any other zero-width space is content.
  • Adoption: a host undo brought back is adopted when a selection change finds the caret in it. If none comes, blur still removes it, and so does the caret leaving it. Creating or removing a host is merged into the current undo step, so it never clears the redo stack.
  • Blur and focus: blur removes the host with SKIP_DOM_SELECTION_TAG and puts the caret at the boundary the host stood for ($selectElementPoint, which doesn't descend into a char span's trailing note). Focus that returns without a selection change re-hosts the caret. That re-host is decided from the committed state, after any pending update commits, and runs an update only when a host is missing. An update made outside any event reads its selection from the DOM, and right after a focus the DOM may not yet hold the committed selection.
  • Keyboard: structureKeyboard.utils.ts treats both offsets of a bare host as one position, so it sees through to the neighboring verse and to the paragraph edges.
  • Delta fast path: DeltaOnChangePlugin's fast path diffs the node's previous text from what it contributed in delta-doc counting. A bare host, or an empty char span's stand-in, contributed nothing, so typing into either no longer deletes the next verse.
  • Reuse: an unmarked zero-width space at a guarded boundary (loaded or typed as content) is reused rather than stacked behind, and is never removed.

Tests

New tests cover each case above: paste, multi-line paste, a Thai paste, a zero-width space typed before other text, typing at either host offset, undo then type, a restored host removed on blur or when the caret leaves, the redo stack, blur staying out of undo and the change handler, blur next to a collapsed note in an unclosed \wj, focus re-hosting, Delete/Backspace from inside a host, the paragraph-edge checks, and both delta ops. Each of those fails on main, or fails when the behavior it covers is reverted. The lifecycle tests mount all three caret guards, as the platform editor does.

Three tests are regression guards rather than bug repros, and pass on main too:

  • "leaves a hosted caret where it is on focus, whatever the DOM selection says" guards the focus re-host this PR adds.

  • "keeps a zero-width space typed after undo and redo through the host".

  • "removes the host once its placeholder is selected". main already removed the host for a range selection.

  • shared-react: 2235 passed

  • platform: 4083 passed (on the latest main)

  • The first CI run caught a flaky noteCaretPlacement test caused by the focus re-host. It failed 3 times in 18 parallel local runs before the fix, and 0 times in 30 after.

  • Typecheck and eslint clean; committed dist rebuilt and verified.

Known limitations

  • A zero-width space typed alone into a host stays in the editor but isn't saved or sent to peers: the USJ serializer and the delta adaptor still drop any placeholder-only text by content. A zero-width space followed by other text is kept everywhere.
  • A drop or paste whose target lands on the far side of the placeholder from the caret can still leave the placeholder in the text. Ordinary typing and pasting can't reach this.
  • The first Shift+Arrow press out of an empty verse selects nothing, as on main. Keeping the host alive for that selection is what let a footnote quote the placeholder.
  • Pre-existing and unchanged: a later untagged SELECTION_CHANGE while the editor is unfocused can re-host and refocus it, and the blur commit's CURSOR_CHANGE_TAG also hides a co-committed marker settle from onUsjChange.

🤖 Generated with Claude Code


This change is Reviewable

timothy-mccormack and others added 2 commits October 26, 2026 18:19
The transient caret host (a placeholder-only text node that gives an empty verse or a trailing collapsed note a caret to render in) was recognized only by the key one guard instance tracked, and its placeholder was stripped by content. That leaked the placeholder into saved Scripture, or deleted real zero-width spaces, in several ways:

- Pasted text merged with the host, carrying the placeholder in under the pasted node's key.
- Stripping removed every zero-width space from text that landed in the host, so a Thai or Khmer word break pasted or typed there was lost.
- With all three guards mounted, a second instance stripped again after the first.
- An undo that brought a host back left it untracked, so text typed into it kept the placeholder.

The host is now marked with node state, which also keeps Lexical from merging neighboring text into it. Only marked nodes are stripped, removed or adopted, and only the host's own placeholder is removed, where its position is known. An untracked host the caret rests in is adopted. Creating or removing a host is merged into the current undo step, so it never clears the redo stack.

Also:

- Blur removes the host without writing the DOM selection back (which stole focus) and leaves the caret at the boundary it stood for, not inside a collapsed note.
- Focus that returns without a selection change re-hosts the caret.
- Any range selection, even inside the placeholder, removes the host, so it can't be copied or quoted by a footnote.
- Delete and Backspace see through a bare host to the neighboring verse marker and the paragraph edges.
- The delta fast path counts a bare host as zero length, so the first keystroke into it no longer emits a delete for whatever follows.
- An unmarked zero-width space at a guarded boundary (loaded or typed as content) is reused rather than stacked behind, and never removed.

Prerequisite for PT-4885, which keeps the host alive between two empty verses.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
An update made outside any event resolves its selection from the DOM. The
focus re-host ran one from a microtask, and right after a focus the DOM may not
yet hold the selection just committed (jsdom puts it at the editor start), so
it could move the caret instead of hosting it. Under CI load this made
noteCaretPlacement's empty-note selectNote test flaky. Decide from the
committed state first and update only when a host is actually missing.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
@timothy-mccormack
timothy-mccormack force-pushed the pt-4885-caret-host-hardening branch from 5fecc42 to db9ae39 Compare October 26, 2026 22:36
@timothy-mccormack
timothy-mccormack marked this pull request as ready for review October 27, 2026 00:38

@katherinejensen00 katherinejensen00 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.

Thanks for your hard work on this, Tim! There are 11 findings, but I mainly care about the first one and am just listing the others in case there are any that you want to fix at the same time. Feel free to ping me for a re review or ask someone else if I am offline so this can get merged by the end of tomorrow.

1. Three new behaviors can be reverted without any test failing

Medium · Confirmed by mutation · libs/shared-react/src/plugins/usj/transientCaretHost.ts:151 (also structureKeyboard.utils.ts:185 and transientCaretHost.ts:331-332)

Each of these mutations passes every shared-react and platform test, and each one changes behavior a user or the host application would see.

Mutation What breaks Reachable by
Delete the offset-1 branch of $removeHostPlaceholder (:150-152) Typing at host offset 1 leaves "​a", and the ZWSP reaches saved USJ. That is the leak this PR exists to close. ArrowRight inside the host, or a browser click that lands after the placeholder
Drop && !$isCaretHost(node) in $caretAtParaEnd (structureKeyboard.utils.ts:185) With the caret at host offset 0 at a paragraph's end (where the guard puts it), $caretAtParaEnd returns false again. Delete there stops arming the structural delete. An empty last verse in a paragraph
Drop the blur's CURSOR_CHANGE_TAG / HISTORY_MERGE_TAG (:331-332) Every blur from a hosted caret creates its own undo step and fires onUsjChange. Clicking out of an empty verse
  • Only $adjacentVerseMarker has unit tests. The $caretAtParaStart / $caretAtParaEnd half of the Keyboard bullet has none.
  • Other surviving mutations turned out to be equivalent or masked downstream, so they need no test: :136, :148, :260, :292, :319 and :353. For example, :148 can't matter, because a host is always inserted after its anchor.

Suggested fix: in EmptyVerseCaretGuardPlugin.test.tsx, add:

  • Typing "a" with the caret at host offset 1. Assert the text is "a".
  • A blur from a hosted caret. Assert that onUsjChange isn't called and that the undo stack length is unchanged.

In structureKeyboard.utils.test.ts, add a $caretAtParaEnd case for a host that ends a paragraph, with the caret at offset 0.

2. A host restored by undo is orphaned if the caret leaves before a selection change adopts it

Low · Confirmed in jsdom; real-browser reachability not verified · libs/shared-react/src/plugins/usj/transientCaretHost.ts:254

Adoption only happens in $repairCaret, so it needs a SELECTION_CHANGE while the caret is still in the restored host. Undo doesn't dispatch one. If the user blurs or clicks away first, no instance ever tracks the host, and it stays in the document.

Repro (jsdom):

  1. Put the caret in an empty verse's host.
  2. Type "a".
  3. Undo. The host comes back with the caret in it.
  4. Blur. The host is still there.

The same happens with a settle between steps 3 and 4.

  • Why: blur and the stale-host pass act only on hostKeyRef, which is undefined after undo. The PR's undo tests dispatch SELECTION_CHANGE by hand, which is what makes adoption happen there.
  • Browser: after undo, the reconcile puts the DOM caret at offset 0 itself. updateDOMSelection then sees a match and doesn't call setBaseAndExtent. Whether adoption happens therefore depends on the browser firing selectionchange for that mutation.
  • Impact: an invisible ZWSP that the serializer and delta adaptor both drop. Main never tracked restored hosts either, so this isn't a regression. But the "Adoption" bullet promises it's handled.

Suggested fix: don't make adoption depend on a selection change.

  • In BLUR, when nothing is tracked, fall back to the node at $restingKey() if $isCaretHost is true for it.
  • In the stale pass, also treat the previous selection's node ($getPreviousSelection()) as stale when $isCaretHost is true for it and the caret has left.
  • Add the two repro sequences above as tests, without hand-dispatching SELECTION_CHANGE.

3. Three of the "each fails on main" tests pass on main

Low · Confirmed (head's EmptyVerseCaretGuardPlugin.test.tsx run against main's four changed sources: 9 failed, 8 passed) · PR description

The Tests section says each new test fails on main. These three pass there:

  • "leaves a hosted caret where it is on focus, whatever the DOM selection says" (:521). It guards the focus handler this PR adds, so it's a regression test for the second commit.
  • "keeps a zero-width space typed after undo and redo through the host" (:413).
  • "removes the host once its placeholder is selected" (:549). The description's Selection bullet ("any range selection removes the host") also describes behavior main already had.

Suggested fix: say which tests are regression guards rather than bug repros, and reword or drop the Selection bullet. A reviewer reading "each fails on main" will otherwise take every test as evidence of a fixed bug.

4. "Is this a host?" is still answered two ways, so a lone typed ZWSP is still lost

Low · Confirmed (probe) · libs/shared-react/src/plugins/usj/transientCaretHost.ts:227 (also :353)

The mark is now what decides stripping, removal, blur and the keyboard rules. Several checks still go by content instead: any placeholder-only text node counts.

  • The reuse check at :227.
  • The focus check at :353.
  • DeltaOnChangePlugin (item 5).
  • The USJ serializer (packages/platform/src/editor/adaptors/editor-usj.adaptor.ts:821) and the delta adaptor (editor-delta.adaptor.ts:302), both unchanged.

Concrete cost: type a single ZWSP into a host.

  • The transform clears the mark and removes the host's own placeholder.
  • That leaves an unmarked "​" node. The editor now keeps it as content, and it survives leaving and blur.
  • The serializer and delta adaptor still drop it as a placeholder.

So the editor shows a character that is never saved or sent to peers. The test at EmptyVerseCaretGuardPlugin.test.tsx:400 only covers a ZWSP followed by Khmer text, so it doesn't catch this. It's still better than main, which lost the character outright.

Suggested fix:

  • At minimum, narrow the description's "typed zero-width space" claim to "a ZWSP followed by other text".
  • Longer term, decide per call site whether it means "marked host" or "placeholder-only text", and give the two predicates names that make the choice explicit. The serialized node already carries node state (the adaptor reads NODE_STATE_KEY at editor-usj.adaptor.ts:581), so the serializer could key on the mark.
  • Moving caretHostState, $createCaretHostNode and $isCaretHost out of the hook module, next to $caretHostAtBoundary in libs/shared, would also let structureKeyboard.utils.ts stop importing a React hook file for a predicate.

5. The delta fast-path fix special-cases one shape; another zero-length shape still deletes the next verse

Low · Confirmed (probe; the second shape is pre-existing) · libs/shared-react/src/plugins/usj/collab/DeltaOnChangePlugin.tsx:149

The fast path's own comment (:125-127) says eligibility comes from delta-doc counting through $isFastPathContentText, "instead of re-listing the exclusions". This fix re-lists one exclusion, and only for the previous node.

Another zero-contribution shape has the same bug:

  • Put an empty-char NBSP placeholder ($isEmptyCharPlaceholderText) between verse 2 and verse 3.
  • Call setTextContent("a") on the same key.
  • The fast path emits [{retain:1},{insert:"a"},{delete:1}]. That deletes the verse-3 embed, and replaying the ops doesn't match the real result.

I didn't verify that real typing into an empty char span keeps the same node key, so this second case may not be reachable from the keyboard. It's still the argument for generalizing.

Suggested fix:

  • Take the fast path only when the previous node also passes $isFastPathContentText (read in prevEditorState), or diff from $getNodeOTContribution(prevNode, "delta-doc"). That costs one full diff on the first keystroke into a host, and removes the special case.
  • If you keep the special case:
    • Rename isBareHost to something like isPlaceholderOnly, since the check is by content, not the mark.
    • Use $isCursorPlaceholderOnlyText(prevNode) instead of re-spelling it.

6. $hasCaretHostMark has no caller in this PR

Low · Confirmed (grep) · libs/shared-react/src/plugins/usj/transientCaretHost.ts:108

  • It's exported and documented as what "a transform that must leave a host alone" should ask, instead of $isCaretHost. But nothing in libs, packages or tests calls it, and no package index re-exports it.
  • Its only caller is in the stacked PT-4885 commit (TextSpacingPlugin).
  • Shipping it here gives readers two near-identical predicates and a rule with no example of using it.

Suggested fix: move it to the stacked PR, where its caller shows when to use which.

7. Design: the lifecycle runs once per guard, now including three focus handlers

Low (follow-up) · Traced · libs/shared-react/src/plugins/usj/transientCaretHost.ts:349

The platform editor mounts three guards (Editor.tsx). Each one runs useTransientCaretHost, with its own hostKeyRef, TextNode transform, and SELECTION_CHANGE, BLUR and now FOCUS handlers.

  • Because of the mark and adoption, the three refs end up tracking the same host. So they are three copies of one fact.
  • Correctness depends on how the copies interleave. That's why the code needs "another guard instance … may have removed it already" (:318) and "the first to see the node clears its mark" (:285).

This was mostly true on main, and the mark makes the cross-instance behavior better, not worse. This PR adds:

  • three focus handlers, each queuing a microtask and a state read per focus;
  • a slightly heavier per-node transform: a $getState plus a text compare, run three times on every dirty text node.

Suggested direction (follow-up ticket, not this PR): register the lifecycle once per editor: one owner of the host key, the transform, blur/focus and stale removal. The guards would contribute only their CaretHostAnchor rules, for example one CaretHostPlugin that takes a list of anchors. Worth doing before PT-4885 adds more host states to reason about.

8. The focus re-host can join a pending content update, and runs even after unmount

Nit · Confirmed mechanically in jsdom · libs/shared-react/src/plugins/usj/transientCaretHost.ts:355

editor.update($syncCaretHost) runs from a microtask, so it joins any update still pending in the same task. If it creates a host, its CURSOR_CHANGE_TAG and HISTORY_MERGE_TAG then cover that update's content edit too. The edit is hidden from onUsjChange and folded into the previous undo step.

  • Probe: root.blur(); root.focus(); editor.update(() => { …setTextContent("changed"); … }) produced a single commit tagged ["cursor-change","history-merge"] that carried the edit.
  • The trigger is narrow, because every focus path in platform and paranext-core goes through editor.focus(), which commits before the microtask runs. Only a raw root.focus() followed by a content update in the same task that leaves the caret hostless reaches it.
  • The microtask also has no check that the effect is still registered. If the guard unmounts between focus and the microtask, it can create a host that no instance tracks.

Suggested fix:

  • Set a disposed flag in the effect cleanup and check it in the microtask.
  • Optionally, skip the update when editor._pendingEditorState is set (or re-check after editor.update's commit), so the tags never cover a co-batched edit.

9. The hook's top-level docs no longer match what it does

Low · Confirmed by reading · libs/shared-react/src/plugins/usj/transientCaretHost.ts:49 (also :56, :180, :183)

Line Says Actually
:49-50 "takes over a host … that no instance tracks" It adopts any host this instance doesn't track (:254 says so).
:56-59 The tag-only-when-mutated rationale names CURSOR_CHANGE_TAG HISTORY_MERGE_TAG riding along would also fold the user's next edit into the previous undo step. That's the more surprising half.
:180 "stripped the moment real text is typed into it" It also loses its placeholder on paste and drop, only its own placeholder is removed, a range selection removes it, and focus re-hosts it.
:183 "Every mutation carries CURSOR_CHANGE_TAG … and HISTORY_MERGE_TAG" The strip transform mutates without tags, correctly, since it rides in the user's edit. Say "every host creation and removal".

Suggested rewrites:

  • :180: "it is created only when the caret comes to rest at such a position (or focus returns to one), removed as soon as the caret leaves (a range selection counts) or the editor blurs, and loses its placeholder the moment text lands in it."
  • :56-59: "It tags the active update (CURSOR_CHANGE_TAG, HISTORY_MERGE_TAG) only when it did. Lexical clears an update's tags only when the commit dirties a node, so tags on a selection-only commit ride along on the user's NEXT update, hiding it from the USJ-change handler and merging it into the previous undo step."

10. The new test separates an existing comment from the test it describes

Low · Confirmed by reading · libs/shared-react/src/plugins/usj/collab/DeltaOnChangePlugin.test.tsx:406

The comment at :403-405 ("tag every mutation … the commit never reaches this handler") introduces the existing "skips the delta for a CURSOR_CHANGE_TAG commit" test. The new "emits only the insert when text replaces a caret host" test was inserted between them. That test's commit does reach the handler, so the comment now reads as describing the opposite of what follows it.

Suggested fix: move the new it(...) above the comment.

11. Inline comments: stale, long or ambiguous

Nit · Confirmed by reading · libs/shared-react/src/plugins/usj/transientCaretHost.ts:338 (also :230, :267-277, :310-314, :330, :146)

  • :338-345 (FOCUS): "a host refocusing the editor" means the host application, but "host" means the caret host everywhere else in this file. The comment is also 8 lines. Suggested: "Focus can return without a selectionchange (the host application refocusing the editor, a menu closing), leaving the caret on the hostless point blur left. Re-host in a later update, since Lexical can fire focus mid-commit against the frozen state, and only when the committed caret lacks a host: an update outside any event reads its selection from the DOM, which may not yet hold the committed caret."
  • :310-314 (BLUR): the parenthetical "(into a collapsed note, past a trailing one)" repeats :328-329. Nothing explains announce: false at :330, which is load-bearing: announcing would fire SELECTION_CHANGE and re-host the caret inside the blur. Suggested: "Runs inside the blur's update. A caret in the host goes to the boundary it stood for, unannounced so no guard re-hosts it. SKIP_DOM_SELECTION_TAG: writing the selection back would refocus the editor."
  • :267-277 ($syncCaretHost): unchanged, but the body under it is now one line. It describes reads and tagging that now live in $repairCaret, and narrates the old bug ("evaluated the PREVIOUS commit … yanked the caret back"). Cut it to the rule: SELECTION_CHANGE runs inside the update that applies the new selection, so the repair reads the pending selection directly. Also keep "it converges".
  • :229-231: lists "unmount" as a cleanup path, but unmount only clears the ref. "Adopted host" here also covers unmarked nodes, which clashes with the description's "only marked nodes are … adopted".
  • :146: the offset-0 branch deliberately doesn't check previous.anchor.key, unlike the offset-1 branch. That's correct, because a ZWSP right at the caret identifies the placeholder, and adding the check would break a caret moved in from elsewhere. But it looks like an oversight. One clause saying why would stop someone "fixing" it.

12. $repairPast is now an identity wrapper, and the repair's boolean is unused

Nit · Confirmed by reading · libs/shared-react/src/plugins/usj/TrailingNoteCaretGuardPlugin.tsx:290

  • Now that $repairCaret tags its own update, $repairPast(note) just calls $repairCaret(note). The five-line comment above it still frames tagging as this caller's job.
  • No caller reads CaretHostRepair's boolean return any more (transientCaretHost.ts:62).
  • Unchanged, but nearby: :319-320 says the tag is "released like the caret repairs below". The repairs below never released tags, on main either.

Suggested fix:

  • Call $repairCaret(note) directly at the three call sites and delete the wrapper and its comment.
  • Make CaretHostRepair return void, and drop "Returns whether it changed any node" from its doc.
  • Fix the :319 wording while you're there.

13. Test comments and placement

Nit · Confirmed by reading · libs/shared-react/src/plugins/usj/EmptyVerseCaretGuardPlugin.test.tsx:385

  • EmptyVerseCaretGuardPlugin.test.tsx:385: "Shift+ArrowRight selects the placeholder; what lands next replaces it" describes a path that can't happen. A real Shift+Arrow fires selectionchange, and the guard removes the host first; :549 asserts exactly that. Suggested: "A selection over the placeholder that no selectionchange has reported yet: what lands replaces it."
  • :564: "replaced by a fresh one at the same position" isn't asserted. Either assert the new host or cut the comment to "The host is removed, and nothing is selected."
  • :333: the local type helper duplicates the describe-level insertText.
  • StructureKeyboardPlugin.test.tsx:795: the collapsed-caret Delete/Backspace test sits in "two-step delete for range selections with verse markers" (:738). Move it to "two-step delete guards", and say why the offsets are 0/1 (each key starts from the offset facing the placeholder).
  • TrailingNoteCaretGuardPlugin.test.tsx:382, :403, :1238: the same inline setTimeout(0) settle three times. EmptyVerseCaretGuardPlugin.test.tsx already has a settle() helper; share it.

@katherinejensen00 reviewed 11 files and all commit messages, and made 2 comments.
Reviewable status: all files reviewed, 1 unresolved discussion (waiting on timothy-mccormack).


libs/shared-react/src/plugins/usj/transientCaretHost.ts line 151 at r1 (raw file):

    }
  } else if (previous.anchor.key === node.getKey() && text[0] === CURSOR_PLACEHOLDER_CHAR) {
    index = 0;

1. Three new behaviors can be reverted without any test failing

Medium · Confirmed by mutation · libs/shared-react/src/plugins/usj/transientCaretHost.ts:151 (also structureKeyboard.utils.ts:185 and transientCaretHost.ts:331-332)

Each of these mutations passes every shared-react and platform test, and each one changes behavior a user or the host application would see.

Mutation What breaks Reachable by
Delete the offset-1 branch of $removeHostPlaceholder (:150-152) Typing at host offset 1 leaves "​a", and the ZWSP reaches saved USJ. That is the leak this PR exists to close. ArrowRight inside the host, or a browser click that lands after the placeholder
Drop && !$isCaretHost(node) in $caretAtParaEnd (structureKeyboard.utils.ts:185) With the caret at host offset 0 at a paragraph's end (where the guard puts it), $caretAtParaEnd returns false again. Delete there stops arming the structural delete. An empty last verse in a paragraph
Drop the blur's CURSOR_CHANGE_TAG / HISTORY_MERGE_TAG (:331-332) Every blur from a hosted caret creates its own undo step and fires onUsjChange. Clicking out of an empty verse
  • Only $adjacentVerseMarker has unit tests. The $caretAtParaStart / $caretAtParaEnd half of the Keyboard bullet has none.
  • Other surviving mutations turned out to be equivalent or masked downstream, so they need no test: :136, :148, :260, :292, :319 and :353. For example, :148 can't matter, because a host is always inserted after its anchor.

Suggested fix: in EmptyVerseCaretGuardPlugin.test.tsx, add:

  • Typing "a" with the caret at host offset 1. Assert the text is "a".
  • A blur from a hosted caret. Assert that onUsjChange isn't called and that the undo stack length is unchanged.

In structureKeyboard.utils.test.ts, add a $caretAtParaEnd case for a host that ends a paragraph, with the caret at offset 0.

timothy-mccormack and others added 2 commits October 26, 2026 22:01
- Tests for typing at host offset 1, blur staying out of undo and the
  USJ-change handler, and $caretAtParaStart/$caretAtParaEnd with a host
  (each fails if its behavior is reverted).
- A host undo restored is removed on blur, or when the caret leaves it,
  even if no selection change adopted it first.
- The delta fast path diffs the previous node from its delta-doc
  contribution, so an empty char span's stand-in no longer deletes the
  next verse either.
- The focus re-host flushes pending updates before deciding, and does
  nothing once its effect is torn down.
- CaretHostRepair returns void; the $repairPast wrapper is gone;
  $hasCaretHostMark moves to the PR that uses it.
- Docs, comments and test placement brought in line with the code.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
…rdening

# Conflicts:
#	packages/platform/dist/index.js
#	packages/platform/dist/index.js.map
@timothy-mccormack

Copy link
Copy Markdown
Contributor Author

I took all of these except Finding 7, which is in 5ffece5. #34 is rebased on top of it.

Finding 1 (untested behaviors): fixed. New tests:

  • typing "a" at host offset 1;
  • a blur from a hosted caret leaving the undo stack unchanged, with every commit tagged CURSOR_CHANGE_TAG;
  • $caretAtParaEnd / $caretAtParaStart with a host at either offset.

I re-applied each of your three mutations, and each one now fails a test.

Finding 2 (restored host orphaned): fixed both ways you suggested. Blur falls back to the host the caret rests in when nothing is tracked. The stale pass also treats the previous selection's host as stale once the caret has left it. Your two repro sequences are tests now, plus a third where the caret leaves through a DOM selection change. None of them hand-dispatches SELECTION_CHANGE, and all three fail on the previous head.

Finding 3 (tests that pass on main): the description now lists those three as regression guards. I dropped the Selection bullet, since main already did that.

Finding 4 (two ways to recognize a host): I narrowed the description's claim to a ZWSP followed by other text. The lone-ZWSP case is now listed as a known limitation. I left the per-call-site predicate split, and moving the mark into libs/shared, as follow-up work. The serializer change touches the USJ adaptor, which seemed too big to add to this PR.

Finding 5 (delta fast path): generalized. The fast path now diffs the previous node from $getNodeOTContribution(prevNode, "delta-doc") (now exported). A zero contribution diffs as empty; any other mismatch takes the full diff. Your NBSP stand-in case is a test now. It emitted retain 1, insert "a", delete 1 before the fix.

While checking that, I found a pre-existing issue. getEditorDelta emits a zero-length {insert: ""} for an empty char span, and quill-delta's diff mishandles it. For that shape, the full diff produces a stray retain: null. Diffing from the contribution means the fast path never relies on that. I haven't fixed it here, but the full-diff path still has it.

Finding 6 ($hasCaretHostMark unused): moved to #34, next to its TextSpacingPlugin caller.

Finding 7 (one lifecycle per editor): agreed, as a follow-up rather than in this PR. I'll leave the ticket decision to Tim.

Finding 8 (focus re-host): fixed. The microtask checks a disposed flag set in the effect's cleanup. It decides with editor.read, which commits any pending update first. So the re-host is always its own update, and its tags can't cover a co-batched edit.

Finding 9 (docs): fixed, using your rewrites for :180 and :56-59. I also corrected "no instance" to "this instance", and "every mutation" to "every host creation and removal". The doc notes the strip transform is untagged on purpose.

Finding 10 (test placement): fixed. The host test, and the new stand-in test, now sit above the comment.

Finding 11 (inline comments): fixed, mostly with your wording. FOCUS now says "the host application". BLUR explains announce: false. The $syncCaretHost comment is cut to the rule plus "it converges". The reuse comment no longer names unmount, and says an unmarked node is tracked but never removed. The offset-0 branch got its "why".

Finding 12 ($repairPast wrapper): fixed. The wrapper is gone, CaretHostRepair returns void, and I fixed the :319 wording. The transientCaretHost.test.tsx tests that read the boolean now assert the update's tags instead.

Finding 13 (test comments and placement): fixed. Both comments match what's asserted now, and the local type helper is replaced by insertText. The Delete/Backspace host test moved to "two-step delete guards", with a note on why its offsets are 0 and 1. settle() is shared from react-test.utils.tsx and used for the three inline settles.

Locally: shared-react 2235 and platform 4083 pass, with typecheck and lint clean and the committed dist verified.

After that, #30 and #32 landed on main and conflicted with the committed dist, so I merged main in as 312733f rather than rebasing under your review. Only the dist conflicted, and I rebuilt it. On the merge, shared 895, shared-react 2266 and platform 4124 pass.

@katherinejensen00 katherinejensen00 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.

These changes look good. It looks like the AI left creating a ticket for 4 and 7 up to you unless you ask it to create those for you, but everything else looks great. Thanks for your hard work on this across 3 PR's, Tim!

@katherinejensen00 reviewed 14 files and all commit messages, made 1 comment, and resolved 1 discussion.
Reviewable status: :shipit: complete! all files reviewed, all discussions resolved (waiting on timothy-mccormack).

@timothy-mccormack
timothy-mccormack merged commit 0e1808d into main Oct 27, 2026
6 checks passed
@timothy-mccormack
timothy-mccormack deleted the pt-4885-caret-host-hardening branch October 27, 2026 15:33
timothy-mccormack added a commit to paranext/paranext-core that referenced this pull request Oct 27, 2026
…ty verse (#2942)

The app styles the editor from its own vendored stylesheet, so the CSS
half of the PT-4885 fix lands here (paranext/scripture-editors#33 and
paranext/scripture-editors#34 carry the editor half). Both vendored
copies, `_usj-nodes.scss` and the demo `usj-nodes.css`, gain the rules:

- The empty-verse ellipsis is a fixed-width box
  (`--psc-empty-verse-ellipsis-width`: 13px in the app copy, deliberately,
  18px in the demo copy). The verse holding the caret keeps it but hides
  it.
- The caret host (`[data-caret-host]`) is pulled back over the hidden
  ellipsis by an equal margin, so the caret is drawn right after the
  number, and in every view a host after a verse takes `nowrap` and a
  trailing word joiner, so the line neither changes width nor wraps.
- The app copy gains the demo copy's RTL `.verse` / `.verse.marker`
  isolation rules, without which the caret was drawn beside the next
  verse's number in RTL projects.

Both headers record where the rules came from. The style tests pin each
load-bearing declaration on its exact selector list.

Checked by hand on macOS in LTR and RTL projects and with forced colors.

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants