Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(BootstrapInput): add OnBlurAsync parameter #4521

Merged
merged 3 commits into from
Oct 24, 2024
Merged

feat(BootstrapInput): add OnBlurAsync parameter #4521

merged 3 commits into from
Oct 24, 2024

Conversation

ArgoZhang
Copy link
Collaborator

@ArgoZhang ArgoZhang commented Oct 24, 2024

add OnBlurAsync parameter

Summary of the changes (Less than 80 chars)

简单描述你更改了什么, 不超过80个字符;如果有关联 Issue 请在下方填写相关编号

Description

fixes #4520

Regression?

  • Yes
  • No

[If yes, specify the version the behavior has regressed from]

[是否影响老版本]

Risk

  • High
  • Medium
  • Low

[Justify the selection above]

Verification

  • Manual (required)
  • Automated

Packaging changes reviewed?

  • Yes
  • No
  • N/A

☑️ Self Check before Merge

⚠️ Please check all items below before review. ⚠️

  • Doc is updated/provided or not needed
  • Demo is updated/provided or not needed
  • Merge the latest code from the main branch

Summary by CodeRabbit

  • New Features

    • Added an OnBlurAsync callback parameter to the BootstrapInput component for handling focus loss events.
    • Implemented an @onblur event handler to enhance input interaction.
  • Bug Fixes

    • Introduced a test to ensure the OnBlurAsync callback is triggered correctly when the input loses focus.
  • Tests

    • Added a new test method to verify the blur event functionality of the BootstrapInput component.

@bb-auto bb-auto bot added the enhancement New feature or request label Oct 24, 2024
@bb-auto bb-auto bot added this to the v8.10.0 milestone Oct 24, 2024
Copy link

coderabbitai bot commented Oct 24, 2024

Warning

Rate limit exceeded

@ArgoZhang has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 14 minutes and 56 seconds before requesting another review.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

📥 Commits

Files that changed from the base of the PR and between 92290c6 and bc86132.

Walkthrough

The changes in this pull request introduce a new @onblur event handler to the <input> element in the BootstrapInput.razor file, enabling the component to respond to blur events. Additionally, an optional OnBlurAsync parameter is added to the BootstrapInput<TValue> class, allowing users to specify a callback for when the input loses focus. A corresponding method, OnBlur, is also implemented to invoke this callback. A unit test is included to verify the correct triggering of the blur event.

Changes

File Change Summary
src/BootstrapBlazor/Components/Input/BootstrapInput.razor Added @onblur="@OnBlur" event handler to <input> element.
src/BootstrapBlazor/Components/Input/BootstrapInput.razor.cs Added optional parameter public Func<TValue, Task>? OnBlurAsync { get; set; } and method protected virtual async Task OnBlur().
test/UnitTest/Components/InputTest.cs Added test method public async Task OnBlurAsync_Ok() to verify blur event handling.

Assessment against linked issues

Objective Addressed Explanation
Add OnBlurAsync parameter (Issue #4520)

Possibly related issues

Possibly related PRs

Poem

In fields of code, a rabbit hops,
With inputs bright, it never stops.
When focus fades, a call appears,
A blur event, to bring us cheers!
So let us code, and test with glee,
For every hop, brings joy to me! 🐇✨


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

🧹 Outside diff range and nitpick comments (3)
src/BootstrapBlazor/Components/Input/BootstrapInput.razor (1)

10-10: Consider adding error handling for the blur event.

The blur event handler implementation looks correct. However, since OnBlur is an async method that invokes a user-provided callback, consider adding error handling to gracefully handle any exceptions that might occur during the callback execution.

Consider wrapping the OnBlur implementation with try-catch:

protected virtual async Task OnBlur()
{
    try
    {
        if (OnBlurAsync != null)
        {
            await OnBlurAsync(Value);
        }
    }
    catch (Exception ex)
    {
        // Log the error or notify through your preferred error handling mechanism
        Logger.LogError(ex, "Error occurred during OnBlur callback");
    }
}
src/BootstrapBlazor/Components/Input/BootstrapInput.razor.cs (1)

25-30: Enhance the XML documentation for OnBlurAsync parameter.

While the basic documentation is present, it would be helpful to add more details about:

  • When exactly this callback is invoked
  • What the TValue parameter represents (the current input value)
  • Whether this is called before or after internal value validation

Consider expanding the documentation like this:

     /// <summary>
-    /// 获得/设置 失去焦点回调方法 默认 null
+    /// 获得/设置 失去焦点回调方法 默认 null
+    /// Gets or sets the callback that is invoked when the input loses focus.
+    /// The callback receives the current input value and is called after internal validation.
     /// </summary>
test/UnitTest/Components/InputTest.cs (1)

360-375: LGTM! Consider adding more test cases for comprehensive coverage.

The test correctly verifies the basic functionality of the OnBlurAsync callback. However, to ensure robust testing, consider adding the following test cases:

+    [Fact]
+    public async Task OnBlurAsync_NullCallback_Ok()
+    {
+        var cut = Context.RenderComponent<BootstrapInput<string>>();
+        var input = cut.Find("input");
+        await cut.InvokeAsync(() => { input.Blur(); });
+        // Should not throw
+    }
+
+    [Fact]
+    public async Task OnBlurAsync_VerifyValue_Ok()
+    {
+        var expectedValue = "test";
+        string? actualValue = null;
+        var cut = Context.RenderComponent<BootstrapInput<string>>(builder =>
+        {
+            builder.Add(a => a.Value, expectedValue);
+            builder.Add(a => a.OnBlurAsync, v =>
+            {
+                actualValue = v;
+                return Task.CompletedTask;
+            });
+        });
+        var input = cut.Find("input");
+        await cut.InvokeAsync(() => { input.Blur(); });
+        Assert.Equal(expectedValue, actualValue);
+    }
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between dcdf40d and 92290c6.

📒 Files selected for processing (3)
  • src/BootstrapBlazor/Components/Input/BootstrapInput.razor (1 hunks)
  • src/BootstrapBlazor/Components/Input/BootstrapInput.razor.cs (2 hunks)
  • test/UnitTest/Components/InputTest.cs (1 hunks)
🔇 Additional comments (3)
src/BootstrapBlazor/Components/Input/BootstrapInput.razor (1)

10-10: Verify async event handling implementation.

The async event handler looks properly integrated. Let's verify the implementation details to ensure proper async/await usage and event handling.

✅ Verification successful

Let me gather more information about the OnBlur implementation in the BootstrapInput component to verify the async event handling.


Based on the gathered information, I can now provide the final response:

Async event handling is properly implemented

The implementation shows a well-structured async event handling pattern:

  • The OnBlur method is correctly marked as virtual async Task
  • It properly checks for null before invoking the async delegate
  • The OnBlurAsync is defined as Func<TValue, Task>? which is the correct signature for async event handlers
  • The implementation is consistent with other components (AutoComplete, Textarea) as seen in the codebase
  • Unit tests verify the blur functionality across components
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the OnBlur implementation and related async handling

# Test 1: Check the base class implementation for any existing blur handling
echo "Checking base class implementation..."
ast-grep --pattern 'class BootstrapInputEventBase<$_> {
  $$$
  OnBlur($$$) {
    $$$
  }
  $$$
}'

