Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
44 changes: 28 additions & 16 deletions src/BootstrapBlazor/Components/SweetAlert/SweetAlertBody.razor.cs
Original file line number Diff line number Diff line change
Expand Up @@ -174,29 +174,41 @@ protected override void OnParametersSet()
ConfirmButtonIcon ??= IconTheme.GetIconByKey(ComponentIcons.SweetAlertConfirmIcon);
}

private async Task OnClickClose()
{
if (OnCloseAsync != null)
{
await OnCloseAsync();
}
private bool _isClosing;

if (CloseModal != null)
{
await CloseModal();
}
}
private bool _actionCompleted;

private Task OnClickClose() => CloseAsync(OnCloseAsync);

private Task OnClickConfirm() => CloseAsync(OnConfirmAsync);

private async Task OnClickConfirm()
private async Task CloseAsync(Func<Task>? callback)
{
if (OnConfirmAsync != null)
if (_isClosing)
{
await OnConfirmAsync();
return;
}

if (CloseModal != null)
_isClosing = true;
try
{
if (!_actionCompleted)
{
if (callback != null)
{
await callback();
}
_actionCompleted = true;
Comment on lines +199 to +201

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Medium · Callbacks repeat after exceptions

When a close or confirm callback performs a side effect and then throws, and the user retries the action, CloseAsync leaves _actionCompleted false and resets _isClosing, so a later click invokes the callback again and repeats the side effect.

Prevent the callback from being invoked again after it has performed a side effect and thrown.

Prompt for AI agents
In `src/BootstrapBlazor/Components/SweetAlert/SweetAlertBody.razor.cs` at lines 199-201:

**Callbacks repeat after exceptions**

When a close or confirm callback performs a side effect and then throws, and the user retries the action, `CloseAsync` leaves `_actionCompleted` false and resets `_isClosing`, so a later click invokes the callback again and repeats the side effect.

Prevent the callback from being invoked again after it has performed a side effect and thrown.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Medium · Auto-hide bypasses action guard

When an auto-hide timer expires while a user-triggered close callback is in progress, the auto-hide path invokes option.OnCloseAsync directly while the button path invokes it through CloseAsync; if the timer expires while a close-button callback is running, both paths execute the callback and duplicate its side effects.

Route auto-hide through the same shared once-only close-action guard as button-triggered closes.

Prompt for AI agents
In `src/BootstrapBlazor/Components/SweetAlert/SweetAlertBody.razor.cs` at line 201:

**Auto-hide bypasses action guard**

When an auto-hide timer expires while a user-triggered close callback is in progress, the auto-hide path invokes `option.OnCloseAsync` directly while the button path invokes it through `CloseAsync`; if the timer expires while a close-button callback is running, both paths execute the callback and duplicate its side effects.

Route auto-hide through the same shared once-only close-action guard as button-triggered closes.

}

if (CloseModal != null)
{
await CloseModal();
}
}
finally
{
await CloseModal();
_isClosing = false;
}
}
}
18 changes: 16 additions & 2 deletions src/BootstrapBlazor/Extensions/SwalExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -14,15 +14,29 @@ public static class SwalExtensions
/// <summary>
/// <para lang="zh">异步回调方法</para>
/// <para lang="en">异步callback method</para>
/// <para lang="zh">已有弹窗显示时忽略新请求并返回 false。</para>
/// <para lang="en">Ignores a new request and returns false while a popup is already displayed.</para>
/// </summary>
/// <param name="service"></param>
/// <param name="option"></param>
/// <param name="swal"><para lang="zh">指定弹窗组件 默认为 null 使用 <see cref="BootstrapBlazorRoot"/> 组件内置弹窗组件</para><para lang="en">指定弹窗component default is为 null 使用 <see cref="BootstrapBlazorRoot"/> component内置弹窗component</para></param>
public static async Task<bool> ShowModal(this SwalService service, SwalOption option, SweetAlert? swal = null)
{
var isConfirm = option.IsConfirm;
option.IsConfirm = true;
await service.Show(option, swal);
return await option.ConfirmContext.ConfirmTask.Task;
var previousContext = option.ConfirmContext;
// An accepted request assigns its context before awaiting rendering.
var showTask = service.Show(option, swal);
var context = option.ConfirmContext;
await showTask;

if (context == null || context == previousContext)
{
option.IsConfirm = isConfirm;
return false;
}

return await context.ConfirmTask.Task;
}

/// <summary>
Expand Down
109 changes: 109 additions & 0 deletions test/UnitTest/Components/SwalTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,115 @@ namespace UnitTest.Components;

