|
| 1 | +using Microsoft.AspNetCore.Components; |
| 2 | +using Microsoft.AspNetCore.Components.Routing; |
| 3 | +using System; |
| 4 | +using System.Collections.Generic; |
| 5 | +using System.Linq; |
| 6 | +using System.Text; |
| 7 | +using System.Threading.Tasks; |
| 8 | + |
| 9 | +namespace BlazorDialog |
| 10 | +{ |
| 11 | + public class LocationChangingHandler : ILocationChangingHandler, IDisposable |
| 12 | + { |
| 13 | + private readonly NavigationManager _navigationManager; |
| 14 | + private IDisposable? _currentRegistration; |
| 15 | + private List<Dialog> _dialogsStack = new List<Dialog>(); |
| 16 | + |
| 17 | + public LocationChangingHandler(NavigationManager navigationManager) |
| 18 | + { |
| 19 | + _navigationManager = navigationManager; |
| 20 | + } |
| 21 | + |
| 22 | + public void RegisterLocationChangingHandler(Dialog dialog) |
| 23 | + { |
| 24 | + if (!_dialogsStack.Contains(dialog)) |
| 25 | + { |
| 26 | + _dialogsStack.Add(dialog); |
| 27 | + } |
| 28 | + |
| 29 | + if(_currentRegistration == null) |
| 30 | + { |
| 31 | + _currentRegistration = _navigationManager.RegisterLocationChangingHandler(OnLocationChanging); |
| 32 | + } |
| 33 | + } |
| 34 | + |
| 35 | + private ValueTask OnLocationChanging(LocationChangingContext context) |
| 36 | + { |
| 37 | + if (!context.IsNavigationIntercepted && _dialogsStack.Any(x => x.PreventNavigation)) |
| 38 | + { |
| 39 | + context.PreventNavigation(); |
| 40 | + } |
| 41 | + return ValueTask.CompletedTask; |
| 42 | + } |
| 43 | + |
| 44 | + public void RemoveLocationChangingHandler(Dialog dialog) |
| 45 | + { |
| 46 | + if (_dialogsStack.Contains(dialog)) |
| 47 | + { |
| 48 | + _dialogsStack.Remove(dialog); |
| 49 | + } |
| 50 | + |
| 51 | + // if there are no dialogs left in the stack, we can remove the location changing handler |
| 52 | + if (_currentRegistration != null && _dialogsStack.Count == 0) |
| 53 | + { |
| 54 | + _currentRegistration.Dispose(); |
| 55 | + _currentRegistration = null; |
| 56 | + } |
| 57 | + } |
| 58 | + |
| 59 | + public void Dispose() |
| 60 | + { |
| 61 | + if(_currentRegistration != null) |
| 62 | + { |
| 63 | + _currentRegistration.Dispose(); |
| 64 | + _currentRegistration = null; |
| 65 | + } |
| 66 | + } |
| 67 | + } |
| 68 | +} |
0 commit comments