oweme/apps/web/src/lib/format.ts
agent b3b57c156e Group page redesign and visual bug fixes
Layout, from the approved mock:
- Group header on Expenses/Balances: my balance as the headline number
  (Money component de-emphasises currency and decimals), total spent, and
  round quick actions Add / Payment / Settle up / Share. The floating +
  shows only once those scroll off screen.
- Expense rows on two lines (title | amount, payer | my part) with round
  icons tinted per category; sentence-case section headings.
- Balances: larger avatars, paired avatars on settle-up rows, tinted button.

Bugs found in a screenshot pass (phone 320/390, desktop 1280; dark, black,
light; English and Czech):
- A long title or member name widened the group page past the screen and
  phones zoomed out (grid tracks without minmax(0, ...)); same in Stats.
- Long titles were clipped mid-word with no ellipsis.
- Category emoji nearly invisible on its grey circle in the light theme.
- Stats period labels wrapped (en) or ran off screen (cs); shortened.
- Icons next to wrapping text were squashed (lock on Home/App settings).
- Dialogs opened with a focus ring on the close button after a tap.
- New expenses always defaulted to Food & drink; now the group's default
  category (settable in group settings), else Other.

e2e: the Balances check now targets the Settle up heading, which the new
quick action shares its text with.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HA82gVKYyo9BHLHPW4qr4x
2026-11-06 20:36:33 +00:00

116 lines
4.6 KiB
TypeScript

import { exponent, toDecimalString } from '@oweme/core';
import { settings } from './settings.svelte.ts';
const cache = new Map<string, Intl.NumberFormat>();
function formatter(currency: string, opts: { sign?: boolean }): Intl.NumberFormat {
const key = `${settings.locale}|${currency}|${opts.sign ? 1 : 0}`;
let f = cache.get(key);
if (!f) {
const e = exponent(currency);
try {
f = new Intl.NumberFormat(settings.locale, {
style: 'currency', currency, minimumFractionDigits: e, maximumFractionDigits: e,
signDisplay: opts.sign ? 'exceptZero' : 'auto',
});
} catch {
f = new Intl.NumberFormat(settings.locale, { minimumFractionDigits: e, maximumFractionDigits: e });
}
cache.set(key, f);
}
return f;
}
/** Format minor units as money in the current locale ("1 234,50 Kč"). */
export function money(minor: number, currency: string, opts: { sign?: boolean } = {}): string {
return formatter(currency, opts).format(minor / 10 ** exponent(currency));
}
/**
* The same text as money(), split so the whole number can be emphasised:
* `before` (sign, currency), `whole` ("1 234"), `frac` (",50"), `after` (" Kč").
*/
export function moneyParts(minor: number, currency: string, opts: { sign?: boolean } = {}) {
const out = { before: '', whole: '', frac: '', after: '' };
let seenNumber = false;
for (const p of formatter(currency, opts).formatToParts(minor / 10 ** exponent(currency))) {
if (p.type === 'integer' || p.type === 'group') {
out.whole += p.value;
seenNumber = true;
} else if (p.type === 'decimal' || p.type === 'fraction') out.frac += p.value;
else if (seenNumber) out.after += p.value;
else out.before += p.value;
}
return out;
}
/** Editable amount text for an input, in the user's decimal style. */
export function amountInput(minor: number, currency: string): string {
const s = toDecimalString(minor, currency);
return settings.lang === 'cs' ? s.replace('.', ',') : s;
}
export function fmtDate(d: string, style: 'short' | 'long' = 'short'): string {
const date = new Date(`${d}T12:00:00`);
return date.toLocaleDateString(settings.locale, style === 'long'
? { weekday: 'short', day: 'numeric', month: 'long', year: 'numeric' }
: { day: 'numeric', month: 'short', year: date.getFullYear() === new Date().getFullYear() ? undefined : 'numeric' });
}
export function fmtDateTime(iso: string): string {
return new Date(iso).toLocaleString(settings.locale, { day: 'numeric', month: 'short', hour: '2-digit', minute: '2-digit' });
}
export function fmtMonth(ym: string): string {
return new Date(`${ym}-15T12:00:00`).toLocaleDateString(settings.locale, { month: 'short', year: '2-digit' });
}
/** Today as YYYY-MM-DD in local time. */
export function today(): string {
const d = new Date();
return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`;
}
export function addDays(d: string, n: number): string {
const x = new Date(`${d}T12:00:00`);
x.setDate(x.getDate() + n);
return `${x.getFullYear()}-${String(x.getMonth() + 1).padStart(2, '0')}-${String(x.getDate()).padStart(2, '0')}`;
}
export function currencyName(code: string): string {
try {
return new Intl.DisplayNames(settings.locale, { type: 'currency' }).of(code) ?? code;
} catch {
return code;
}
}
/** A hue per category, used to tint its round icon background. */
export const CATEGORY_COLORS: Record<string, string> = {
food: '#ff8f6b', groceries: '#3ddc97', transport: '#ffc85a', accommodation: '#7aa7ff', entertainment: '#e879a6',
shopping: '#c084fc', utilities: '#facc15', rent: '#4fd1c5', travel: '#60a5fa', gifts: '#f472b6', health: '#f87171',
other: '#9ca3af', transfer: '#3ddc97',
};
export const CATEGORY_ICONS: Record<string, string> = {
food: '🍽️', groceries: '🛒', transport: '🚕', accommodation: '🏨', entertainment: '🎟️',
shopping: '🛍️', utilities: '💡', rent: '🏠', travel: '✈️', gifts: '🎁', health: '💊',
other: '🧾', transfer: '💸',
};
export const MEMBER_COLORS = ['#3DDC97', '#F2A65A', '#6CB4EE', '#E879A6', '#C9A227', '#9B8CF2', '#4FD1C5', '#F87171', '#A3E635', '#FB923C'];
export function download(filename: string, content: BlobPart, type: string) {
const url = URL.createObjectURL(new Blob([content], { type }));
const a = document.createElement('a');
a.href = url;
a.download = filename;
document.body.append(a);
a.click();
a.remove();
setTimeout(() => URL.revokeObjectURL(url), 10_000);
}
export function slug(s: string): string {
return s.normalize('NFKD').replace(/[̀-ͯ]/g, '').replace(/[^A-Za-z0-9]+/g, '-').replace(/^-|-$/g, '').toLowerCase() || 'group';
}