@inherits DComponentBase
@* daisyUI Modal: https://daisyui.com/components/modal/ . Always rendered; the open state lives in C# (@bind-IsOpen)
and shows as modal-open. On opening, the box takes the focus (Blazor's FocusAsync) so that Escape, handled on the
root, closes it; the backdrop button stretches over the area outside the box and closes it on click. *@
@if (Heading is not null)
{
@Heading
}
@ChildContent
@if (Actions is not null)
{
@Actions
}
@if (CloseOnBackdrop)
{
@CloseText
}
@code {
[Parameter] public RenderFragment Heading { get; set; }
[Parameter] public RenderFragment ChildContent { get; set; }
[Parameter] public RenderFragment Actions { get; set; }
[Parameter] public bool IsOpen { get; set; }
[Parameter] public EventCallback IsOpenChanged { get; set; }
[Parameter] public DModalPlacement Placement { get; set; }
/// Close on a click outside the box (renders the modal-backdrop).
[Parameter] public bool CloseOnBackdrop { get; set; } = true;
/// Text of the invisible backdrop button, read by screen readers.
[Parameter] public string CloseText { get; set; } = "close";
[Parameter] public string BoxClass { get; set; }
readonly string uid = "d" + Guid.NewGuid().ToString("N")[..8];
ElementReference box;
bool wasOpen;
bool focusPending;
string CssClass => Cx("modal", PlacementClass, IsOpen ? "modal-open" : null, Class);
string PlacementClass => Placement switch
{
DModalPlacement.Top => "modal-top",
DModalPlacement.Bottom => "modal-bottom",
DModalPlacement.Start => "modal-start",
DModalPlacement.End => "modal-end",
_ => null
};
protected override void OnParametersSet()
{
if (IsOpen && !wasOpen)
focusPending = true;
wasOpen = IsOpen;
}
protected override async Task OnAfterRenderAsync(bool firstRender)
{
if (!focusPending)
return;
focusPending = false;
await box.FocusAsync();
}
Task Close() => SetOpen(false);
Task OnKeyDown(KeyboardEventArgs e) => e.Key == "Escape" && IsOpen ? SetOpen(false) : Task.CompletedTask;
async Task SetOpen(bool isOpen)
{
IsOpen = isOpen;
wasOpen = isOpen;
await IsOpenChanged.InvokeAsync(isOpen);
}
}