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

Add Precision parameter to BitNumberField (#10244) #10261

Merged

Conversation

Cyrus-Sushiant
Copy link
Member

@Cyrus-Sushiant Cyrus-Sushiant commented Mar 15, 2025

This closes #10244

Summary by CodeRabbit

  • New Features

    • Introduced a precision setting for numeric input fields that controls the number of decimal places displayed, ensuring values are consistently rounded.
    • Updated interactive demos to highlight and explain the new precision capability with clear, real-world examples.
  • Documentation

    • Revised demo sections to incorporate the precision feature, providing users with enhanced guidance on how number inputs behave with customized precision.

Copy link

coderabbitai bot commented Mar 15, 2025

Walkthrough

This change set introduces a new nullable Precision parameter across the number field component and its tests. The tests now pass a precision value (2) to verify number formatting and validation. The component logic is updated to store, set, and use precision for rounding via new methods (OnSetPrecision, Normalize, and NormalizeValue). Additionally, the demo pages now include a dedicated "Precision" section with updated examples and renumbered IDs, along with the introduction of a sample field to demonstrate precision behavior.

Changes

File(s) Change Summary
src/BlazorUI/Bit.BlazorUI.Tests/.../BitNumberFieldTests.cs Added a new parameter (Precision set to 2) in BitNumberFieldEnterKeyDownTest to control number field precision during testing.
src/BlazorUI/Bit.BlazorUI/Components/Inputs/NumberField/BitNumberField.razor.cs Introduced a new nullable Precision parameter with an associated private field _precision. Implemented OnSetPrecision, Normalize, and NormalizeValue to round values, updated value parsing, and managed event subscriptions.
src/BlazorUI/Demo/Client/.../BitNumberFieldDemo.razor, BitNumberFieldDemo.razor.cs, and BitNumberFieldDemo.razor.samples.cs Updated demo sections: renamed "HideInput" to "Precision" and renumbered subsequent sections. Added a new component parameter Precision, a new private field precisionInputValue, and adjusted sample example variable names and ordering to reflect the precision feature.

Sequence Diagram(s)

sequenceDiagram
    participant UI as User/Input
    participant NF as BitNumberField Component
    participant NP as Normalization Process
    participant EVT as OnValueChanged Event

    UI->>NF: Set value and Precision parameter
    NF->>NF: Invoke OnSetPrecision (store precision in _precision)
    NF->>NP: Call Normalize(value, Precision)
    NP-->>NF: Return rounded value
    NF->>NF: Execute NormalizeValue (update value if changed)
    NF->>EVT: Trigger OnValueChanged event
Loading

Poem

I'm a bunny hopping through the code,
Adding precision to lighten the load.
Numbers now round with a graceful twist,
Bugs retreat, peace can't be missed.
With every test and updated demo line,
I celebrate these changes—oh so fine!
🐇💻 Hop on to perfection, one digit at a time!

Tip

⚡🧪 Multi-step agentic review comment chat (experimental)
  • We're introducing multi-step agentic chat in review comments. This experimental feature enhances review discussions with the CodeRabbit agentic chat by enabling advanced interactions, including the ability to create pull requests directly from comments.
    - To enable this feature, set early_access to true under in the settings.
✨ Finishing Touches
  • 📝 Generate Docstrings

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ 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 generate docstrings to generate docstrings for this 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: 2

🧹 Nitpick comments (4)
src/BlazorUI/Bit.BlazorUI/Components/Inputs/NumberField/BitNumberField.razor.cs (4)

12-12: Consider adding XML documentation for private field

While private fields typically don't need documentation, this field is used across multiple methods and could benefit from a brief comment explaining its purpose and default value.

-    private int _precision;
+    /// <summary>
+    /// Stores the number of decimal places for rounding numeric values.
+    /// Default is 0 if not explicitly set.
+    /// </summary>
+    private int _precision;

648-669: Consider simplifying precision calculation logic

The regex-based precision calculation is a bit complex and might be hard to maintain. Consider simplifying it for better readability.

private int CalculatePrecision()
{
-   var step = Step ?? _step?.ToString() ?? "1";
-   var regex = new Regex(@"[1-9]([0]+$)|\.([0-9]*)");
-   if (regex.IsMatch(step) is false) return 0;
-
-   var matches = regex.Matches(step);
-   if (matches.Count == 0) return 0;
-
-   var groups = matches[0].Groups;
-   if (groups[1] != null && groups[1].Length != 0)
-   {
-       return -groups[1].Length;
-   }
-
-   if (groups[2] != null && groups[2].Length != 0)
-   {
-       return groups[2].Length;
-   }
-
-   return 0;
+   var step = Step ?? _step?.ToString() ?? "1";
+   
+   // Check for trailing zeros in whole numbers (e.g., 100, 1000)
+   if (step.EndsWith("0") && !step.Contains('.'))
+   {
+       int zeroCount = 0;
+       for (int i = step.Length - 1; i >= 0; i--)
+       {
+           if (step[i] == '0')
+               zeroCount++;
+           else
+               break;
+       }
+       return -zeroCount; // Negative precision for trailing zeros
+   }
+   
+   // Check for decimal places
+   int decimalPointIndex = step.IndexOf('.');
+   if (decimalPointIndex >= 0)
+   {
+       return step.Length - decimalPointIndex - 1;
+   }
+   
+   return 0;
}

671-680: Consider adding a check to avoid unnecessary state updates

The NormalizeValue method could potentially trigger unnecessary state updates. A direct comparison before updating Value would be more efficient.

The implementation already checks for equality and only updates if needed, which is good practice. This prevents unnecessary re-renders.


682-685: Consider using lambda for simple event handlers

For simple event handlers like this, consider using a lambda expression when subscribing to the event for better readability.

protected override async Task OnInitializedAsync()
{
-   OnValueChanged += HandleOnValueChanged;
+   OnValueChanged += (sender, args) => NormalizeValue();

    if (ValueHasBeenSet is false && DefaultValue is not null)
    {
        Value = DefaultValue;
    }

    NormalizeValue();

    await base.OnInitializedAsync();
}

-private void HandleOnValueChanged(object? sender, EventArgs args)
-{
-    NormalizeValue();
-}
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between cff26d6 and b0f3fc5.

📒 Files selected for processing (5)
  • src/BlazorUI/Bit.BlazorUI.Tests/Components/Inputs/NumberField/BitNumberFieldTests.cs (1 hunks)
  • src/BlazorUI/Bit.BlazorUI/Components/Inputs/NumberField/BitNumberField.razor.cs (5 hunks)
  • src/BlazorUI/Demo/Client/Bit.BlazorUI.Demo.Client.Core/Pages/Components/Inputs/NumberField/BitNumberFieldDemo.razor (5 hunks)
  • src/BlazorUI/Demo/Client/Bit.BlazorUI.Demo.Client.Core/Pages/Components/Inputs/NumberField/BitNumberFieldDemo.razor.cs (2 hunks)
  • src/BlazorUI/Demo/Client/Bit.BlazorUI.Demo.Client.Core/Pages/Components/Inputs/NumberField/BitNumberFieldDemo.razor.samples.cs (5 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: build and test
🔇 Additional comments (9)
src/BlazorUI/Bit.BlazorUI.Tests/Components/Inputs/NumberField/BitNumberFieldTests.cs (1)

644-644: Good addition of precision parameter in test

The addition of a precision parameter with a value of 2 aligns with the new functionality being added to the component. This ensures that the test properly validates the rounding behavior when the Enter key is pressed.

src/BlazorUI/Demo/Client/Bit.BlazorUI.Demo.Client.Core/Pages/Components/Inputs/NumberField/BitNumberFieldDemo.razor.cs (2)

232-237: Good parameter documentation

The parameter is well-documented with clear type, default value, and description that explains the purpose of the precision parameter.


494-494: Good test value for precision demonstration

Using 3.1415 (π) as the test value is appropriate to demonstrate precision rounding functionality, as it contains enough decimal places to clearly show the effect of rounding.

src/BlazorUI/Bit.BlazorUI/Components/Inputs/NumberField/BitNumberField.razor.cs (2)

216-221: Good parameter implementation with CallOnSet attribute

The parameter is correctly implemented with XML documentation and the CallOnSet attribute that triggers the OnSetPrecision method when the parameter is set.


693-693: Correctly unsubscribing from event

Good practice to unsubscribe from the event in the DisposeAsync method to prevent memory leaks.

src/BlazorUI/Demo/Client/Bit.BlazorUI.Demo.Client.Core/Pages/Components/Inputs/NumberField/BitNumberFieldDemo.razor (2)

145-151: Good demo section for the new precision feature

The demo section clearly demonstrates the precision functionality with a concise description and practical example. The label "Rounding to 2 Decimal Places" effectively communicates what the user should expect to see.


153-164: Properly updated section IDs

All section IDs have been correctly updated to maintain sequential order after the addition of the new Precision section. This ensures proper navigation and linking within the demo page.

Also applies to: 166-166, 181-181, 203-203, 234-234

src/BlazorUI/Demo/Client/Bit.BlazorUI.Demo.Client.Core/Pages/Components/Inputs/NumberField/BitNumberFieldDemo.razor.samples.cs (2)

94-97: Good addition of the precision parameter example

The new example clearly demonstrates the Precision parameter functionality with a value set to 2 decimal places, using π (3.1415) as a clear demonstration value that will show the rounding behavior.


99-99: Consistent renumbering of examples

The subsequent examples have been correctly renumbered to accommodate the new Example 8, maintaining consistency throughout the file.

Also applies to: 104-104, 107-107, 116-116, 121-121, 130-130, 140-140, 236-236

@msynk msynk merged commit 7f19b65 into bitfoundation:develop Mar 16, 2025
3 checks passed
@Cyrus-Sushiant Cyrus-Sushiant deleted the 10244-add-precision-bitnumberfield branch March 22, 2025 17:02
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Add Precision parameter to BitNumberField component
2 participants