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

fix: allow amount inputs to be empty #288

Merged
merged 5 commits into from
Feb 17, 2025
Merged

Conversation

hansl
Copy link
Contributor

@hansl hansl commented Feb 15, 2025

And refactor the two places found to have buggy amounts into this new component.

Fixes #281

Summary by CodeRabbit

  • New Features

    • Upgraded the amount entry field in token transfer forms to offer smoother, more intuitive numeric input with improved validation.
  • Style

    • Refined the visual presentation of the amount input to ensure a consistent and streamlined user experience across forms.

And refactor the two places found to have buggy amounts into
this new component.

Fixes liftedinit#281
@hansl hansl requested a review from chalabi2 February 15, 2025 00:01
Copy link
Contributor

coderabbitai bot commented Feb 15, 2025

Warning

Rate limit exceeded

@hansl has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 13 minutes and 4 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

Reviewing files that changed from the base of the PR and between 5f6ea8c and e72ad0e.

📒 Files selected for processing (1)
  • components/react/inputs/__tests__/AmountInput.test.tsx (1 hunks)

Walkthrough

This change introduces a new React component called AmountInput that encapsulates the logic for handling numerical inputs for token amounts. Both the IbcSendForm and SendForm components have been updated to replace their native <input> elements with AmountInput, integrating with Formik for form state management. Additionally, tests have been added for the new component and its behavior, and an export update makes the component available across the application.

Changes

File(s) Change Summary
components/bank/forms/(ibcSendForm.tsx, sendForm.tsx) Replaced standard HTML <input> for amount with the new AmountInput; updated event handling (using onValueChange) and removed placeholder text; adjusted styling while preserving form structure.
components/react/inputs/AmountInput.tsx Introduced new AmountInput component that validates positive decimals and manages value changes with an onValueChange callback; accepts additional props and renders an input with modified attributes.
components/react/inputs/__tests__/AmountInput.test.tsx Added a test suite using Bun and React Testing Library to verify correct rendering and functionality of AmountInput, including handling valid, empty, and invalid inputs.
components/react/inputs/index.ts Updated export statements to include the new AmountInput component for public accessibility.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant Form
    participant AmountInput

    User->>Form: Opens send form
    Form->>AmountInput: Passes current amount value & onValueChange callback
    User->>AmountInput: Enters or updates amount
    AmountInput->>Form: Calls onValueChange(newValue)
Loading

Possibly related PRs

Suggested labels

bug, render

Suggested reviewers

  • fmorency

Poem

Hoppin' through code on a bright spring day,
I found a new input to lead the way.
AmountInput brings clarity, oh so neat,
Guiding each number with a friendly beat.
With a twitch of my nose, I cheer in delight—
CodeRabbit Inc makes our code shine bright!


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 generate docstrings to generate docstrings for this PR. (Beta)
  • @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

codecov bot commented Feb 15, 2025

Codecov Report

All modified and coverable lines are covered by tests ✅

Project coverage is 53.61%. Comparing base (0f685be) to head (e72ad0e).
Report is 2 commits behind head on main.

Additional details and impacted files
@@            Coverage Diff             @@
##             main     #288      +/-   ##
==========================================
+ Coverage   53.57%   53.61%   +0.04%     
==========================================
  Files         209      210       +1     
  Lines       17246    17255       +9     
==========================================
+ Hits         9240     9252      +12     
+ Misses       8006     8003       -3     

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

Copy link
Contributor

@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: 1

🔭 Outside diff range comments (3)
components/bank/forms/sendForm.tsx (1)

75-104: 🛠️ Refactor suggestion

Consider updating validation schema for empty values.

The validation schema requires a value but the AmountInput component allows empty values. Consider updating the schema to align with the new component's behavior.

 amount: Yup.number()
-  .required('Amount is required')
+  .transform((value) => (value === '' ? null : value))
+  .nullable()
+  .required('Amount is required')
   .positive('Amount must be positive')
components/bank/forms/ibcSendForm.tsx (2)

129-132: ⚠️ Potential issue

Validation schema conflicts with PR objective.

The validation schema requires the amount to be non-empty and positive, which conflicts with the PR objective to "allow amount inputs to be empty".

Update the validation schema to allow empty amounts:

-    amount: Yup.number()
-      .required('Amount is required')
+    amount: Yup.string()
+      .test('valid-amount', 'Amount must be positive when provided', function(value) {
+        if (!value) return true;
+        const num = Number(value);
+        return !isNaN(num) && num > 0;
+      })

168-338: ⚠️ Potential issue