public class SwalTest : BootstrapBlazorTestBase
{
[Theory]
[InlineData(true)]
[InlineData(false)]
public async Task ShowModal_ReturnsConfirmationResult_Ok(bool expected)
{
var cut = Context.Render<BootstrapBlazorRoot>(pb =>
{
pb.AddChildContent<MockSwalTest>();
});
var swal = cut.FindComponent<MockSwalTest>().Instance.SwalService;
var option = new SwalOption();
var modalTask = Task.FromResult(false);

await cut.InvokeAsync(() =>
{
modalTask = swal.ShowModal(option);
});

var modal = cut.FindComponents<Modal>().Last();
await cut.InvokeAsync(() => cut.Find(expected ? ".btn-danger" : ".btn-secondary").Click());
await cut.InvokeAsync(() => modal.Instance.CloseCallback());

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Medium · Cancel result passes without canceling

When the secondary-button handler fails to set the confirmation value and the modal is still closed, in ShowModal_ReturnsConfirmationResult_Ok(false), the assertion at SwalTest.cs:32 still passes if the secondary-button handler never writes false: line 30 calls CloseCallback directly, which resolves the task from the default-false SweetContext.Value, so the broken cancel action is reported as successful.

Make the cancellation case fail unless the secondary-button handler ran, for example by asserting an observable callback side effect before invoking CloseCallback.

Prompt for AI agents
In `test/UnitTest/Components/SwalTest.cs` at line 30:

**Cancel result passes without canceling**

When the secondary-button handler fails to set the confirmation value and the modal is still closed, in `ShowModal_ReturnsConfirmationResult_Ok(false)`, the assertion at `SwalTest.cs:32` still passes if the secondary-button handler never writes `false`: line 30 calls `CloseCallback` directly, which resolves the task from the default-false `SweetContext.Value`, so the broken cancel action is reported as successful.

Make the cancellation case fail unless the secondary-button handler ran, for example by asserting an observable callback side effect before invoking `CloseCallback`.


Assert.Equal(expected, await modalTask);
Assert.True(option.IsConfirm);
}

[Fact]
public async Task ShowModal_IgnoresRequestsWhileBusy_Ok()
{
var cut = Context.Render<BootstrapBlazorRoot>(pb =>
{
pb.AddChildContent<MockSwalTest>();
});
var swal = cut.FindComponent<MockSwalTest>().Instance.SwalService;
var option = new SwalOption()
{
Content = "Active Swal"
};
var modalTask = Task.FromResult(false);

await cut.InvokeAsync(() =>
{
modalTask = swal.ShowModal(option);
});

var newOption = new SwalOption()
{
Content = "Ignored Swal"
};
var newRequestTask = Task.FromResult(true);
await cut.InvokeAsync(() =>
{
newRequestTask = swal.ShowModal(newOption);
});

Assert.False(await newRequestTask);
Assert.False(newOption.IsConfirm);

var repeatedRequestTask = Task.FromResult(true);
await cut.InvokeAsync(() =>
{
repeatedRequestTask = swal.ShowModal(option);
});

Assert.False(await repeatedRequestTask);
Assert.True(option.IsConfirm);
Assert.Contains("Active Swal", cut.Markup);
Assert.DoesNotContain("Ignored Swal", cut.Markup);

var modal = cut.FindComponents<Modal>().Last();
await cut.InvokeAsync(() => cut.Find(".btn-danger").Click());
await cut.InvokeAsync(() => modal.Instance.CloseCallback());

Assert.True(await modalTask);
}

[Fact]
public async Task CloseAsync_IgnoresConcurrentCall_Ok()
{
var callbackStarted = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
var continueCallback = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
var callbackCount = 0;
var cut = Context.Render<SweetAlertBody>(pb =>
{
pb.Add(a => a.IsConfirm, true);
pb.Add(a => a.OnConfirmAsync, async () =>
{
callbackCount++;
callbackStarted.TrySetResult();
await continueCallback.Task;
});
});

var firstClick = cut.InvokeAsync(() => cut.Find(".btn-danger").Click());
try
{
await callbackStarted.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken);
await cut.InvokeAsync(() => cut.Find(".btn-danger").Click());

Assert.Equal(1, callbackCount);
}
finally
{
continueCallback.TrySetResult();
}

await firstClick;
}

Comment on lines +10 to +118

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚪ Low · Unrequested unit tests were added

When the defect-fix task does not explicitly request new unit tests, SwalTest adds three unit tests even though no request to add tests was made, contrary to the repository’s default for defect fixes.

Remove the newly added unit tests unless adding tests is explicitly requested.

Prompt for AI agents
In `test/UnitTest/Components/SwalTest.cs` at lines 10-118:

**Unrequested unit tests were added**

When the defect-fix task does not explicitly request new unit tests, `SwalTest` adds three unit tests even though no request to add tests was made, contrary to the repository’s default for defect fixes.

Remove the newly added unit tests unless adding tests is explicitly requested.

From .github/copilot-instructions.md L10:

普通功能开发、缺陷修复等任务,默认不新增、修改或运行单元测试,除非用户明确要求

[Fact]
public void Show_Ok()
{
Expand Down
Loading