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

refactor: better TokenBalance #2068

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
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
2 changes: 1 addition & 1 deletion playground/nextjs-app-router/onchainkit/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@coinbase/onchainkit",
"version": "0.37.4",
"version": "0.37.5",
"type": "module",
"repository": "https://github.com/coinbase/onchainkit.git",
"license": "MIT",
Expand Down
16 changes: 6 additions & 10 deletions src/token/components/TokenBalance.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -88,7 +88,12 @@ describe('TokenBalance', () => {
expect(screen.getByText(`0.000 ETH ${subtitle}`)).toBeInTheDocument();
});

it('renders action button when showAction is true', () => {
it('does not render action button when onActionPress is not provided', () => {
render(<TokenBalance token={mockToken} />);
expect(screen.queryByTestId('ockTokenBalanceAction')).toBeNull();
});

it('renders action button when onActionPress is provided', () => {
const onActionPress = vi.fn();
render(
<TokenBalance
Expand All @@ -107,15 +112,6 @@ describe('TokenBalance', () => {
expect(onActionPress).toHaveBeenCalled();
});

it('handles keyboard events on action button', () => {
const onActionPress = vi.fn();
render(<TokenBalance token={mockToken} onActionPress={onActionPress} />);

const actionButton = screen.getByRole('button', { name: 'Use max' });
fireEvent.keyDown(actionButton);
expect(onActionPress).toHaveBeenCalled();
});

it('applies custom class names to token elements when no action is provided', () => {
const customClassNames = {
tokenName: 'custom-name',
Expand Down
132 changes: 79 additions & 53 deletions src/token/components/TokenBalance.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,33 +2,47 @@ import { formatFiatAmount } from '@/internal/utils/formatFiatAmount';
import { truncateDecimalPlaces } from '@/internal/utils/truncateDecimalPlaces';
import { border, cn, color, text } from '@/styles/theme';
import { TokenImage } from '@/token/components/TokenImage';
import { useCallback } from 'react';
import { useMemo } from 'react';
import { formatUnits } from 'viem';
import type { TokenBalanceProps } from '../types';

export function TokenBalance({
token,
onClick,
onActionPress,
actionText = 'Use max',
Copy link
Contributor

Choose a reason for hiding this comment

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

swap is just "max", should this match?

classNames,
'aria-label': ariaLabel,
...contentProps
}: TokenBalanceProps) {
if (onClick) {
return (
<button
type="button"
onClick={() => onClick(token)}
className={cn(
'flex w-full items-center justify-start gap-4 px-2 py-1',
classNames?.container,
<div className="relative">
<button
type="button"
aria-label={ariaLabel ?? `${token.name} token balance`}
onClick={() => onClick(token)}
className={cn(
'flex w-full items-center justify-start gap-4 px-2 py-1',
classNames?.container,
)}
data-testid="ockTokenBalanceButton"
>
<TokenBalanceContent
token={token}
classNames={classNames}
onActionPress={onActionPress}
{...contentProps}
/>
</button>
{onActionPress && (
<ActionButton
actionText={actionText}
onActionPress={onActionPress}
className={classNames?.action}
/>
)}
data-testid="ockTokenBalanceButton"
>
<TokenBalanceContent
token={token}
{...contentProps}
classNames={classNames}
/>
</button>
</div>
);
}

Expand All @@ -45,6 +59,13 @@ export function TokenBalance({
{...contentProps}
classNames={classNames}
/>
{onActionPress && (
<ActionButton
actionText={actionText}
onActionPress={onActionPress}
className={classNames?.action}
/>
)}
</div>
);
}
Expand All @@ -53,31 +74,26 @@ function TokenBalanceContent({
token,
subtitle,
showImage = true,
actionText = 'Use max',
onActionPress,
tokenSize = 40,
classNames,
}: TokenBalanceProps) {
const formattedFiatValue = formatFiatAmount({
amount: token.fiatBalance,
currency: 'USD',
});

const formattedCryptoValue = truncateDecimalPlaces(
formatUnits(BigInt(token.cryptoBalance), token.decimals),
3,
const formattedFiatValue = useMemo(
() =>
formatFiatAmount({
amount: token.fiatBalance,
currency: 'USD',
}),
[token.fiatBalance],
);

const handleActionPress = useCallback(
(
e:
| React.MouseEvent<HTMLDivElement, MouseEvent>
| React.KeyboardEvent<HTMLDivElement>,
) => {
e.stopPropagation();
onActionPress?.();
},
[onActionPress],
const formattedCryptoValue = useMemo(
() =>
truncateDecimalPlaces(
formatUnits(BigInt(token.cryptoBalance), token.decimals),
3,
),
[token.cryptoBalance, token.decimals],
);

return (
Expand Down Expand Up @@ -107,25 +123,7 @@ function TokenBalanceContent({
</span>
</div>
<div className="text-right">
{onActionPress ? (
<div
role="button"
data-testid="ockTokenBalanceAction"
aria-label={actionText}
onClick={handleActionPress}
onKeyDown={handleActionPress}
className={cn(
text.label2,
color.primary,
border.radius,
'ml-auto cursor-pointer p-0.5 font-bold',
'border border-transparent hover:border-[--ock-line-primary]',
classNames?.action,
)}
>
{actionText}
</div>
) : (
{!onActionPress && (
<span
className={cn(
text.label2,
Expand All @@ -141,3 +139,31 @@ function TokenBalanceContent({
</div>
);
}

function ActionButton({
Copy link
Contributor

Choose a reason for hiding this comment

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

Thoughts on putting ActionButton and or TokenBalanceContent in a separate file?

Copy link
Contributor

Choose a reason for hiding this comment

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

Seems like TokenBalanceContent should be extracted

actionText,
onActionPress,
className,
}: Pick<TokenBalanceProps, 'actionText' | 'onActionPress'> & {
className?: string;
}) {
return (
<button
type="button"
data-testid="ockTokenBalanceAction"
aria-label={actionText}
onClick={onActionPress}
className={cn(
text.label2,
color.primary,
border.radius,
'cursor-pointer p-0.5 font-bold',
'border border-transparent hover:border-[--ock-line-primary]',
'-translate-y-1/2 absolute top-1/2 right-2',
className,
)}
>
{actionText}
</button>
);
}
36 changes: 25 additions & 11 deletions src/token/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -130,12 +130,10 @@ export type TokenBalanceProps = {
token: PortfolioTokenWithFiatValue;
/** Subtitle to display next to the token name (eg. "available") */
subtitle?: string;
/** Show the token image (default: true) */
showImage?: boolean;
/** Click handler for the whole component*/
onClick?: (token: PortfolioTokenWithFiatValue) => void;
/** Size of the token image in px (default: 40) */
tokenSize?: number;
/** Optional aria label for the component */
'aria-label'?: string;
/** Optional additional CSS classes to apply to the component */
classNames?: {
container?: string;
Expand All @@ -146,13 +144,29 @@ export type TokenBalanceProps = {
};
} & (
| {
/** Hide the action button (default)*/
actionText?: never;
onActionPress?: never;
/** Show the token image (default: true) */
showImage?: true;
/** Size of the token image in px (default: 40) */
tokenSize?: number;
}
| {
/** Show an additional action button (eg. "Use max") */
actionText?: string;
onActionPress: () => void;
/** Hide the token image */
showImage: false;
Comment on lines +153 to +154
Copy link
Contributor

Choose a reason for hiding this comment

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

nit:

Suggested change
/** Hide the token image */
showImage: false;
/** Hide the token image (default: false) */
showImage: false;

/** Size of the token image in px (default: 40) */
tokenSize?: never;
}
);
) &
(
| {
/** Hide the action button (default)*/
onActionPress?: never;
Comment on lines +161 to +162
Copy link
Contributor

@cpcramer cpcramer Mar 6, 2025

Choose a reason for hiding this comment

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

What's the default here? The code comment looks unfinished

/** Optional action button text (default: "Use max") */
actionText?: never;
}
| {
/** Action handler for the action button */
onActionPress: () => void;
/** Optional action button text (default: "Use max") */
actionText?: string;
}
);