Verify empty amount handling in submission logic.

The form submission logic needs to be verified to handle empty amounts correctly. Currently, it attempts to convert the amount to base units without checking if it's empty.

Update the submission handler to handle empty amounts:

  const handleSend = async (values: {
    recipient: string;
-    amount: string;
+    amount: string | '';
    selectedToken: CombinedBalanceInfo;
    memo: string;
  }) => {
    setIsSending(true);
    try {
+     if (!values.amount) {
+       throw new Error('Amount is required for sending tokens');
+     }
      // Convert amount to base units
      const exponent = values.selectedToken.metadata?.denom_units[1]?.exponent ?? 6;
      const amountInBaseUnits = parseNumberToBigInt(values.amount, exponent).toString();
🧹 Nitpick comments (3)
components/react/inputs/AmountInput.tsx (2)

18-39: Consider adding input validation for maximum decimal places.

The current regex allows any number of decimal places. Consider adding validation for the maximum number of decimal places based on the token's metadata.

-const newValue = /^\d*\.?\d*$/.test(v) ? parseFloat(v) : NaN;
+const newValue = /^\d*\.?\d{0,6}$/.test(v) ? parseFloat(v) : NaN;
🧰 Tools
🪛 GitHub Check: codecov/patch

[warning] 27-28: components/react/inputs/AmountInput.tsx#L27-L28
Added lines #L27 - L28 were not covered by tests


[warning] 36-36: components/react/inputs/AmountInput.tsx#L36
Added line #L36 was not covered by tests


41-53: Consider extracting styles to a CSS module or Tailwind class.

The inline styles in className could be moved to a CSS module or a Tailwind class for better maintainability.

components/react/inputs/__tests__/AmountInput.test.tsx (1)

1-78: Add tests for additional edge cases.

While the current test suite covers basic functionality, consider adding tests for:

  1. Handling decimal places validation
  2. Single period input
  3. Invalid input when previous value is empty
  4. Maximum value constraints
test('handles single period input correctly', () => {
  const onValueChange = jest.fn();
  render(
    <TestForm>
      <AmountInput name="test" value="" onValueChange={onValueChange} />
    </TestForm>
  );
  const input = screen.getByPlaceholderText('0.00');
  fireEvent.change(input, { target: { value: '.' } });
  expect(onValueChange).toHaveBeenCalledWith('.');
});

test('handles invalid input when previous value is empty', () => {
  const onValueChange = jest.fn();
  render(
    <TestForm>
      <AmountInput name="test" value="" onValueChange={onValueChange} />
    </TestForm>
  );
  const input = screen.getByPlaceholderText('0.00');
  fireEvent.change(input, { target: { value: 'abc' } });
  expect(onValueChange).toHaveBeenCalledWith('');
});
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 0f685be and 5f6ea8c.

📒 Files selected for processing (5)
  • components/bank/forms/ibcSendForm.tsx (2 hunks)
  • components/bank/forms/sendForm.tsx (2 hunks)
  • components/react/inputs/AmountInput.tsx (1 hunks)
  • components/react/inputs/__tests__/AmountInput.test.tsx (1 hunks)
  • components/react/inputs/index.ts (1 hunks)
🧰 Additional context used
🪛 GitHub Check: codecov/patch
components/react/inputs/AmountInput.tsx

[warning] 27-28: components/react/inputs/AmountInput.tsx#L27-L28
Added lines #L27 - L28 were not covered by tests


[warning] 36-36: components/react/inputs/AmountInput.tsx#L36
Added line #L36 was not covered by tests

⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: build
🔇 Additional comments (5)
components/react/inputs/index.ts (1)

1-1: LGTM!

The export statement follows the established pattern and maintains consistency with other input component exports.

components/react/inputs/AmountInput.tsx (2)

3-6: LGTM!

The props interface is well-defined and follows React TypeScript best practices by extending HTMLInputElement attributes.


8-16: LGTM!

The component is well-documented with clear JSDoc comments explaining its purpose and parameters.

components/bank/forms/sendForm.tsx (1)

201-205: LGTM!

The AmountInput integration with Formik is clean and maintains the existing form functionality.

components/bank/forms/ibcSendForm.tsx (1)

525-529: LGTM! AmountInput integration looks good.

The AmountInput component is properly integrated with Formik's form management through the onValueChange prop.

components/react/inputs/AmountInput.tsx Show resolved Hide resolved
@fmorency fmorency merged commit 14e6f4f into liftedinit:main Feb 17, 2025
5 checks passed
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.

Can't clear the amount input field
2 participants