diff --git a/src/CodeBeam.MudBlazor.Extensions/Components/CodeInput/MudCodeInput.razor.cs b/src/CodeBeam.MudBlazor.Extensions/Components/CodeInput/MudCodeInput.razor.cs index d5f25669..df2bdf6b 100644 --- a/src/CodeBeam.MudBlazor.Extensions/Components/CodeInput/MudCodeInput.razor.cs +++ b/src/CodeBeam.MudBlazor.Extensions/Components/CodeInput/MudCodeInput.razor.cs @@ -248,7 +248,7 @@ protected async Task CheckFocus(int count) return; } string str = ConvertSet(_theValue.Value) ?? string.Empty; - await _elementReferences[str.Length].FocusAsync(); + await _elementReferences[Math.Min(str.Length, _count.Value - 1)].FocusAsync(); } /// diff --git a/tests/CodeBeam.MudBlazor.Extensions.UnitTests/Components/CodeInputTests.cs b/tests/CodeBeam.MudBlazor.Extensions.UnitTests/Components/CodeInputTests.cs new file mode 100644 index 00000000..33ba901a --- /dev/null +++ b/tests/CodeBeam.MudBlazor.Extensions.UnitTests/Components/CodeInputTests.cs @@ -0,0 +1,27 @@ +using Bunit; +using AwesomeAssertions; +using Microsoft.AspNetCore.Components; + +namespace MudExtensions.UnitTests.Components +{ + [TestFixture] + public class CodeInputTests : BunitTest + { + [TestCase("123", 3)] + [TestCase("123456", 5)] + public async Task CodeInput_Focus_RedirectsToFirstEmptyOrLastBox(string value, int expectedIndex) + { + var comp = Context.Render>(opt => + { + opt.Add(a => a.Count, 6); + opt.Add(a => a.Value, value); + }); + var fields = comp.FindComponents>(); + + await comp.FindAll("input")[1].FocusAsync(new()); + + var focused = (ElementReference)Context.JSInterop.VerifyFocusAsyncInvoke().Arguments[0]!; + focused.Id.Should().Be(fields[expectedIndex].Instance.InputReference.ElementReference.Id); + } + } +}