Skip to content

Commit

Permalink
Add check for Focusing tab button during pre-rendering
Browse files Browse the repository at this point in the history
  • Loading branch information
codymullins committed Aug 8, 2024
1 parent 5941841 commit 4bb55da
Showing 1 changed file with 12 additions and 10 deletions.
22 changes: 12 additions & 10 deletions src/Pure.Blazor.Components/Layout/PureTabButton.razor
Original file line number Diff line number Diff line change
@@ -1,13 +1,14 @@
@using System.Text
@inherits PureComponent
<button @ref="_elementReference" tabindex="@(IsActive ? 0 : -1)" @onclick="@((e) => { Console.WriteLine("clicked"); OnClick.InvokeAsync(e); })" class="@ApplyStyle(InternalCss)" @onkeyup="OnKeyUp" role="tab">
<button @ref="_elementReference" @key="Title" tabindex="@(IsActive ? 0 : -1)" @onclick="@((e) => { Console.WriteLine("clicked"); OnClick.InvokeAsync(e); })" class="@ApplyStyle(InternalCss)" @onkeyup="OnKeyUp" role="tab">
<!-- todo: icon -->
@Title
</button>

@code {
private ElementReference? _elementReference;
private ElementReference _elementReference;
private bool prevStateActive = false;
[Inject] public required ILogger<PureTabButton> Logger { get; set; }
[Parameter] public string Title { get; set; } = string.Empty;

[Parameter] public bool IsActive { get; set; }
Expand All @@ -28,23 +29,24 @@
}

private string InternalCss { get; set; } = string.Empty;

protected override async Task OnParametersSetAsync()
{
if (_elementReference is null)
{
return;
}

// If the button is not active yet, but the parameter is set to active, focus on the button.
// This is to ensure that the button is focused when it becomes active the first time.
if (!prevStateActive && IsActive)
{
try
{
await _elementReference.Value.FocusAsync();
// Context is null when pre-rendering or when using static rendering
if (_elementReference.Context is not null)
{
await Task.Run(async () => await _elementReference.FocusAsync());
}
}
catch (Exception e)
{
Console.WriteLine(e);
// Log the error and continue
Logger.LogWarning(e, "Failed to focus on tab button");
}
}

Expand Down

0 comments on commit 4bb55da

Please sign in to comment.