Skip to content

Commit 21d8cea

Browse files
authored
Fix caret position after backspace (#16712)
* Added failing test for caret position after backspace * Fix incorrect caret position after backspace
1 parent 8540780 commit 21d8cea

File tree

2 files changed

+38
-1
lines changed

2 files changed

+38
-1
lines changed

src/Avalonia.Controls/TextBox.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1468,7 +1468,7 @@ protected override void OnKeyDown(KeyEventArgs e)
14681468

14691469
SetCurrentValue(CaretIndexProperty, start);
14701470

1471-
_presenter.MoveCaretToTextPosition(start, true);
1471+
_presenter.MoveCaretToTextPosition(start);
14721472
}
14731473
}
14741474

tests/Avalonia.Controls.UnitTests/TextBoxTests.cs

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1492,6 +1492,43 @@ public void Should_Throw_ArgumentOutOfRange()
14921492
}
14931493
}
14941494

1495+
[Fact]
1496+
public void Backspace_Should_Delete_Last_Character_In_Line_And_Keep_Caret_On_Same_Line()
1497+
{
1498+
using var _ = UnitTestApplication.Start(Services);
1499+
1500+
var textBox = new TextBox
1501+
{
1502+
Template = CreateTemplate(),
1503+
Text = "a\nb",
1504+
CaretIndex = 3
1505+
};
1506+
textBox.ApplyTemplate();
1507+
1508+
var topLevel = new TestTopLevel(CreateMockTopLevelImpl().Object)
1509+
{
1510+
Template = CreateTopLevelTemplate(),
1511+
Content = textBox
1512+
};
1513+
topLevel.ApplyTemplate();
1514+
topLevel.LayoutManager.ExecuteInitialLayoutPass();
1515+
1516+
var textPresenter = textBox.FindDescendantOfType<TextPresenter>();
1517+
Assert.NotNull(textPresenter);
1518+
1519+
var oldCaretY = textPresenter.GetCursorRectangle().Top;
1520+
Assert.NotEqual(0, oldCaretY);
1521+
1522+
RaiseKeyEvent(textBox, Key.Back, KeyModifiers.None);
1523+
1524+
Assert.Equal("a\n", textBox.Text);
1525+
Assert.Equal(2, textBox.CaretIndex);
1526+
Assert.Equal(2, textPresenter.CaretIndex);
1527+
1528+
var caretY = textPresenter.GetCursorRectangle().Top;
1529+
Assert.Equal(oldCaretY, caretY);
1530+
}
1531+
14951532
private static TestServices FocusServices => TestServices.MockThreadingInterface.With(
14961533
focusManager: new FocusManager(),
14971534
keyboardDevice: () => new KeyboardDevice(),

0 commit comments

Comments
 (0)