40 lines
1.4 KiB
C#
40 lines
1.4 KiB
C#
namespace decePubClient.Services
|
|||
|
|
{
|
||
|
|
/// <summary>
|
||
|
|
/// Asks before what can't be undone (deleting a post, blocking, leaving a group, signing out): Ask shows the question
|
||
|
|
/// in ConfirmHost (MainLayout) and returns whether the reader confirmed it. One question at a time; a second one asked
|
||
|
|
/// while the first is open answers the first no.
|
||
|
|
/// </summary>
|
||
|
|
public class ConfirmService
|
||
|
|
{
|
||
|
|
TaskCompletionSource<bool> pending;
|
||
|
|
|
||
|
|
public event Action Changed;
|
||
|
|
|
||
|
|
public bool IsAsking => pending is not null;
|
||
|
|
public string Heading { get; private set; }
|
||
|
|
public string Text { get; private set; }
|
||
|
|
public string ConfirmText { get; private set; }
|
||
|
|
/// <summary>The confirm button shows as a danger (it deletes or cuts something off).</summary>
|
||
|
|
public bool Danger { get; private set; }
|
||
|
|
|
||
|
|
public async Task<bool> Ask(string heading, string text, string confirmText, bool danger, CancellationToken cancellationToken = default)
|
||
|
|
{
|
||
|
|
pending?.TrySetResult(false);
|
||
|
|
var asking = new TaskCompletionSource<bool>();
|
||
|
|
pending = asking;
|
||
|
|
(Heading, Text, ConfirmText, Danger) = (heading, text, confirmText, danger);
|
||
|
|
Changed?.Invoke();
|
||
|
|
await using var cancel = cancellationToken.Register(() => asking.TrySetResult(false));
|
||
|
|
var confirmed = await asking.Task;
|
||
|
|
if (pending == asking)
|
||
|
|
{
|
||
|
|
pending = null;
|
||
|
|
Changed?.Invoke();
|
||
|
|
}
|
||
|
|
return confirmed;
|
||
|
|
}
|
||
|
|
|
||
|
|
public void Answer(bool confirmed) => pending?.TrySetResult(confirmed);
|
||
|
|
}
|
||
|
|
}
|