| | | 1 | | // ----------------------------------------------------------------------- |
| | | 2 | | // <copyright file="PresenterDialogStrategy.cs" company="Stéphane ANDRE"> |
| | | 3 | | // Copyright (c) Stéphane ANDRE. All rights reserved. |
| | | 4 | | // </copyright> |
| | | 5 | | // ----------------------------------------------------------------------- |
| | | 6 | | |
| | | 7 | | using System; |
| | | 8 | | using System.Collections.Generic; |
| | | 9 | | using System.Linq; |
| | | 10 | | using System.Threading; |
| | | 11 | | using System.Threading.Tasks; |
| | | 12 | | |
| | | 13 | | namespace MyNet.UI.Dialogs.ContentDialogs; |
| | | 14 | | |
| | | 15 | | /// <summary> |
| | | 16 | | /// Routes dialog display to the highest-priority registered <see cref="IDialogPresenter"/>. |
| | | 17 | | /// </summary> |
| | | 18 | | /// <param name="presenters">Presenters registered in the service collection.</param> |
| | | 19 | | public sealed class PresenterDialogStrategy(IEnumerable<IDialogPresenter> presenters) : IDialogStrategy |
| | | 20 | | { |
| | | 21 | | /// <summary>Default priority for presenter-based strategies (above <see cref="HeadlessDialogStrategy"/>).</summary> |
| | | 22 | | public const int DefaultPriority = 0; |
| | | 23 | | |
| | | 24 | | /// <inheritdoc /> |
| | 3 | 25 | | public int Priority => DefaultPriority; |
| | | 26 | | |
| | | 27 | | /// <inheritdoc /> |
| | 12 | 28 | | public bool CanHandle(IDialog dialog, DialogOptions? options) => SelectPresenter(dialog, options) is not null; |
| | | 29 | | |
| | | 30 | | /// <inheritdoc /> |
| | | 31 | | public Task<DialogResult<bool>> ShowAsync(IDialog dialog, DialogOptions options, CancellationToken ct = default) |
| | | 32 | | { |
| | 6 | 33 | | var presenter = SelectPresenter(dialog, options) |
| | 6 | 34 | | ?? throw new InvalidOperationException( |
| | 6 | 35 | | $"No {nameof(IDialogPresenter)} found for '{dialog.GetType().Name}'."); |
| | | 36 | | |
| | 6 | 37 | | return presenter.PresentAsync(dialog, options, ct); |
| | | 38 | | } |
| | | 39 | | |
| | | 40 | | /// <inheritdoc /> |
| | | 41 | | public Task CloseAsync(IDialog dialog) |
| | | 42 | | { |
| | 0 | 43 | | var presenter = SelectPresenter(dialog, null) |
| | 0 | 44 | | ?? throw new InvalidOperationException( |
| | 0 | 45 | | $"No {nameof(IDialogPresenter)} found for '{dialog.GetType().Name}'."); |
| | | 46 | | |
| | 0 | 47 | | return presenter.CloseAsync(dialog); |
| | | 48 | | } |
| | | 49 | | |
| | | 50 | | private IDialogPresenter? SelectPresenter(IDialog dialog, DialogOptions? options) |
| | 18 | 51 | | => presenters |
| | 18 | 52 | | .Where(p => p.CanPresent(dialog, options)) |
| | 18 | 53 | | .OrderByDescending(p => p.Priority) |
| | 18 | 54 | | .FirstOrDefault(); |
| | | 55 | | } |
| | | 56 | | |