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(explorer-ui): formatAmount #2956

Merged
merged 3 commits into from
Jul 30, 2024
Merged

Conversation

bigboydiamonds
Copy link
Collaborator

@bigboydiamonds bigboydiamonds commented Jul 29, 2024

Summary by CodeRabbit

  • New Features
    • Enhanced amount formatting options for greater customization, including compact notation and rounding modes.
    • Improved display of very small amounts in the user interface for better clarity.
  • Bug Fixes
    • Resolved issues with formatting non-finite numbers and empty strings.
  • Refactor
    • Replaced reliance on external library with native locale-aware formatting for better performance and flexibility.

a7110bc: explorer-ui preview link
a609849: explorer-ui preview link
4e74e40: explorer-ui preview link

Copy link
Contributor

coderabbitai bot commented Jul 29, 2024

Walkthrough

The formatAmount function in the explorer-ui package has been significantly revamped to enhance customization, error handling, and formatting logic. With the introduction of the FormatOptions interface, developers can now more effectively tailor the formatting behavior for various scenarios. The function utilizes Intl.NumberFormat for improved locale-aware formatting, moving away from the previous reliance on the numeral library. Additional updates in the UI component ensure better display of amounts.

Changes

File Path Change Summary
packages/explorer-ui/utils/formatAmount.ts The formatAmount function has been redefined to accept an options parameter via a new FormatOptions interface. Enhanced error handling and new formatting logic have been implemented, with native Intl.NumberFormat replacing the numeral library.
packages/explorer-ui/components/misc/IconAndAmount.tsx A new displayAmount variable formats the amount for display, improving the representation of small values in the UI. Tooltip and rendering updates ensure consistency with the new formatting logic.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant Formatter
    User->>Formatter: Call formatAmount(amount, options)
    Formatter->>Formatter: Validate input
    Formatter->>Formatter: Check options for formatting
    Formatter->>Formatter: Format amount based on options
    Formatter-->>User: Return formatted amount
Loading

Poem

🐇 In the meadow, numbers play,
Format them bright, in a new way!
Options now dance, so spry and neat,
Locale-aware, a wondrous feat!
With each amount, a joyful cheer,
Rabbit’s delight, let’s make it clear! 🎉


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>.
    • 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 generate interesting stats about this repository and render them as a table.
    • @coderabbitai show all the console.log statements in this repository.
    • @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 as 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.

Additionally, you can add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.

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

@greptile-apps greptile-apps bot left a comment

Choose a reason for hiding this comment

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

PR Summary

The formatAmount.ts file has been refactored to enhance functionality and flexibility, introducing a FormatOptions interface and leveraging Intl.NumberFormat for improved localization and precision.

  • Introduced FormatOptions interface in packages/explorer-ui/utils/formatAmount.ts for customizable formatting.
  • Replaced numeral library with Intl.NumberFormat for better localization support.
  • Added options like fullAmount, standardDigits, useCompactNotation, compactDigits, minimumAmount, and roundingMode.
  • Ensure thorough testing of edge cases and new options to avoid unexpected behavior.

1 file(s) reviewed, no comment(s)
Edit PR Review Bot Settings

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: 8

Outside diff range, codebase verification and nitpick comments (2)
packages/explorer-ui/utils/formatAmount.ts (2)

29-34: Document default values for options.

The default values for the options are set within the function. Consider documenting these defaults in the FormatOptions interface or function documentation.

/**
 * Formats an amount based on the provided options.
 * 
 * @param {string} amount - The amount to format.
 * @param {FormatOptions} [options] - The formatting options.
 * @returns {string} The formatted amount.
 */
