Merge pull request #94114 from bruvzg/ios_text_change

[iOS/Text Input] Avoid deleting and reentering unchanged part of text.
This commit is contained in:
Rémi Verschelde 2024-07-09 16:47:23 +02:00
commit 1b0430dc3a
No known key found for this signature in database
GPG Key ID: C3336907360768E1
1 changed files with 18 additions and 12 deletions

View File

@ -149,23 +149,18 @@
return; return;
} }
NSString *substringToDelete = nil;
if (self.previousSelectedRange.length == 0) { if (self.previousSelectedRange.length == 0) {
// We are deleting all text before cursor if no range was selected. // Get previous text to delete.
// This way any inserted or changed text will be updated. substringToDelete = [self.previousText substringToIndex:self.previousSelectedRange.location];
NSString *substringToDelete = [self.previousText substringToIndex:self.previousSelectedRange.location];
[self deleteText:substringToDelete.length];
} else { } else {
// If text was previously selected // If text was previously selected we are sending only one `backspace`. It will remove all text from text input.
// we are sending only one `backspace`.
// It will remove all text from text input.
[self deleteText:1]; [self deleteText:1];
} }
NSString *substringToEnter; NSString *substringToEnter = nil;
if (self.selectedRange.length == 0) { if (self.selectedRange.length == 0) {
// If previous cursor had a selection // If previous cursor had a selection we have to calculate an inserted text.
// we have to calculate an inserted text.
if (self.previousSelectedRange.length != 0) { if (self.previousSelectedRange.length != 0) {
NSInteger rangeEnd = self.selectedRange.location + self.selectedRange.length; NSInteger rangeEnd = self.selectedRange.location + self.selectedRange.length;
NSInteger rangeStart = MIN(self.previousSelectedRange.location, self.selectedRange.location); NSInteger rangeStart = MIN(self.previousSelectedRange.location, self.selectedRange.location);
@ -187,7 +182,18 @@
substringToEnter = [self.text substringWithRange:self.selectedRange]; substringToEnter = [self.text substringWithRange:self.selectedRange];
} }
[self enterText:substringToEnter]; NSInteger skip = 0;
if (substringToDelete != nil) {
for (NSInteger i = 0; i < MIN([substringToDelete length], [substringToEnter length]); i++) {
if ([substringToDelete characterAtIndex:i] == [substringToEnter characterAtIndex:i]) {
skip++;
} else {
break;
}
}
[self deleteText:[substringToDelete length] - skip]; // Delete changed part of previous text.
}
[self enterText:[substringToEnter substringFromIndex:skip]]; // Enter changed part of new text.
self.previousText = self.text; self.previousText = self.text;
self.previousSelectedRange = self.selectedRange; self.previousSelectedRange = self.selectedRange;