Skip to content
Merged
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
142 changes: 89 additions & 53 deletions apps/app/src/components/collaboration/CollaborativeBudgetField.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,23 +4,25 @@ import { useCollaborativeFragment } from '@/hooks/useCollaborativeFragment';
import type { BudgetData } from '@op/common/client';
import { Button } from '@op/ui/Button';
import { NumberField } from '@op/ui/NumberField';
import { useEffect, useRef, useState } from 'react';
import { useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react';

import { useTranslations } from '@/lib/i18n';

import { useCollaborativeDoc } from './CollaborativeDocContext';

const DEFAULT_CURRENCY = 'USD';
const DEFAULT_CURRENCY_SYMBOL = '$';

const CURRENCY_SYMBOLS: Record<string, string> = {
USD: DEFAULT_CURRENCY_SYMBOL,
};

/** Formats a number as a locale-aware currency string (e.g. 5000 → "$5,000") */
function formatBudgetDisplay(amount: number, currencySymbol: string): string {
return `${currencySymbol}${amount.toLocaleString()}`;
}
const getCurrencySymbol = (currency: string) =>
(0)
.toLocaleString(undefined, {
style: 'currency',
currency,
currencyDisplay: 'narrowSymbol',
minimumFractionDigits: 0,
maximumFractionDigits: 0,
})
.replace(/\d/g, '')
.trim();

interface CollaborativeBudgetFieldProps {
maxAmount?: number;
Expand All @@ -33,8 +35,9 @@ interface CollaborativeBudgetFieldProps {
* Stores `MoneyAmount` (`{ amount, currency }`) as a JSON string in the shared doc
* for future multi-currency support.
*
* Displays as a pill when a value exists, switching to an inline
* NumberField on click for editing.
* Displays as a pill when a value exists or empty, switching to an inline
* NumberField on click for editing. The pill width matches the input width
* to prevent layout shifts.
*/
export function CollaborativeBudgetField({
maxAmount,
Expand Down Expand Up @@ -69,11 +72,40 @@ export function CollaborativeBudgetField({

const [isEditing, setIsEditing] = useState(false);
const budgetAmount = budget?.amount ?? null;
const currencySymbol =
CURRENCY_SYMBOLS[budget?.currency ?? DEFAULT_CURRENCY] ??
DEFAULT_CURRENCY_SYMBOL;
const currency = budget?.currency ?? DEFAULT_CURRENCY;
const currencySymbol = useMemo(() => getCurrencySymbol(currency), [currency]);

const placeholderText = maxAmount
? t('Max {amount}', { amount: maxAmount.toLocaleString() })
: t('Enter amount');

// Size the input to its placeholder text instead of the default size=20
useLayoutEffect(() => {
if (budgetInputRef.current) {
budgetInputRef.current.size = placeholderText.length;
}
}, [placeholderText]);

// Use the larger of the input and button natural widths so both match
const buttonRef = useRef<HTMLButtonElement>(null);
const [sharedWidth, setSharedWidth] = useState(0);

useEffect(() => {
if (isEditing) {
return;
}
const frame = requestAnimationFrame(() => {
const group = budgetInputRef.current?.closest('[role="group"]');
const inputW = group instanceof HTMLElement ? group.offsetWidth : 0;
const buttonW = buttonRef.current?.scrollWidth ?? 0;
const width = Math.max(inputW, buttonW);
if (width > 0) {
setSharedWidth(width);
}
});
return () => cancelAnimationFrame(frame);
}, [isEditing]);

// Auto-focus when switching to edit mode
useEffect(() => {
if (isEditing && budgetInputRef.current) {
budgetInputRef.current.focus();
Expand All @@ -85,14 +117,14 @@ export function CollaborativeBudgetField({
setBudget(null);
} else {
setBudget({
currency: budget?.currency ?? DEFAULT_CURRENCY,
currency,
amount: value,
});
}
};

useEffect(() => {
const emitted: BudgetData | null = budget;
const emitted = budgetText ? (JSON.parse(budgetText) as BudgetData) : null;
const key = emitted ? `${emitted.amount}:${emitted.currency}` : null;

if (lastEmittedRef.current === key) {
Expand All @@ -101,7 +133,7 @@ export function CollaborativeBudgetField({

lastEmittedRef.current = key ?? undefined;
onChangeRef.current?.(emitted);
}, [budget]);
}, [budgetText]);

const handleStartEditing = () => {
setIsEditing(true);
Expand All @@ -111,40 +143,44 @@ export function CollaborativeBudgetField({
setIsEditing(false);
};

// No value and not editing → "Add budget" pill
if (budgetAmount === null && !isEditing) {
return (
<Button variant="pill" color="pill" onPress={handleStartEditing}>
{t('Add budget')}
</Button>
);
}

// Has a value and not editing → display as pill
if (budgetAmount !== null && !isEditing) {
return (
<Button variant="pill" color="pill" onPress={handleStartEditing}>
{formatBudgetDisplay(budgetAmount, currencySymbol)}
</Button>
);
}

// Editing mode → inline NumberField
return (
<NumberField
ref={budgetInputRef}
value={budgetAmount}
onChange={handleChange}
prefixText={currencySymbol}
inputProps={{
placeholder: maxAmount
? t('Max {amount}', {
amount: maxAmount.toLocaleString(),
})
: t('Enter amount'),
onBlur: handleBlur,
}}
fieldClassName="w-auto"
/>
<>
<div
className={isEditing ? '' : 'pointer-events-none absolute opacity-0'}
style={sharedWidth > 0 ? { minWidth: sharedWidth } : undefined}
>
<NumberField
ref={budgetInputRef}
value={budgetAmount}
onChange={handleChange}
prefixText={currencySymbol}
inputProps={{
placeholder: placeholderText,
onBlur: handleBlur,
className: 'shadow-none',
}}
fieldClassName="rounded-md"
/>
</div>
{!isEditing && (
<Button
ref={buttonRef}
variant="pill"
color="pill"
onPress={handleStartEditing}
className="justify-start text-left"
style={sharedWidth > 0 ? { minWidth: sharedWidth } : undefined}
>
{budgetAmount !== null
? budgetAmount.toLocaleString(undefined, {
style: 'currency',
currency,
currencyDisplay: 'narrowSymbol',
maximumFractionDigits: 0,
})
: t('Add budget')}
</Button>
)}
</>
);
}
Loading