From b8f58a0a4773959ed5e76ff0e9c50bf504874fb0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Marek=20Fi=C5=A1era?= Date: Wed, 23 Nov 2022 20:28:35 +0100 Subject: [PATCH] #434 - Any open modal is close on back button and navigation is intercepted. --- .../Components/Bootstrap/Modal.razor.cs | 18 +++++++++++++----- .../Components/Bootstrap/ModalInterop.cs | 3 +++ src/Money.Blazor.Host/wwwroot/js/site.js | 4 ++++ 3 files changed, 20 insertions(+), 5 deletions(-) diff --git a/src/Money.Blazor.Host/Components/Bootstrap/Modal.razor.cs b/src/Money.Blazor.Host/Components/Bootstrap/Modal.razor.cs index 4c2860b7..564a466c 100644 --- a/src/Money.Blazor.Host/Components/Bootstrap/Modal.razor.cs +++ b/src/Money.Blazor.Host/Components/Bootstrap/Modal.razor.cs @@ -13,8 +13,10 @@ namespace Money.Components.Bootstrap { public partial class Modal : System.IDisposable { + private System.IDisposable locationChangingToken; + [Inject] - internal ModalInterop Interop { get; set; } + protected ModalInterop Interop { get; set; } [Inject] internal ILog Log { get; set; } @@ -62,17 +64,23 @@ public partial class Modal : System.IDisposable protected override void OnInitialized() { base.OnInitialized(); - NavigationManager.LocationChanged += OnLocationChanged; + locationChangingToken = NavigationManager.RegisterLocationChangingHandler(OnLocationChanging); } public void Dispose() { Hide(); - NavigationManager.LocationChanged -= OnLocationChanged; + locationChangingToken.Dispose(); } - private void OnLocationChanged(object sender, LocationChangedEventArgs e) - => Hide(); + private async ValueTask OnLocationChanging(LocationChangingContext context) + { + if (await Interop.IsOpenAsync(Container)) + { + context.PreventNavigation(); + Hide(); + } + } protected override void OnParametersSet() { diff --git a/src/Money.Blazor.Host/Components/Bootstrap/ModalInterop.cs b/src/Money.Blazor.Host/Components/Bootstrap/ModalInterop.cs index 768157fd..2d5834de 100644 --- a/src/Money.Blazor.Host/Components/Bootstrap/ModalInterop.cs +++ b/src/Money.Blazor.Host/Components/Bootstrap/ModalInterop.cs @@ -29,5 +29,8 @@ internal void Hide(ElementReference element) internal void Dispose(ElementReference element) => jsRuntime.InvokeVoidAsync("Bootstrap.Modal.Dispose", element); + + internal ValueTask IsOpenAsync(ElementReference element) + => jsRuntime.InvokeAsync("Bootstrap.Modal.IsOpen", element); } } diff --git a/src/Money.Blazor.Host/wwwroot/js/site.js b/src/Money.Blazor.Host/wwwroot/js/site.js index 832464e7..a8d0c162 100644 --- a/src/Money.Blazor.Host/wwwroot/js/site.js +++ b/src/Money.Blazor.Host/wwwroot/js/site.js @@ -24,6 +24,10 @@ window.Bootstrap = { Hide: function (container) { $(container).modal('hide'); }, + IsOpen: function (container) { + const data = $(container).data('bs.modal'); + return !data || !data._isShown ? false : true; + }, Dispose: function (container) { $(container).modal('dispose'); }