# Test 2: Look for similar blur event implementations in other components
echo "Checking other components for blur handling patterns..."
rg -l "protected\s+virtual\s+async\s+Task\s+OnBlur"

# Test 3: Verify the test implementation
echo "Checking test implementation..."
rg -A 5 "OnBlurAsync_Ok"

Length of output: 2474


Script:

#!/bin/bash
# Check the actual implementation of OnBlur in BootstrapInput and related components

# Look for OnBlur implementation in BootstrapInput
echo "Checking BootstrapInput OnBlur implementation..."
rg -A 10 "OnBlur\(" "src/BootstrapBlazor/Components/Input/BootstrapInput.razor.cs"

# Check for OnBlurAsync property/method
echo "Checking OnBlurAsync definition..."
rg -A 5 "OnBlurAsync" "src/BootstrapBlazor/Components/Input/BootstrapInput.razor.cs"

# Check base class for any event handling patterns
echo "Checking base class event handling..."
ast-grep --pattern 'class BootstrapInputBase<$_> {
    $$$
    protected $$ OnBlur($$$) {
        $$$
    }
    $$$
}'

Length of output: 969

src/BootstrapBlazor/Components/Input/BootstrapInput.razor.cs (2)

60-65: Verify the interaction between validation and blur handling.

There might be a race condition between validation and the blur event. Ensure that OnBlurAsync is called with the validated value, not the raw input value.

Let's check the component's event ordering:

#!/bin/bash
# Search for validation-related code in the component
rg -l "OnValidate|ValidationMessage" --type cs

# Check if there are any existing tests covering this scenario
rg -l "OnBlurAsync.*Invalid" --type cs

56-66: 🛠️ Refactor suggestion

Consider improving the OnBlur method implementation.

The current implementation has several areas that could be enhanced:

  1. Exception handling for the callback
  2. Documentation for proper virtual method usage
  3. Support for cancellation in long-running operations

Consider this improved implementation:

     /// <summary>
-    /// OnBlur 方法
+    /// Called when the input loses focus.
+    /// Override this method to customize blur behavior while ensuring to call base.OnBlur().
     /// </summary>
+    /// <returns>A task representing the asynchronous operation.</returns>
+    /// <exception cref="Exception">Any exceptions from the OnBlurAsync callback are propagated.</exception>
     protected virtual async Task OnBlur()
     {
         if (OnBlurAsync != null)
         {
-            await OnBlurAsync(Value);
+            try 
+            {
+                using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(30));
+                await OnBlurAsync(Value).WaitAsync(cts.Token);
+            }
+            catch (OperationCanceledException)
+            {
+                // Log or handle timeout
+                throw;
+            }
         }
     }

This implementation:

  • Adds proper documentation for inheritors
  • Includes timeout protection for the callback
  • Makes exception handling explicit

Let's check if there are any existing derived classes that might be affected:

Copy link

codecov bot commented Oct 24, 2024

Codecov Report

All modified and coverable lines are covered by tests ✅

Project coverage is 100.00%. Comparing base (dcdf40d) to head (bc86132).
Report is 1 commits behind head on main.

Additional details and impacted files
@@            Coverage Diff            @@
##              main     #4521   +/-   ##
=========================================
  Coverage   100.00%   100.00%           
=========================================
  Files          631       631           
  Lines        27063     27070    +7     
  Branches      3926      3927    +1     
=========================================
+ Hits         27063     27070    +7     

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

@ArgoZhang ArgoZhang merged commit 0afbc41 into main Oct 24, 2024
7 checks passed
@ArgoZhang ArgoZhang deleted the feat-input branch October 24, 2024 04:10
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request
Projects
None yet
Development

Successfully merging this pull request may close these issues.

feat(BootstrapInput): add OnBlurAsync parameter
1 participant