Skip to content

input: fix caret jumping to end of text on iOS keyboard switch - #3799

Open
koteitan wants to merge 2 commits into
damus-io:masterfrom
koteitan:fix-cursor-jump-keyboard-switch
Open

input: fix caret jumping to end of text on iOS keyboard switch#3799
koteitan wants to merge 2 commits into
damus-io:masterfrom
koteitan:fix-cursor-jump-keyboard-switch

Conversation

@koteitan

@koteitan koteitan commented Jul 24, 2026

Copy link
Copy Markdown

Summary

Fixes the post composer caret jumping to the end of the text when the iOS keyboard-switching (globe) button is pressed while the caret is placed mid-text (#3545).

Root cause: PostView keeps an explicitly tracked cursor position (newCursorIndex) which TextViewWrapper.updateUIView applies with priority over the saved selection (a mechanism introduced in 4941b50 to fix #3461). The tracked position is updated on every text change, but never when the user moves the caret without editing (e.g. by tapping), and it is never cleared after being applied. After typing, it goes stale, still pointing at the position of the last edit — typically the end of the text. Switching keyboards changes the keyboard height, which triggers a SwiftUI re-render, and updateUIView re-applies the stale index, jumping the caret to the end.

Fix: implement textViewDidChangeSelection in the coordinator so user-driven caret moves keep the tracked position in sync, and suppress that tracking while updateUIView applies programmatic text/selection changes — their delegate callbacks must not be recorded as user moves, and view state must not be mutated during a SwiftUI view update. Range selections (length > 0) are left untracked since a single index cannot represent them; behavior there is unchanged.

Checklist

Standard PR Checklist

  • I have read (or I am familiar with) the Contribution Guidelines
  • I have tested the changes in this PR
  • I have profiled the changes to ensure there are no performance regressions, or I do not need to profile the changes.
    • If not needed, provide reason: the change adds a constant-time delegate callback on caret moves; no loops, I/O, or allocations on hot paths.
  • I have filed or linked an existing issue/ticket related to this change: Bug: The cursor jumps to the end of text when keyboard-switching button of iOS #3545
  • My PR is either small, or I have split it into smaller logical commits that are easier to review
  • I have added the signoff line to all my commits. See Signing off your work
  • I have added appropriate changelog entries for the changes in this PR (Changelog-Fixed)
  • I have added appropriate Closes: or Fixes: tags in the commit messages wherever applicable

Test report

Device: iPhone 11 Pro

iOS: 26.5.2

Damus (before / bug reproduction): official TestFlight build 1.18 (1332), commit 85e38ad4

Damus (after / fix verification): Debug build of this change sideloaded via AltStore, shown as version 1.18 (6) — built from the fork test branch (koteitan/damus @ 31be5c4 = this PR's change plus sideload-packaging-only commits)

Setup: English (QWERTY) and Japanese (Romaji QWERTY) keyboards enabled; logged in with an existing account.

Test 1 — main effect (with video)

Video comparing both builds: https://v.nostr.build/sdiqpZlYTsx9Cfup.mp4

Steps:

  1. Open the post composer and type a few lines of text
  2. Move the caret to the middle of the text using space-bar long-press (trackpad mode)
  3. Press the iOS keyboard-switching (globe) button

Results:

Test 2 — range selections are not tracked (the selectedRange.length == 0 guard)

Steps: double-tap a word to select it, then drag the selection handles to grow and shrink the selection.

Results: the selection stays stable while dragging and the edit menu works normally. (If range selections were tracked, each handle drag would mutate the tracked state and the resulting re-render would collapse the in-progress selection.)

Test 3 — programmatic changes are not tracked (the isApplyingProgrammaticChange guard)

Steps: with the caret mid-text, type @ plus a few letters, insert a mention from the autocomplete list, then press the globe button.

Results: after insertion the caret sits right after the mention, and it stays there across the keyboard switch. (When updateUIView re-assigns the attributed text, UIKit transiently resets the caret to the end and fires textViewDidChangeSelection; if that callback were recorded, the next keyboard switch would jump the caret to the end.)

Overall:

  • PASS (all three tests)

Unit test added: PostViewTests.testSelectionChangeUpdatesTrackedCursorPosition, covering the same three paths at the unit level: caret-move tracking, exclusion of range selections, and suppression of programmatic selection changes.

Other notes

🤖 Generated with Claude Code

https://claude.ai/code/session_0118vy9nfQ3SYqh8ARtMRRyb

Summary by CodeRabbit

  • Bug Fixes
    • Improved tracked caret/cursor position when users move the caret without editing text.
    • Prevented programmatic updates from incorrectly affecting tracked cursor position.
    • Ensured caret tracking ignores text-range selections (only single-caret movement is considered).
  • Tests
    • Added XCTest coverage for user-driven caret moves, range selection behavior, and ignoring programmatic selection changes.

The post composer tracks an explicit cursor position (newCursorIndex)
that takes priority over the saved selection when the view updates. It
was updated on every text change but never cleared or updated when the
user moved the caret without editing, so it went stale, still pointing
at the position of the last text edit (typically the end of the text).

Pressing the iOS keyboard-switch (globe) button changes the keyboard
height, which triggers a SwiftUI re-render, and updateUIView re-applied
the stale index, jumping the caret to the end of the text.

Track user-driven caret moves in textViewDidChangeSelection so the
tracked position never goes stale, and suppress tracking while
updateUIView applies programmatic text/selection changes, so their
delegate callbacks are not recorded as user-driven moves.

Changelog-Fixed: Fixed cursor jumping to the end of the text when pressing the iOS keyboard-switching button in the post composer
Closes: damus-io#3545

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Signed-off-by: koteitan <ukaibutton@mac.com>
@coderabbitai

coderabbitai Bot commented Jul 24, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: 246d6567-c5e9-48a3-a33c-aaa23381bf66

📥 Commits

Reviewing files that changed from the base of the PR and between 91248de and fa315e3.

📒 Files selected for processing (1)
  • damus/Shared/Components/Text/TextViewWrapper.swift
🚧 Files skipped from review as they are similar to previous changes (1)
  • damus/Shared/Components/Text/TextViewWrapper.swift

📝 Walkthrough

Walkthrough

TextViewWrapper now distinguishes programmatic text and selection updates from user caret movement, while tests verify caret, range-selection, and programmatic-selection behavior.

Changes

Text Selection Tracking

Layer / File(s) Summary
Selection callback handling
damus/Shared/Components/Text/TextViewWrapper.swift, damusTests/PostViewTests.swift
TextViewWrapper marks programmatic updates, ignores their selection callbacks, tracks user caret movements, and tests caret, range, and programmatic selection behavior.

Estimated code review effort: 2 (Simple) | ~10 minutes

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly matches the main change: fixing the caret jump on iOS keyboard switching.
Description check ✅ Passed The description follows the template with summary, standard checklist, test report, and other notes filled in.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@koteitan
koteitan marked this pull request as ready for review July 24, 2026 17:08

@coderabbitai coderabbitai Bot 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.

🧹 Nitpick comments (2)
damus/Shared/Components/Text/TextViewWrapper.swift (1)

53-56: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Add /// documentation for the selection-tracking contract.

The new coordinator property and delegate method, plus the modified updateUIView behavior, are documented only with inline // comments. Add declaration-level Swift doc comments describing when programmatic callbacks are suppressed and when caret positions are tracked.

As per coding guidelines, Swift code must ensure docstring coverage for any code added or modified.

Also applies to: 116-118, 160-168

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@damus/Shared/Components/Text/TextViewWrapper.swift` around lines 53 - 56, The
selection-tracking contract lacks declaration-level Swift documentation. Add ///
doc comments to the coordinator’s programmatic-change state property, the
relevant delegate method, and the modified updateUIView behavior, documenting
that programmatic callbacks are suppressed while only user-driven caret moves
update the tracked position; retain the existing inline comments and behavior.

Source: Coding guidelines

damusTests/PostViewTests.swift (1)

322-356: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Exercise updateUIView in the suppression test.

This test manually sets isApplyingProgrammaticChange, so it verifies only the delegate guard. It would still pass if updateUIView stopped setting or resetting that flag. Add coverage that invokes updateUIView and confirms programmatic selection callbacks are suppressed and the flag is restored afterward.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@damusTests/PostViewTests.swift` around lines 322 - 356, Extend
testSelectionChangeUpdatesTrackedCursorPosition to invoke updateUIView while
applying a programmatic selection change, using the existing coordinator,
textView, and binding setup. Verify the selection callback does not update
trackedCursorPosition during updateUIView, then assert
isApplyingProgrammaticChange is restored to false afterward.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Nitpick comments:
In `@damus/Shared/Components/Text/TextViewWrapper.swift`:
- Around line 53-56: The selection-tracking contract lacks declaration-level
Swift documentation. Add /// doc comments to the coordinator’s
programmatic-change state property, the relevant delegate method, and the
modified updateUIView behavior, documenting that programmatic callbacks are
suppressed while only user-driven caret moves update the tracked position;
retain the existing inline comments and behavior.

In `@damusTests/PostViewTests.swift`:
- Around line 322-356: Extend testSelectionChangeUpdatesTrackedCursorPosition to
invoke updateUIView while applying a programmatic selection change, using the
existing coordinator, textView, and binding setup. Verify the selection callback
does not update trackedCursorPosition during updateUIView, then assert
isApplyingProgrammaticChange is restored to false afterward.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: ca9d4d4b-f4fe-4403-ac53-a4e1822ac7eb

📥 Commits

Reviewing files that changed from the base of the PR and between e462dbd and 91248de.

📒 Files selected for processing (2)
  • damus/Shared/Components/Text/TextViewWrapper.swift
  • damusTests/PostViewTests.swift

Convert the inline comments on the selection tracking added by the
previous commit into declaration-level doc comments, per the docstring
coverage guideline. Comment-only change; no code change.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Signed-off-by: koteitan <ukaibutton@mac.com>
@tkhumush

Copy link
Copy Markdown

This has been an annoyance for a while now. it would be great seeing it fixed.

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.

New note: cursor jumps behind first letter

2 participants