export const formatAmount = (
  amount: string,
  options?: FormatOptions
): string => {
  const fullAmount = options?.fullAmount ?? false
  const standardDigits = options?.standardDigits ?? 4
  const useCompactNotation = options?.useCompactNotation ?? true
  const compactDigits = options?.compactDigits ?? (useCompactNotation ? 2 : 0)
  const minimumAmount = options?.minimumAmount ?? 0.0001

45-47: Clarify minimum amount handling.

The function returns < minimumAmount for values below the minimum. Consider documenting this behavior.

if (floatAmount < minimumAmount) {
  return `< ${minimumAmount}`
}
Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 5dbb6e9 and 7b3ab43.

Files selected for processing (1)
  • packages/explorer-ui/utils/formatAmount.ts (1 hunks)
Additional comments not posted (5)
packages/explorer-ui/utils/formatAmount.ts (5)

37-39: Ensure consistent zero-value return.

The function returns '0.0' for zero values. Ensure consistency by returning '0.0' for empty strings as well.


57-61: Ensure fractional digits are configurable.

The fractional digits for values less than 1 are hardcoded to standardDigits. Ensure this is configurable.


63-67: Ensure significant digits are configurable.

The significant digits for values less than 1000 are hardcoded to standardDigits. Ensure this is configurable.


70-73: Ensure fractional digits are configurable.

The fractional digits for values less than 1,000,000 are hardcoded to 0. Ensure this is configurable.


76-80: Ensure compact notation is configurable.

The compact notation and fractional digits are configurable through compactDigits and useCompactNotation. This is well-implemented.

Comment on lines +1 to +8
interface FormatOptions {
fullAmount?: boolean
standardDigits?: number
useCompactNotation?: boolean
compactDigits?: number
minimumAmount?: number
roundingMode?: string
}
Copy link
Contributor

Choose a reason for hiding this comment

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

Ensure roundingMode is validated.

The roundingMode property is a string, but its valid values are not documented or enforced. Consider using a union type or an enum to restrict possible values.

interface FormatOptions {
  fullAmount?: boolean
  standardDigits?: number
  useCompactNotation?: boolean
  compactDigits?: number
  minimumAmount?: number
  roundingMode?: 'ceil' | 'floor' | 'round'
}

Comment on lines +10 to +13
export const formatAmount = (
amount: string,
options?: FormatOptions
): string => {
Copy link
Contributor

Choose a reason for hiding this comment

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

Consider validating the amount parameter.

The amount parameter is expected to be a string representing a number. Consider adding validation to ensure it is a valid numeric string before parsing.

export const formatAmount = (
  amount: string,
  options?: FormatOptions
): string => {
  if (isNaN(parseFloat(amount))) {
    throw new TypeError(`"${amount}" is not a valid numeric string`)
  }

Comment on lines +14 to +16
if (amount === '') {
return ''
}
Copy link
Contributor

Choose a reason for hiding this comment

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

Return '0.0' for empty string input.

Instead of returning an empty string for an empty amount, consider returning '0.0' for consistency with other zero-value returns.

if (amount === '') {
  return '0.0'
}

Comment on lines +18 to +19
const floatAmount = parseFloat(amount)

Copy link
Contributor

Choose a reason for hiding this comment

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

Avoid re-parsing the amount.

The floatAmount is parsed twice in the function. Consider parsing it once and reusing the value.

const floatAmount = parseFloat(amount)
if (!Number.isFinite(floatAmount)) {
  throw new TypeError(`"${amount}" is not a finite number`)
}

Comment on lines +24 to +27
} catch ({ name, message }) {
// console.error(name, message)
return amount
}
Copy link
Contributor

Choose a reason for hiding this comment

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

Remove try-catch block for finite check.

The try-catch block is unnecessary since the finite check can be done directly. Remove the try-catch block for simplicity.

if (!Number.isFinite(floatAmount)) {
  throw new TypeError(`"${amount}" is not a finite number`)
}

const compactDigits = options?.compactDigits ?? (useCompactNotation ? 2 : 0)
const minimumAmount = options?.minimumAmount ?? 0.0001

const locales = 'en-UK'
Copy link
Contributor

Choose a reason for hiding this comment

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

Consider making locales configurable.

The locales variable is hardcoded to 'en-UK'. Consider making it configurable through the FormatOptions interface.

const locales = options?.locales ?? 'en-UK'

Comment on lines +41 to +43
if (fullAmount) {
return Intl.NumberFormat(locales).format(floatAmount)
}
Copy link
Contributor

Choose a reason for hiding this comment

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

Consider adding locale options for full amount.

When fullAmount is true, the locale should still be configurable.

if (fullAmount) {
  return Intl.NumberFormat(locales).format(floatAmount)
}

Comment on lines +49 to +55
const absAmount = Math.abs(floatAmount)

if (absAmount < 0.0001) {
return Intl.NumberFormat(locales, {
maximumSignificantDigits: 1,
}).format(floatAmount)
}
Copy link
Contributor

Choose a reason for hiding this comment

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

Ensure significant digits are configurable.

The significant digits for values less than 0.0001 are hardcoded to 1. Consider making this configurable.

if (absAmount < 0.0001) {
  return Intl.NumberFormat(locales, {
    maximumSignificantDigits: options?.significantDigits ?? 1,
  }).format(floatAmount)
}

Copy link

cloudflare-workers-and-pages bot commented Jul 29, 2024

Deploying sanguine-fe with  Cloudflare Pages  Cloudflare Pages

Latest commit: 60a0491
Status: ✅  Deploy successful!
Preview URL: https://34339dc2.sanguine-fe.pages.dev
Branch Preview URL: https://explorer-format-amount.sanguine-fe.pages.dev

View logs

Copy link

codecov bot commented Jul 29, 2024

Codecov Report

All modified and coverable lines are covered by tests ✅

Project coverage is 25.70725%. Comparing base (d7c74f2) to head (60a0491).
Report is 1 commits behind head on master.

Additional details and impacted files
@@              Coverage Diff              @@
##              master       #2956   +/-   ##
=============================================
  Coverage   25.70725%   25.70725%           
=============================================
  Files            771         771           
  Lines          55603       55603           
  Branches          80          80           
=============================================
  Hits           14294       14294           
  Misses         39823       39823           
  Partials        1486        1486           
Flag Coverage Δ
packages 90.48563% <ø> (ø)

Flags with carried forward coverage won't be shown. Click here to find out more.

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

Copy link

codecov bot commented Jul 30, 2024

Bundle Report

Changes will increase total bundle size by 2.33MB ⬆️

Bundle name Size Change
sdk-router-@synapsecns/sdk-router-esm 252.32kB 0 bytes
explorer-ui-server-cjs 892.71kB 658 bytes ⬆️
sdk-router-@synapsecns/sdk-router-cjs 521.95kB 404.94kB ⬆️
explorer-ui-edge-server-array-push 83 bytes 0 bytes
explorer-ui-client-array-push 2.33MB 9.28kB ⬇️
widget-cjs-esm 273.3kB 273.3kB ⬆️
widget-esm-cjs 275.25kB 275.25kB ⬆️
synapse-interface-server-cjs 1.38MB 1.38MB ⬆️
synapse-interface-edge-server-array-push 83 bytes 83 bytes ⬆️

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: 0

Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 7b3ab43 and 60a0491.

Files selected for processing (1)
  • packages/explorer-ui/components/misc/IconAndAmount.tsx (2 hunks)
Additional comments not posted (2)
packages/explorer-ui/components/misc/IconAndAmount.tsx (2)

40-44: LGTM! But verify the correctness of formatAmount usage.

The return statement correctly uses displayAmount to enhance the user interface. Ensure that the formatAmount function handles all edge cases properly.


28-29: LGTM! But verify the correctness of formatAmount usage.

The displayAmount variable correctly formats the amount for display purposes. Ensure that the formatAmount function handles all edge cases properly.

@bigboydiamonds bigboydiamonds merged commit 8851088 into master Jul 30, 2024
29 checks passed
@bigboydiamonds bigboydiamonds deleted the explorer/format-amount branch July 30, 2024 10:25
Copy link

@greptile-apps greptile-apps bot left a comment

Choose a reason for hiding this comment

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

PR Summary

(updates since last review)

Enhanced amount formatting and refactoring for better performance and maintainability.

  • Refactor: packages/explorer-ui/components/BridgeTransaction/BridgeTransactionTable.tsx - Reordered imports and commented out properties in IconAndAmount for improved code organization.
  • Refactor: packages/explorer-ui/components/ChainChart/index.tsx - Code formatting and minor refactoring for better readability.
  • Refactor: packages/explorer-ui/components/Chart/index.tsx - Minor refactoring and improvements in code readability.
  • Refactor: packages/explorer-ui/components/ContainerCard.tsx - Converted to arrow functions and updated imports for consistency.
  • Refactor: packages/explorer-ui/components/CopyButtonIcon/index.tsx - Refactored to functional component with arrow functions and improved import statements.

109 file(s) reviewed, 1 comment(s)
Edit PR Review Bot Settings

@@ -35,11 +37,11 @@ export const IconAndAmount = ({
className={`${iconSize} min-w-[1rem] min-h-[1rem] inline rounded-full`}
/>
<div
data-tooltip-content={amount}
data-tooltip-content={displayAmount}
data-tooltip-id="amount"
className="flex-1 pl-1 mr-1 text-white"
Copy link

Choose a reason for hiding this comment

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

check: Ensure that the formatAmount function handles all edge cases, especially with large or small numbers.

Copy link

@greptile-apps greptile-apps bot left a comment

Choose a reason for hiding this comment

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

PR Summary

(updates since last review)

Enhanced amount formatting options and improved error handling for better user experience and performance.

  • New Feature: packages/explorer-ui/utils/formatAmount.ts - Added compact notation and rounding modes for amount formatting.
  • Bug Fix: packages/explorer-ui/utils/formatAmount.ts - Improved handling of non-finite numbers and empty strings.
  • Refactor: packages/explorer-ui/components/misc/IconAndAmount.tsx - Introduced displayAmount variable for clearer representation of small amounts.
  • Performance: Replaced external library with native locale-aware formatting in packages/explorer-ui/utils/formatAmount.ts for better performance.

1 file(s) reviewed, 2 comment(s)
Edit PR Review Bot Settings

@@ -25,6 +25,8 @@ export const IconAndAmount = ({
amount = formattedValue / (dec / 10 ** 6)
}

const displayAmount = amount ? formatAmount(amount) : '< 0.001'
Copy link

Choose a reason for hiding this comment

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

logic: Consider caching the result of formatAmount to avoid repeated calculations.

@@ -25,6 +25,8 @@ export const IconAndAmount = ({
amount = formattedValue / (dec / 10 ** 6)
}

const displayAmount = amount ? formatAmount(amount) : '< 0.001'
Copy link

Choose a reason for hiding this comment

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

style: Ensure formatAmount handles all edge cases, especially with large or small numbers.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants