feat(costs): split a custom expense by shares (#1165)

A stay shared by people who slept a different number of nights had to be
worked out by hand. The custom split now takes shares next to amounts and
percent: five nights against four split the total 5/9 to 4/9, cent-exact by
largest remainder. Only the amounts are saved, so server and MCP are
unchanged; the phone sheet gains the same unit switch, percent included.
This commit is contained in:
Maurice
2026-11-13 09:27:28 +01:00
parent 2934319722
commit 10d5f3ed46
36 changed files with 430 additions and 69 deletions
+18 -17
View File
@@ -23,7 +23,7 @@ import {
import { useCostsLedger } from './useCostsLedger'
import { useExpenseLinks } from './useExpenseLinks'
import { useSettlementForm } from './useSettlementForm'
import { usePercentSplit, type CustomSplitUnit } from './usePercentSplit'
import type { CustomSplitUnit } from './usePercentSplit'
import { useExpenseForm } from './useExpenseForm'
import { ReceiptPreviewModal } from './ReceiptPreviewModal'
import { useExpenseDeleteConfirm } from './useExpenseDeleteConfirm'
@@ -1132,14 +1132,14 @@ export function ExpenseModal({ tripId, base, people, me, editing, prefill, onClo
handleRemoveReceipt, handleToggleItemParticipant, handleUpdateItemName, handleUpdateItemPrice, isTicketMode,
multiPayer, name, nameOf, note, onPayerAmountChange, onTotalChange, participants, payerAmounts, payerId, payerIds,
payersOk, pendingReceiptFiles, placeholderShares, previewReceipts: modalPreviewReceipts, receipts, save, saving,
currencyChoices, setCat, setCurrency, setCustomAmounts, setDay, setName, setNote, setPayerId,
currencyChoices, setCat, setCurrency, setDay, setName, setNote, setPayerId, splitUnits: units,
setPreviewReceipts: setModalPreviewReceipts, setSplitMode, splitMode, splitShortfall, splitSum, sym, ticketInfo,
ticketItems, toggleParticipant, togglePayer, total, totalNum, tripCur, uploadingReceipt, valid,
} = useExpenseForm({ tripId, base, people, me, editing, prefill, onSaved })
// The custom split typed as percentages instead of amounts (#1709).
const pct = usePercentSplit({ total: totalNum, participants, customAmounts, setCustomAmounts, currency })
const inPercent = splitMode === 'custom' && pct.unit === 'percent'
// A custom split typed as percentages (#1709) or shares (#1165), each field showing its amount.
const inUnits = splitMode === 'custom' && units.unit !== 'amount'
const inPercent = inUnits && units.unit === 'percent'
const catInfo = catMeta(cat)
const money = (v: number) => formatMoney(v, currency, locale)
@@ -1164,7 +1164,6 @@ export function ExpenseModal({ tripId, base, people, me, editing, prefill, onClo
const personName = (p: TripMember, on: boolean) => (
<span className={`truncate font-medium ${on ? 'text-content' : 'text-content-faint'}`} style={fs(13.5, 'body')}>{nameOf(p)}</span>
)
const excludedNote = <span />
const modeHint = (text: string) => <p className="m-0 mb-2.5 text-content-faint" style={fs(12, 'body')}>{text}</p>
// Figures sit in badges, so an amount never reads as part of the sentence beside it.
const BADGE = 'inline-flex items-center gap-1.5 whitespace-nowrap rounded-full px-2.5 py-[3px] font-geist font-semibold tabular-nums'
@@ -1234,7 +1233,7 @@ export function ExpenseModal({ tripId, base, people, me, editing, prefill, onClo
onValueChange={v => onPayerAmountChange(p.id, v)}
className={AMOUNT_INPUT} style={fs(13.5, 'body')} />
</div>
) : excludedNote}
) : <span />}
</div>
)
})}
@@ -1266,14 +1265,15 @@ export function ExpenseModal({ tripId, base, people, me, editing, prefill, onClo
>
{splitMode === 'custom' ? (
<div className="mb-2.5 flex items-center justify-between gap-3">
<p className="m-0 min-w-0 text-content-faint" style={fs(12, 'body')}>{t(inPercent ? 'costs.splitHint.percent' : 'costs.splitHint.custom')}</p>
<p className="m-0 min-w-0 text-content-faint" style={fs(12, 'body')}>{t(inPercent ? 'costs.splitHint.percent' : inUnits ? 'costs.splitHint.shares' : 'costs.splitHint.custom')}</p>
<Segmented<CustomSplitUnit>
label={t('costs.splitUnit')}
value={pct.unit}
onChange={pct.setUnit}
value={units.unit}
onChange={units.setUnit}
options={[
{ value: 'amount', label: sym(currency) },
{ value: 'percent', label: '%' },
{ value: 'shares', label: t('costs.splitUnitShares') },
]}
/>
</div>
@@ -1361,15 +1361,16 @@ export function ExpenseModal({ tripId, base, people, me, editing, prefill, onClo
{personName(p, on)}
{p.is_guest && <GuestBadge size="xs" customTooltip />}
</button>
{!on ? excludedNote : splitMode === 'equally' ? (
{!on ? <span /> : splitMode === 'equally' ? (
<span className="text-end">{badge(money(equalShares[p.id] || 0))}</span>
) : inPercent ? (
) : inUnits ? (
<div className="flex flex-col items-end gap-0.5">
<div className={`${AMOUNT_BOX} w-full`}>
<input type="text" inputMode="decimal" aria-label={`${nameOf(p)} %`} placeholder={pct.placeholderPercent} value={pct.percents[p.id] ?? ''}
onChange={e => pct.onPercentChange(p.id, e.target.value)}
<input type="text" inputMode="decimal" placeholder={units.placeholder}
aria-label={inPercent ? `${nameOf(p)} %` : t('costs.splitSharesOf', { name: nameOf(p) })}
value={units.entries[p.id] ?? ''} onChange={e => units.onEntryChange(p.id, e.target.value)}
className={AMOUNT_INPUT} style={fs(13.5, 'body')} />
<span className="text-content-faint" style={fs(13, 'body')}>%</span>
{inPercent && <span className="text-content-faint" style={fs(13, 'body')}>%</span>}
</div>
{customAmounts[p.id] && <span className="font-geist tabular-nums text-content-faint" style={fs(10.5)}>{money(Number.parseFloat(customAmounts[p.id]) || 0)}</span>}
</div>
@@ -1393,8 +1394,8 @@ export function ExpenseModal({ tripId, base, people, me, editing, prefill, onClo
</>
) : customBalanced ? (
badge(<><Check size={12} strokeWidth={3} />{t('costs.splitBalanced')}</>, 'success')
) : inPercent ? (
badge(<><AlertCircle size={12} strokeWidth={2.4} />{t('costs.splitPercentOff', { sum: String(Math.round(pct.percentSum * 100) / 100) })}</>, 'danger')
) : inUnits ? (
badge(<><AlertCircle size={12} strokeWidth={2.4} />{inPercent ? t('costs.splitPercentOff', { sum: String(Math.round(units.percentSum * 100) / 100) }) : t('costs.splitSharesNone')}</>, 'danger')
) : (
badge(<><AlertCircle size={12} strokeWidth={2.4} />{t(splitShortfall > 0 ? 'costs.splitSumUnder' : 'costs.splitSumOver', {
sum: money(splitSum),
@@ -0,0 +1,72 @@
// FE-COSTS-EXPSPLIT-001 to FE-COSTS-EXPSPLIT-002
import userEvent from '@testing-library/user-event';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { buildBudgetItem, buildTrip, buildUser } from '../../../tests/helpers/factories';
import { render, screen, waitFor } from '../../../tests/helpers/render';
import { resetAllStores, seedStore } from '../../../tests/helpers/store';
import { useAuthStore } from '../../store/authStore';
import { useTripStore, type TripStoreState } from '../../store/tripStore';
import { ExpenseModal } from './CostsPanel';
const people = [
{ id: 1, username: 'alice', avatar_url: null },
{ id: 2, username: 'bob', avatar_url: null },
];
let addBudgetItem: ReturnType<typeof vi.fn>;
beforeEach(() => {
resetAllStores();
seedStore(useAuthStore, { user: buildUser({ id: 1 }), isAuthenticated: true });
addBudgetItem = vi.fn(async () => buildBudgetItem({ id: 9 }));
useTripStore.setState({
trip: buildTrip({ id: 1, currency: 'EUR' }),
addBudgetItem,
} as unknown as Partial<TripStoreState>);
});
async function startCustomSplit(total: string) {
const user = userEvent.setup();
render(
<ExpenseModal tripId={1} base="EUR" people={people} me={1} editing={null} onClose={vi.fn()} onSaved={vi.fn()} />
);
await user.type(screen.getByPlaceholderText('e.g. Dinner, souvenirs, gas…'), 'Apartment');
await user.type(screen.getAllByPlaceholderText('0,00')[0], total);
await user.click(screen.getByRole('button', { name: 'Custom' }));
await user.click(screen.getByRole('button', { name: 'Shares' }));
return user;
}
describe('ExpenseModal: a custom split by shares (#1165)', () => {
it('FE-COSTS-EXPSPLIT-001: five nights against four save the stay split 5/9 to 4/9', async () => {
const user = await startCustomSplit('390');
// Shares start even, one each, so the split balances before anything is typed.
expect(screen.getByText('Split matches total')).toBeInTheDocument();
await user.type(screen.getByRole('textbox', { name: 'Shares for You' }), '5');
await user.type(screen.getByRole('textbox', { name: 'Shares for bob' }), '4');
expect(screen.getByText('216,67 €')).toBeInTheDocument();
expect(screen.getByText('173,33 €')).toBeInTheDocument();
const submits = screen.getAllByRole('button', { name: 'Add expense' });
await user.click(submits[submits.length - 1]);
await waitFor(() => expect(addBudgetItem).toHaveBeenCalledTimes(1));
expect(addBudgetItem.mock.calls[0][1]).toMatchObject({
total_price: 390,
members: [
{ user_id: 1, amount: 216.67 },
{ user_id: 2, amount: 173.33 },
],
});
});
it('FE-COSTS-EXPSPLIT-002: nobody holding a share leaves the split open and the save blocked', async () => {
const user = await startCustomSplit('90');
await user.type(screen.getByRole('textbox', { name: 'Shares for You' }), '0');
await user.type(screen.getByRole('textbox', { name: 'Shares for bob' }), '0');
expect(screen.getByText('Give at least one person a share')).toBeInTheDocument();
const submits = screen.getAllByRole('button', { name: 'Add expense' });
expect(submits[submits.length - 1]).toBeDisabled();
});
});
@@ -29,6 +29,7 @@ import { catMeta } from './costsCategories';
import { currencyOptions } from './costsModel';
import { useExpenseFx } from './expenseFx';
import { saveWithReceipts } from './receiptUploads';
import { usePercentSplit } from './usePercentSplit';
export type ExpenseSplitMode = 'equally' | 'custom' | 'ticket';
@@ -38,7 +39,7 @@ let ticketItemSeq = 0;
/**
* The expense editor behind the desktop ExpenseModal and the phone MCostSheet:
* name, category, amount and currency, payers, the Equally / Custom / Ticket
* splits, the note and the receipts, what makes the entry valid, and the save
* splits (a custom one typed as amounts, percentages or shares), the note and the receipts, what makes the entry valid, and the save
* through the trip store. Both surfaces lay it out their own way.
*
* Where the two save differently today, the surface says which way:
@@ -182,6 +183,8 @@ export function useExpenseForm({
const totalNum = isTicketMode ? ticketInfo.total : Number.parseFloat(total) || 0;
const fx = preview(totalNum, currency);
// The custom split typed as percentages (#1709) or shares (#1165) instead of amounts.
const splitUnits = usePercentSplit({ total: totalNum, participants, customAmounts, setCustomAmounts, currency });
const splitSum = [...participants].reduce((sum, id) => sum + (Number.parseFloat(customAmounts[id]) || 0), 0);
const customBalanced = Math.round(splitSum * 100) === Math.round(totalNum * 100);
// How much is still to be handed out, read on the total's own side: on a refund
@@ -468,8 +471,8 @@ export function useExpenseForm({
handleRemoveItem,
handleToggleItemParticipant,
customAmounts,
setCustomAmounts,
handleCustomAmountChange,
splitUnits,
splitSum,
customBalanced,
splitShortfall,
@@ -1,8 +1,8 @@
// FE-BUDGET-PCT-001 to FE-BUDGET-PCT-006
// FE-BUDGET-PCT-001 to FE-BUDGET-PCT-009
import { describe, it, expect } from 'vitest'
import { useState } from 'react'
import { act, renderHook } from '@testing-library/react'
import { amountsToPercents, percentsToAmounts, percentString, usePercentSplit } from './usePercentSplit'
import { amountsToPercents, percentsToAmounts, percentString, sharesToAmounts, shareWeight, usePercentSplit } from './usePercentSplit'
describe('percent split maths (#1709)', () => {
it('FE-BUDGET-PCT-001: thirds add up to the total exactly', () => {
@@ -31,7 +31,29 @@ describe('percent split maths (#1709)', () => {
})
})
describe('usePercentSplit (#1709)', () => {
describe('share split maths (#1165)', () => {
it('FE-BUDGET-PCT-007: five nights against four split the stay 5/9 to 4/9, to the cent', () => {
expect(sharesToAmounts(390, { 1: '5', 2: '4' }, [1, 2], 'EUR')).toEqual({ 1: 216.67, 2: 173.33 })
const thirds = sharesToAmounts(100, { 1: '1', 2: '1', 3: '1' }, [1, 2, 3], 'EUR')
expect(Math.round(Object.values(thirds).reduce((s, v) => s + v, 0) * 100)).toBe(10000)
// A refund runs negative and still adds up; a won amount stays whole.
const refund = sharesToAmounts(-10, { 1: '2', 2: '1' }, [1, 2], 'EUR')
expect(Math.round((refund[1] + refund[2]) * 100)).toBe(-1000)
expect(sharesToAmounts(1000, { 1: '1', 2: '2' }, [1, 2], 'KRW')).toEqual({ 1: 333, 2: 667 })
})
it('FE-BUDGET-PCT-008: an empty field is one share, zero is none, and nobody holding one gives no amounts', () => {
expect(shareWeight(undefined)).toBe(1)
expect(shareWeight('')).toBe(1)
expect(shareWeight('0')).toBe(0)
expect(shareWeight('2.5')).toBe(2.5)
expect(sharesToAmounts(90, { 1: '2' }, [1, 2], 'EUR')).toEqual({ 1: 60, 2: 30 })
expect(sharesToAmounts(90, { 1: '0', 2: '3' }, [1, 2], 'EUR')).toEqual({ 1: 0, 2: 90 })
expect(sharesToAmounts(90, { 1: '0', 2: '0' }, [1, 2], 'EUR')).toEqual({})
})
})
describe('usePercentSplit (#1709, #1165)', () => {
function setup(total = 90) {
return renderHook(({ t }) => {
const [amounts, setAmounts] = useState<Record<number, string>>({ 1: '30', 2: '60' })
@@ -43,24 +65,38 @@ describe('usePercentSplit (#1709)', () => {
it('FE-BUDGET-PCT-005: switching to % carries the typed amounts over, and typing writes amounts back', () => {
const { result } = setup()
act(() => result.current.pct.setUnit('percent'))
expect(result.current.pct.percents).toEqual({ 1: '33.33', 2: '66.67' })
act(() => result.current.pct.onPercentChange(1, '50'))
act(() => result.current.pct.onPercentChange(2, '25'))
act(() => result.current.pct.onPercentChange(3, '25'))
expect(result.current.pct.entries).toEqual({ 1: '33.33', 2: '66.67' })
act(() => result.current.pct.onEntryChange(1, '50'))
act(() => result.current.pct.onEntryChange(2, '25'))
act(() => result.current.pct.onEntryChange(3, '25'))
expect(result.current.amounts).toEqual({ 1: '45.00', 2: '22.50', 3: '22.50' })
expect(result.current.pct.percentSum).toBe(100)
// Not a percentage: ignored.
act(() => result.current.pct.onPercentChange(3, 'abc'))
expect(result.current.pct.percents[3]).toBe('25')
act(() => result.current.pct.onEntryChange(3, 'abc'))
expect(result.current.pct.entries[3]).toBe('25')
})
it('FE-BUDGET-PCT-006: a changed total moves the amounts, the placeholder offers the rest', () => {
const { result, rerender } = setup()
act(() => result.current.pct.setUnit('percent'))
act(() => result.current.pct.onPercentChange(1, '50'))
act(() => result.current.pct.onPercentChange(2, ''))
expect(result.current.pct.placeholderPercent).toBe('25')
act(() => result.current.pct.onEntryChange(1, '50'))
act(() => result.current.pct.onEntryChange(2, ''))
expect(result.current.pct.placeholder).toBe('25')
rerender({ t: 200 })
expect(result.current.amounts).toEqual({ 1: '100.00' })
})
it('FE-BUDGET-PCT-009: shares start even, one each, and typed shares write the amounts back', () => {
const { result, rerender } = setup()
act(() => result.current.pct.setUnit('shares'))
expect(result.current.pct.entries).toEqual({})
expect(result.current.pct.placeholder).toBe('1')
expect(result.current.amounts).toEqual({ 1: '30.00', 2: '30.00', 3: '30.00' })
act(() => result.current.pct.onEntryChange(1, '5'))
act(() => result.current.pct.onEntryChange(2, '4'))
act(() => result.current.pct.onEntryChange(3, '0'))
expect(result.current.amounts).toEqual({ 1: '50.00', 2: '40.00', 3: '0.00' })
rerender({ t: 390 })
expect(result.current.amounts).toEqual({ 1: '216.67', 2: '173.33', 3: '0.00' })
})
})
+68 -33
View File
@@ -1,21 +1,39 @@
import { useEffect, useState } from 'react'
import { amountToInputString, currencyDecimals } from '../../utils/formatters'
export type CustomSplitUnit = 'amount' | 'percent'
export type CustomSplitUnit = 'amount' | 'percent' | 'shares'
const PERCENT_INPUT = /^\d{0,3}(\.\d{0,2})?$/
/** What a percent or a share field takes: up to 999, with two decimals at most. */
const UNIT_INPUT = /^\d{0,3}(\.\d{0,2})?$/
/** A percent as typed back into the field: at most two decimals, no trailing zeros. */
export function percentString(value: number): string {
return String(Math.round(value * 100) / 100)
}
/**
* Whole minor units for each id from its exact (fractional) part of `totalUnits`.
* The parts must add up to `totalUnits`; the units a plain rounding would lose go
* to the largest remainders, the same way splitEqualShares hands out an
* indivisible cent, so the result adds up to the total exactly.
*/
function largestRemainder(totalUnits: number, parts: { id: number; exact: number }[]): Record<number, number> {
const floors = parts.map(p => ({ id: p.id, units: Math.floor(p.exact), rest: p.exact - Math.floor(p.exact) }))
let left = totalUnits - floors.reduce((s, f) => s + f.units, 0)
// On a refund the total is negative, so the remainder runs the other way.
const order = [...floors].sort((a, b) => (left >= 0 ? b.rest - a.rest : a.rest - b.rest) || a.id - b.id)
for (const f of order) {
if (left === 0) break
f.units += Math.sign(left)
left -= Math.sign(left)
}
return Object.fromEntries(floors.map(f => [f.id, f.units]))
}
/**
* Amounts from percentages of `total` (#1709), in whole minor units. When the
* percentages add up to 100 the shares add up to the total exactly: the units a
* plain rounding would lose go to the largest remainders, the same way
* splitEqualShares hands out an indivisible cent. Ids without a percentage get
* no amount.
* percentages add up to 100 the shares add up to the total exactly (see
* largestRemainder). Ids without a percentage get no amount.
*/
export function percentsToAmounts(total: number, percents: Record<number, string>, ids: number[], currency: string): Record<number, number> {
const factor = 10 ** currencyDecimals(currency)
@@ -27,22 +45,35 @@ export function percentsToAmounts(total: number, percents: Record<number, string
const out: Record<number, number> = {}
const pctSum = entered.reduce((s, e) => s + e.pct, 0)
if (Math.abs(pctSum - 100) < 1e-9) {
const floors = raw.map(r => ({ id: r.id, units: Math.floor(r.exact), rest: r.exact - Math.floor(r.exact) }))
let left = totalUnits - floors.reduce((s, f) => s + f.units, 0)
// On a refund the total is negative, so the remainder runs the other way.
const order = [...floors].sort((a, b) => (left >= 0 ? b.rest - a.rest : a.rest - b.rest) || a.id - b.id)
for (const f of order) {
if (left === 0) break
f.units += Math.sign(left)
left -= Math.sign(left)
}
for (const f of floors) out[f.id] = f.units / factor
for (const [id, units] of Object.entries(largestRemainder(totalUnits, raw))) out[Number(id)] = units / factor
} else {
for (const r of raw) out[r.id] = Math.round(r.exact) / factor
}
return out
}
/** A person's number of shares; a field left empty counts as one, the equal split. */
export function shareWeight(raw: string | undefined): number {
const n = Number.parseFloat(raw ?? '')
return Number.isFinite(n) ? n : 1
}
/**
* Amounts from shares of `total` (#1165): five nights against four split a
* stay 5/9 to 4/9. The shares always add up to the whole, so the amounts add
* up to the total exactly (see largestRemainder). No amounts while nobody holds
* a share, which leaves the split unbalanced instead of dividing by zero.
*/
export function sharesToAmounts(total: number, shares: Record<number, string>, ids: number[], currency: string): Record<number, number> {
const factor = 10 ** currencyDecimals(currency)
const totalUnits = Math.round(total * factor)
const weights = ids.map(id => ({ id, weight: shareWeight(shares[id]) }))
const weightSum = weights.reduce((s, w) => s + w.weight, 0)
if (weightSum <= 0) return {}
const units = largestRemainder(totalUnits, weights.map(w => ({ id: w.id, exact: (totalUnits * w.weight) / weightSum })))
return Object.fromEntries(Object.entries(units).map(([id, u]) => [Number(id), u / factor]))
}
/** The percentages the typed amounts make of `total`; an empty or unparsable amount stays empty. */
export function amountsToPercents(total: number, amounts: Record<number, string>, ids: number[]): Record<number, string> {
const out: Record<number, string> = {}
@@ -65,46 +96,50 @@ interface Args {
}
/**
* The "%" side of a custom split (#1709). Percentages are only an input aid:
* every change is turned straight into the amounts the custom split already
* keeps, so what is saved, validated and settled is unchanged.
* The "%" (#1709) and "shares" (#1165) sides of a custom split. Both are only
* an input aid: every change is turned straight into the amounts the custom
* split already keeps, so what is saved, validated and settled is unchanged.
* `entries` holds what the person typed in the current unit, percentages or
* shares; the amount unit types the amounts themselves.
*/
export function usePercentSplit({ total, participants, customAmounts, setCustomAmounts, currency, initialUnit = 'amount' }: Args) {
const [unit, setUnitState] = useState<CustomSplitUnit>(initialUnit)
const [percents, setPercents] = useState<Record<number, string>>({})
const [entries, setEntries] = useState<Record<number, string>>({})
const ids = [...participants]
// Percentages carry the typed amounts over; shares start even, one each.
const setUnit = (next: CustomSplitUnit) => {
if (next === unit) return
if (next === 'percent') setPercents(amountsToPercents(total, customAmounts, ids))
setEntries(next === 'percent' ? amountsToPercents(total, customAmounts, ids) : {})
setUnitState(next)
}
const onPercentChange = (id: number, raw: string) => {
const onEntryChange = (id: number, raw: string) => {
const val = raw.replace(',', '.')
if (val !== '' && !PERCENT_INPUT.test(val)) return
setPercents(prev => {
if (val !== '' && !UNIT_INPUT.test(val)) return
setEntries(prev => {
const next = { ...prev, [id]: val }
if (val === '') delete next[id]
return next
})
}
// The amounts follow the percentages: on every percentage typed, and when the
// total changes or somebody leaves the split.
// The amounts follow the entries: on every one typed, and when the total
// changes or somebody leaves the split.
const idsKey = ids.join(',')
useEffect(() => {
if (unit !== 'percent') return
if (unit === 'amount') return
const idList = idsKey ? idsKey.split(',').map(Number) : []
const amounts = percentsToAmounts(total, percents, idList, currency)
const amounts = (unit === 'percent' ? percentsToAmounts : sharesToAmounts)(total, entries, idList, currency)
const strings: Record<number, string> = {}
for (const [id, amount] of Object.entries(amounts)) strings[Number(id)] = amountToInputString(amount, currency)
setCustomAmounts(strings)
}, [unit, percents, total, idsKey, currency, setCustomAmounts])
}, [unit, entries, total, idsKey, currency, setCustomAmounts])
const percentSum = ids.reduce((s, id) => s + (Number.parseFloat(percents[id]) || 0), 0)
const empty = ids.filter(id => !percents[id])
const placeholderPercent = empty.length > 0 ? percentString(Math.max(0, 100 - percentSum) / empty.length) : '0'
const percentSum = ids.reduce((s, id) => s + (Number.parseFloat(entries[id]) || 0), 0)
const empty = ids.filter(id => !entries[id])
// The percent left over spread across the empty fields; a share field reads one.
const placeholder = unit === 'shares' ? '1' : empty.length > 0 ? percentString(Math.max(0, 100 - percentSum) / empty.length) : '0'
return { unit, setUnit, percents, onPercentChange, percentSum, placeholderPercent }
return { unit, setUnit, entries, onEntryChange, percentSum, placeholder }
}