fix(ui): refine trip forms and planner empty states

This commit is contained in:
Maurice
2026-12-02 22:03:08 +01:00
parent c6a50695d8
commit f10435b42b
19 changed files with 286 additions and 183 deletions
@@ -17,6 +17,7 @@ import { amountToInputString, currencyDecimals } from '../../utils/formatters'
import { localIsoDate } from '../../utils/localDate'
import type { ExpensePrefill } from './CostsPanel'
import type { BudgetItem } from '../../types'
import type { CostsSettlement } from './costsModel'
// The split and receipt fields guard their own precision on every keystroke, so the
// guard has to follow the currency: a three-decimal one (KWD, BHD, …) seeds three
@@ -329,3 +330,24 @@ export function expenseEditorFor(
if (receipt) return { key: 'receipt', editing: null, prefill: receipt, close: closeReceipt }
return null
}
/** Expenses and settle-up payments grouped newest day first in the Costs ledger. */
export function groupLedgerByDay(expenses: readonly BudgetItem[], payments: readonly CostsSettlement[], locale: string, noDate: string) {
const entries = [
...expenses.map(e => ({ kind: 'expense' as const, date: e.expense_date || '', e })),
...payments.map(s => ({ kind: 'payment' as const, date: settlementDate(s), s })),
].sort((a, b) => b.date.localeCompare(a.date))
const groups = new Map<string, typeof entries>()
for (const entry of entries) {
let label = noDate
if (entry.date) {
try {
label = new Date(entry.date + 'T00:00:00Z').toLocaleDateString(locale, { weekday: 'short', day: 'numeric', month: 'short', timeZone: 'UTC' })
} catch { label = entry.date }
}
const group = groups.get(label)
if (group) group.push(entry)
else groups.set(label, [entry])
}
return [...groups].map(([day, entries]) => ({ day, entries }))
}
@@ -944,13 +944,13 @@ describe('CostsPanel — overview', () => {
expect(labels).toEqual(['Food & drink', 'Transport'])
expect(within(breakdown).getByText('90 €')).toBeInTheDocument()
expect(within(breakdown).getByText('30 €')).toBeInTheDocument()
})
});
it('FE-W5COSTS-006: an empty trip shows the empty ledger and the empty breakdown', async () => {
it('FE-W5COSTS-006: an empty trip shows the empty ledger without a total or category breakdown', async () => {
mount([])
expect(await screen.findByText('No expenses yet. Add your first one.')).toBeInTheDocument()
expect(screen.getByText('No expenses yet.')).toBeInTheDocument()
expect(await screen.findByText('No expenses yet. Add your first one.')).toBeInTheDocument();
expect(screen.queryByRole('region', { name: 'Total trip spend' })).toBeNull();
expect(screen.queryByRole('region', { name: 'By category' })).toBeNull();
expect(screen.getByText("Everyone's square")).toBeInTheDocument()
})
+20 -40
View File
@@ -13,7 +13,7 @@ import { CustomDatePicker } from '../shared/CustomDateTimePicker'
import { useReceiptScan } from './useReceiptScan'
import { ReceiptScanModal } from './ReceiptScanModal'
import { SPLIT_COLORS } from './BudgetPanel.constants'
import { finalBudgetFor, finalBudgetSources, formerParticipantRows, NOTE_MAX, paidByUser, readUserNote, settlementDate } from './CostsPanel.helpers'
import { groupLedgerByDay, finalBudgetFor, finalBudgetSources, formerParticipantRows, NOTE_MAX, paidByUser, readUserNote } from './CostsPanel.helpers'
import { COST_CATEGORY_LIST, catMeta } from './costsCategories'
import {
baseTotal as baseTotalOf, booked as bookedAmount, isUnfinished as isUnfinishedModel, lineOf as lineOfModel, memberShareOf,
@@ -52,12 +52,6 @@ interface CostsPanelProps {
tripMembers?: TripMember[]
}
// One row in the unified Costs ledger — either an expense or a settle-up payment,
// carrying the date used to group it by day.
type LedgerEntry =
| { kind: 'expense'; date: string; e: BudgetItem }
| { kind: 'payment'; date: string; s: Settlement }
const round2 = (n: number) => Math.round(n * 100) / 100
const FIELD_H = 40 // shared height for the amount / currency / day row in the modal
const COSTS_VIEW_KEY = 'trek:costs-view'
@@ -66,6 +60,7 @@ export default function CostsPanel({ tripId, tripMembers = [] }: CostsPanelProps
const { trip, budgetItems, deleteBudgetItem, loadBudgetItems, addBudgetItem, updateBudgetItem } = useTripStore()
const can = useCanDo()
const canEdit = can('budget_edit', trip)
const hasExpenses = budgetItems.length > 0
const receiptScan = useReceiptScan(tripId, canEdit)
const toast = useToast()
const { t, locale } = useTranslation()
@@ -143,27 +138,9 @@ export default function CostsPanel({ tripId, tripMembers = [] }: CostsPanelProps
// Nobody paid, so nobody owes (#2225).
const myShareOf = (e: BudgetItem) => settledShareOf(e, ctx)
// ── day grouping ─────────────────────────────────────────────────────────
const dayGroups = useMemo(() => {
const entries: LedgerEntry[] = [
...filtered.map(e => ({ kind: 'expense' as const, date: e.expense_date || '', e })),
...filteredSettlements.map(s => ({ kind: 'payment' as const, date: settlementDate(s), s })),
]
const labelOf = (date: string) => {
if (!date) return t('costs.noDate')
try { return new Date(date + 'T00:00:00Z').toLocaleDateString(locale, { weekday: 'short', day: 'numeric', month: 'short', timeZone: 'UTC' }) } catch { return date }
}
// Newest day first; within a day, expenses before payments (insertion order).
const sorted = entries.slice().sort((a, b) => (b.date || '').localeCompare(a.date || ''))
const groups: { day: string; entries: LedgerEntry[] }[] = []
for (const en of sorted) {
const day = labelOf(en.date)
let g = groups.find(x => x.day === day)
if (!g) { g = { day, entries: [] }; groups.push(g) }
g.entries.push(en)
}
return groups
}, [filtered, filteredSettlements, locale, t])
const noDate = t('costs.noDate')
const dayGroups = useMemo(() => groupLedgerByDay(filtered, filteredSettlements, locale, noDate), [filtered, filteredSettlements, locale, noDate])
const emptyLedger = !hasExpenses && dayGroups.length === 0
// ── filter dropdown options (category + single day) ──────────────────────
const categoryOptions = useMemo(() => [
@@ -285,8 +262,8 @@ export default function CostsPanel({ tripId, tripMembers = [] }: CostsPanelProps
}} />
{/* ── Summary cards; with nothing to split (#2689) the total stands alone ── */}
{!splitting ? <div style={{ marginBottom: 36 }}>{totalCard}</div> : (
<div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, minmax(0, 1fr))', gap: 16, marginBottom: 36 }} className="costs-summary">
{!splitting ? (hasExpenses && <div style={{ marginBottom: 36 }}>{totalCard}</div>) : (
<div style={{ display: 'grid', gridTemplateColumns: hasExpenses ? 'repeat(4, minmax(0, 1fr))' : 'repeat(3, minmax(0, 1fr))', gap: 16, marginBottom: 36 }} className="costs-summary">
<SummaryCard label={t('costs.youOwe')} sub={t('costs.youOweSub')} amount={balancesKnown ? totals.owe : null} currency={base} locale={locale}
icon={<ArrowDown size={18} />} tone="owe" failed={settlementError}
foot={totals.owe > 0.01
@@ -302,7 +279,7 @@ export default function CostsPanel({ tripId, tripMembers = [] }: CostsPanelProps
foot={totals.outstandingCount > 0
? <span><b>{totals.outstandingCount}</b> {t('costs.outstandingItems', { count: totals.outstandingCount })}</span>
: settledUp && <span className="text-content-faint">{t('costs.allSettled')}</span>} />
{totalCard}
{hasExpenses && totalCard}
</div>)}
{/* ── Main grid ── */}
@@ -310,10 +287,10 @@ export default function CostsPanel({ tripId, tripMembers = [] }: CostsPanelProps
sidebar the last, so it lines up with the total-spend card. */}
<div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, minmax(0, 1fr))', columnGap: 16, rowGap: 32, alignItems: 'start' }} className="costs-grid">
{/* expenses */}
<div className="costs-main" style={{ gridColumn: 'span 3', minWidth: 0 }}>
<div className="costs-main" style={{ gridColumn: emptyLedger ? '1 / -1' : 'span 3', minWidth: 0 }}>
{dayBanner}
{view === 'table' ? (
{emptyLedger ? <EmptyState scene="costs" title={t('costs.emptyText')} /> : view === 'table' && hasExpenses ? (
filtered.length === 0 && budgetItems.length > 0 ? (
<div className="text-content-faint" style={{ textAlign: 'center', padding: '60px 20px' }}>{t('costs.noMatch')}</div>
) : (
@@ -379,14 +356,14 @@ export default function CostsPanel({ tripId, tripMembers = [] }: CostsPanelProps
</>}
{/* by category; the table view sums up four ways instead */}
{view === 'table' ? (
{hasExpenses && (view === 'table' ? (
<CostsTableSummary items={filtered} baseTotal={baseTotal} toBase={booked} fmt={v => fmt(v)} personName={personName} splitting={splitting} />
) : (
<section aria-label={t('costs.byCategory')} className={SIDE_CARD}>
{sideHead(t('costs.byCategory'))}
<div className="px-4 py-4">{categoryBars}</div>
</section>
)}
))}
<CostsModeCard trip={trip} memberCount={people.length} canEdit={canEdit} className={SIDE_CARD} />
</div>
</div>
@@ -493,7 +470,7 @@ export default function CostsPanel({ tripId, tripMembers = [] }: CostsPanelProps
return (
<div style={{ display: 'flex', flexDirection: 'column', gap: 16, paddingTop: 8 }}>
{/* Total card */}
<section style={{ background: 'linear-gradient(135deg,#1f2937,#111827)', color: '#fff', borderRadius: 22, padding: '20px 20px 16px', boxShadow: '0 8px 24px -8px rgba(0,0,0,0.28)' }}>
{hasExpenses ? <section style={{ background: 'linear-gradient(135deg,#1f2937,#111827)', color: '#fff', borderRadius: 22, padding: '20px 20px 16px', boxShadow: '0 8px 24px -8px rgba(0,0,0,0.28)' }}>
<div style={{ fontSize: 'calc(11.5px * var(--fs-scale-caption, 1))', textTransform: 'uppercase', letterSpacing: '0.12em', color: 'rgba(255,255,255,0.6)', fontWeight: 600 }}>{t('costs.totalSpend')}</div>
<div style={{ fontSize: 'calc(44px * var(--fs-scale-title, 1))', fontWeight: 700, letterSpacing: '-0.04em', lineHeight: 1, marginTop: 8, display: 'flex', alignItems: 'baseline' }}>{bigMoney(totals.totalSpend, 24, 'rgba(255,255,255,0.6)')}</div>
{splitting && <div style={{ display: 'flex', gap: 18, marginTop: 12, fontSize: 'calc(12px * var(--fs-scale-body, 1))', color: 'rgba(255,255,255,0.6)', flexWrap: 'wrap' }}>
@@ -512,7 +489,10 @@ export default function CostsPanel({ tripId, tripMembers = [] }: CostsPanelProps
<ScanLine size={16} /> {t('costs.scan.button')}
</button>
)}
</section>
</section> : <div className="flex flex-wrap justify-end gap-2">
{receiptScan.offered && <DialogButton onClick={receiptScan.open}>{t('costs.scan.button')}</DialogButton>}
{canEdit && <DialogButton variant="primary" onClick={() => { setEditing(null); setModalOpen(true) }}>{t('costs.addExpense')}</DialogButton>}
</div>}
{/* Owe / Owed, outstanding and settling up: only with something to split (#2689) */}
{splitting && <>
@@ -582,7 +562,7 @@ export default function CostsPanel({ tripId, tripMembers = [] }: CostsPanelProps
<CustomSelect value={dayFilter} onChange={v => setDayFilter(String(v))} options={dayOptions} size="sm" searchable style={{ flex: 1, minWidth: 0 }} />
</div>
{dayBanner}
{dayGroups.length === 0
{emptyLedger ? <EmptyState scene="costs" title={t('costs.emptyText')} /> : dayGroups.length === 0
? <div className="text-content-faint" style={{ textAlign: 'center', padding: '36px 16px', fontSize: 'calc(13px * var(--fs-scale-body, 1))' }}>{search ? t('costs.noMatch') : t('costs.emptyText')}</div>
: dayGroups.map(g => {
const dtot = g.entries.reduce((a, en) => en.kind === 'expense' ? a + baseTotal(en.e) : a, 0)
@@ -611,10 +591,10 @@ export default function CostsPanel({ tripId, tripMembers = [] }: CostsPanelProps
</>}
{/* By category */}
<div className={cardCls} style={{ borderRadius: 18, padding: 16 }}>
{hasExpenses && <div className={cardCls} style={{ borderRadius: 18, padding: 16 }}>
<div className={labelCls} style={{ marginBottom: 14 }}>{t('costs.byCategory')}</div>
{categoryBars}
</div>
</div>}
<CostsModeCard trip={trip} memberCount={people.length} canEdit={canEdit} className={`${cardCls} rounded-[18px]`} />
</div>
)
@@ -153,4 +153,9 @@ describe('ListsRail', () => {
renderRail({ onSelectLibrary: vi.fn(), libraryCount: null });
expect(screen.getByRole('button', { name: /All places/ })).toHaveTextContent(/^All places$/);
});
it('hides All places when the library is known to be empty', () => {
renderRail({ onSelectLibrary: vi.fn(), libraryCount: 0 });
expect(screen.queryByRole('button', { name: /All places/ })).not.toBeInTheDocument();
});
});
@@ -75,7 +75,7 @@ export default function ListsRail(props: ListsRailProps): React.ReactElement {
</Tooltip>
</div>
{onSelectLibrary && (
{onSelectLibrary && libraryCount !== 0 && (
<div className="col-row">
<button type="button" onClick={onSelectLibrary} className={`col-row-btn${libraryActive ? ' on' : ''}`} aria-current={libraryActive ? 'page' : undefined}>
<span className="ico tile"><Globe2 size={15} /></span>
@@ -83,11 +83,11 @@ function DayRowTourPills({ tour, stageKey }: { tour: TourListItem; stageKey?: st
}
// Description line, one line like every stop's.
function SublineDescription({ text, isTourPlace }: { text: string; isTourPlace: boolean }) {
function SublineDescription({ text, isTourPlace, fade }: { text: string; isTourPlace: boolean; fade: boolean }) {
return (
<div
data-testid={isTourPlace ? 'trip-plan-tour-description' : undefined}
className="collab-note-md min-w-0 flex-1 text-content-faint"
className={`collab-note-md min-w-0 flex-1 text-content-faint${fade ? 'trek-fade-end' : ''}`}
style={{
...fs(10.5),
overflow: 'hidden',
@@ -115,13 +115,15 @@ export function DayPlanPlaceSubline({
}: DayPlanPlaceSublineProps) {
const { locale } = useTranslation();
const dayRowTour = tourTimes?.tour;
const wrapTourFacts = !!dayRowTour || hasPlannedTimes(tourTimes);
const description = place.description || place.address || cat?.name;
if (!(dayRowTour || place.place_time || hasPlannedTimes(tourTimes) || description)) return null;
if (!(wrapTourFacts || place.place_time || description)) return null;
return (
// The description stays on one line and gives way first. The pills wrap rather
// than run out of the row: a tour carries a time, its duration and its distance,
// and in the narrow day column the last of them used to be cut off unseen.
<div className="trek-fade-end mt-0.5 flex min-w-0 flex-wrap items-center gap-x-1.5 gap-y-1 overflow-hidden">
// At a regular stop, the time stays readable and only the description gives way.
// A tour can wrap its time, duration and distance in the narrow day column.
<div
className={`mt-0.5 flex min-w-0 items-center gap-x-1.5 overflow-hidden ${wrapTourFacts ? 'trek-fade-end flex-wrap gap-y-1' : 'flex-nowrap'}`}
>
{place.place_time && dayRowTour && (
// TIME-02: a tour's end, typed or worked out from its start and its time.
<TimePill quiet>
@@ -143,7 +145,7 @@ export function DayPlanPlaceSubline({
tourTimes && <PlannedTourPills tourTimes={tourTimes} />
)}
{dayRowTour && <WalkProgressPill tour={dayRowTour} assignmentId={assignmentId} />}
{description && <SublineDescription text={description} isTourPlace={isTourPlace} />}
{description && <SublineDescription text={description} isTourPlace={isTourPlace} fade={!wrapTourFacts} />}
</div>
);
}
@@ -142,12 +142,12 @@ describe('TripFormModal', () => {
const trip = buildTrip({ id: 1, title: 'Iceland Adventure' });
render(<TripFormModal {...defaultProps} trip={trip} />);
expect(screen.getByDisplayValue('Iceland Adventure')).toBeInTheDocument();
expect(screen.getByRole('textbox', { name: 'Title' }).closest('header')).toBeInTheDocument();
});
it('FE-COMP-TRIPFORM-012: shows Title label', () => {
it('FE-COMP-TRIPFORM-012: puts the only trip title field in the dialog header', () => {
render(<TripFormModal {...defaultProps} />);
// dashboard.tripTitle = "Title"
expect(screen.getByText('Title')).toBeInTheDocument();
expect(screen.getByRole('textbox', { name: 'Title' }).closest('header')).toBeInTheDocument();
});
it('FE-COMP-TRIPFORM-013: shows Cover Image section', () => {
+37 -21
View File
@@ -513,28 +513,30 @@ export default function TripFormModal({
<div className={`${panelCls} flex-1`}>
<CardHead
icon={<Type size={16} strokeWidth={2} />}
title={t('trip.form.aboutTitle')}
hint={t('trip.form.aboutHint')}
title={embedded ? t('trip.form.aboutTitle') : t('dashboard.tripDescription')}
hint={embedded ? t('trip.form.aboutHint') : undefined}
/>
<div>
<label className={labelCls}>
{t('dashboard.tripTitle')} <span className="text-danger">*</span>
</label>
<input
data-initial-focus={(!embedded && canEditTrip) || undefined}
type="text"
value={formData.title}
onChange={(e) => canEditTrip && update('title', e.target.value)}
required
readOnly={!canEditTrip}
placeholder={t('dashboard.tripTitlePlaceholder')}
className={inputCls}
/>
</div>
{embedded && (
<div>
<label className={labelCls}>
{t('dashboard.tripTitle')} <span className="text-danger">*</span>
</label>
<input
type="text"
value={formData.title}
onChange={(e) => canEditTrip && update('title', e.target.value)}
required
readOnly={!canEditTrip}
placeholder={t('dashboard.tripTitlePlaceholder')}
className={inputCls}
/>
</div>
)}
<div>
<label className={labelCls}>{t('dashboard.tripDescription')}</label>
{embedded && <label className={labelCls}>{t('dashboard.tripDescription')}</label>}
<textarea
aria-label={t('dashboard.tripDescription')}
value={formData.description}
onChange={(e) => canEditTrip && update('description', e.target.value)}
readOnly={!canEditTrip}
@@ -831,9 +833,23 @@ export default function TripFormModal({
}
: onClose
}
eyebrow={pendingReview ? undefined : isEditing ? t('dashboard.editTrip') : undefined}
title={
pendingReview ? reviewTitle : isEditing ? trip?.title || t('dashboard.editTrip') : t('dashboard.createTrip')
eyebrow={pendingReview ? undefined : t(isEditing ? 'dashboard.editTrip' : 'dashboard.createTrip')}
title={pendingReview ? reviewTitle : undefined}
titleInput={
pendingReview
? undefined
: {
value: formData.title,
label: t('dashboard.tripTitle'),
placeholder: t('dashboard.tripTitlePlaceholder'),
readOnly: !canEditTrip,
required: true,
onChange: (value) => canEditTrip && update('title', value),
onKeyDown: (event) => {
if (canEditTrip && !busy && event.key === 'Enter' && !event.nativeEvent.isComposing)
void handleSubmit(event);
},
}
}
/>
}
+3 -1
View File
@@ -199,7 +199,8 @@ export interface HeaderTitleInput {
/** The field's accessible name, e.g. the old "Title *" label. */
label: string
placeholder?: string
autoFocus?: boolean
autoFocus?: boolean;
readOnly?: boolean;
required?: boolean
maxLength?: number
onKeyDown?: (e: ReactKeyboardEvent<HTMLInputElement>) => void
@@ -253,6 +254,7 @@ export function DialogHeader(p: DialogHeaderProps) {
aria-label={f.label}
placeholder={f.placeholder}
ref={f.autoFocus ? focusRevealedEditor : undefined}
readOnly={f.readOnly}
required={f.required}
maxLength={f.maxLength}
className="-mx-2 block w-[calc(100%+16px)] rounded-[10px] border-0 bg-transparent px-2 py-0.5 font-bold tracking-[-0.01em] text-content outline-none placeholder:font-semibold placeholder:text-content-faint hover:bg-surface-card focus:bg-surface-card focus:shadow-sm dark:bg-transparent dark:hover:bg-surface-card dark:focus:bg-surface-card"