Skip to content

Commit

Permalink
close on escape
Browse files Browse the repository at this point in the history
  • Loading branch information
erinnmclaughlin committed May 20, 2024
1 parent 483399f commit 255fb3c
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 1 deletion.
2 changes: 1 addition & 1 deletion src/HeadlessBlazor.Core/HeadlessBlazor.Core.csproj
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
<Project Sdk="Microsoft.NET.Sdk.Razor">
<Project Sdk="Microsoft.NET.Sdk.Razor">

<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
Expand Down
16 changes: 16 additions & 0 deletions src/HeadlessBlazor.Dropdown/HBDropdown.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Components.Rendering;
using Microsoft.AspNetCore.Components.Web;

namespace HeadlessBlazor;

Expand All @@ -9,6 +10,9 @@ public class HBDropdown : HBElement<HBDropdown>, IReferenceable

public bool IsOpen { get; private set; }

[Parameter]
public bool CloseOnEscape { get; set; } = true;

[Parameter]
public bool CloseOnOutsideClick { get; set; } = true;

Expand Down Expand Up @@ -59,6 +63,18 @@ protected override void BuildRenderTree(RenderTreeBuilder builder)
builder.CloseComponent();
}

protected override void AddEventHandlers(RenderTreeBuilder builder, ref int sequenceNumber)
{
if (CloseOnEscape)
{
builder.AddAttribute(sequenceNumber++, "onkeydown", EventCallback.Factory.Create<KeyboardEventArgs>(this, async (args) =>
{
if (args.Key == "Escape")
await CloseAsync();
}));
}
}

protected override void AddElementReference(RenderTreeBuilder builder, ref int sequenceNumber)
{
builder.AddElementReferenceCapture(sequenceNumber++, async capturedRef =>
Expand Down

0 comments on commit 255fb3c

Please sign in to comment.