Skip to content

Commit

Permalink
Control background click mouse events (#523)
Browse files Browse the repository at this point in the history
Mouse click, down, and up events will be handled to avoid closing the modal by accident.
This avoids accidents when highlighting text and dragging the mouse cursor outside of the modal area (into the background).

Solves #518

This also allows the user to escape closing the modal by dragging the mouse click back into the modal content area.

Co-authored-by: Chris Sainty <[email protected]>
  • Loading branch information
gian7sm and chrissainty authored Oct 2, 2023
1 parent 91ea15a commit 6b30fd0
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 4 deletions.
8 changes: 5 additions & 3 deletions src/Blazored.Modal/BlazoredModalInstance.razor
Original file line number Diff line number Diff line change
Expand Up @@ -7,11 +7,13 @@
else
{
<div class="bm-container @Position @OverlayCustomClass @OverlayAnimationClass"
@ref="_modalReference"
@onclick="HandleBackgroundClick">
@ref="_modalReference"
@onmousedown="ListenToBackgroundClick"
@onmouseup="HandleBackgroundClick"
@onclick="StopListeningToBackgroundClick">

<FocusTrap @ref="FocusTrap" IsActive="ActivateFocusTrap">
<div class="@ModalClass" role="dialog" aria-modal="true" @onclick:stopPropagation="true">
<div class="@ModalClass" role="dialog" aria-modal="true" @onmouseup:stopPropagation="true" @onmousedown:stopPropagation="true">
@if (!HideHeader)
{
<div class="bm-header">
Expand Down
13 changes: 12 additions & 1 deletion src/Blazored.Modal/BlazoredModalInstance.razor.cs
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ public partial class BlazoredModalInstance : IDisposable
private ElementReference _modalReference;
private bool _setFocus;
private bool _disableNextRender;
private bool _listenToBackgroundClicks;

// Temporarily add a tabindex of -1 to the close button so it doesn't get selected as the first element by activateFocusTrap
private readonly Dictionary<string, object> _closeBtnAttributes = new() { { "tabindex", "-1" } };
Expand Down Expand Up @@ -334,9 +335,19 @@ private async Task HandleBackgroundClick()
return;
}

await CancelAsync();
if (_listenToBackgroundClicks)
{
await CancelAsync();
_listenToBackgroundClicks = false;
}
}

private void ListenToBackgroundClick()
=> _listenToBackgroundClicks = true;

private void StopListeningToBackgroundClick()
=> _listenToBackgroundClicks = false;

void IDisposable.Dispose()
=> Parent.OnModalClosed -= AttemptFocus;
}

0 comments on commit 6b30fd0

Please sign in to comment.