Compare commits

..

2 commits

Author SHA1 Message Date
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
c12fd64f09 Core: per-group default category (group.updated defaultCategory)
SPEC listed defaultCategory on group.updated but nothing implemented it.
Replay accepts one of CATEGORIES and ignores the whole event otherwise,
validating before any field is applied.

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
20 changed files with 293 additions and 66 deletions

18
SPEC.md
View file

@ -262,8 +262,8 @@ the minimum in practice, and is easy to reason about.
- Create group: name, base currency (default by locale: CZK for Czech, EUR
otherwise), icon/emoji, initial members.
- Share: copy link, native share sheet, QR code.
- Settings: rename, members, "who am I", remove from device, export, delete
group (see 8.3).
- Settings: rename, members, "who am I", default category, remove from
device, export, delete group (see 8.3).
- **Base currency is locked once the group has any expense or transfer.** It
can be changed freely while the group is empty; afterwards the setting is
read-only with a short explanation. Clients enforce this during replay too:
@ -288,6 +288,12 @@ Fixed v1 set with icons: food & drink, groceries, transport, accommodation,
entertainment, shopping, utilities, rent, travel, gifts, health, other.
Transfers have their own implicit category.
Each group has a **default category** (`group.updated` → `defaultCategory`,
one of the set above; absent means "other") that new expenses start with.
Replay ignores a `group.updated` whose `defaultCategory` isn't in the set,
without applying any other field of that event. Each category has an icon
colour (`CATEGORY_COLORS` in `apps/web/src/lib/format.ts`).
### 7.4 Recurring expenses
- A template (expense object + rule: weekly / monthly / yearly, interval,
@ -435,8 +441,12 @@ which group ids exist.
1. **Home**: groups saved on this device, each showing my balance. "New
group", "Open link/scan QR".
2. **Group**: tabs: Expenses · Balances (settle up) · Stats · Activity.
Floating "+" button for a new expense.
2. **Group**: on Expenses and Balances, a header with my balance as the
headline number ("You're owed / You owe / settled up"; the group total if
"who am I" isn't set), the group's total spent, and round quick actions:
Add · Payment · Settle up · Share. Tabs: Expenses · Balances (settle up) ·
Stats · Activity. A floating "+" appears only once the quick actions have
scrolled off screen.
3. **Expense editor** (sheet on mobile, dialog on desktop).
4. **Expense detail**: photo, split breakdown, comments, history.
5. **Group settings**.

View file

@ -70,6 +70,7 @@
}
* { box-sizing: border-box; }
svg { flex-shrink: 0; } /* icons beside wrapping text must not be squashed */
html { -webkit-text-size-adjust: 100%; }
body {
margin: 0;
@ -82,7 +83,8 @@ body {
h1, h2, h3 { line-height: 1.2; margin: 0; }
h1 { font-size: 1.35rem; }
h2 { font-size: 1.05rem; }
h3 { font-size: 0.85rem; text-transform: uppercase; letter-spacing: 0.06em; color: var(--muted); font-weight: 600; }
h3 { font-size: 1.05rem; font-weight: 700; letter-spacing: -0.01em; }
h3.day { font-size: 0.85rem; font-weight: 600; letter-spacing: 0; color: var(--muted); padding-left: 4px; }
a { color: var(--accent); }
p { margin: 0; }
.muted { color: var(--muted); }
@ -145,6 +147,8 @@ button, .btn {
.btn.primary:hover { filter: brightness(1.08); }
.btn.danger { color: var(--danger); border-color: color-mix(in srgb, var(--danger) 40%, var(--border)); }
.btn.ghost { background: transparent; border-color: transparent; }
.btn.tint { background: color-mix(in srgb, var(--accent) 15%, var(--surface)); border-color: transparent; color: var(--accent); }
.btn.tint:hover { background: color-mix(in srgb, var(--accent) 24%, var(--surface)); }
.btn.small { min-height: 34px; padding: 0 14px; font-size: 0.9rem; }
.btn.block { width: 100%; }
.btn:disabled { opacity: 0.5; cursor: not-allowed; }
@ -166,9 +170,13 @@ input:focus-visible, select:focus-visible, textarea:focus-visible, .btn:focus-vi
input[type='checkbox'] { width: 22px; height: 22px; min-height: 0; accent-color: var(--accent); flex-shrink: 0; }
input[type='date'] { min-width: 0; }
.seg { display: flex; background: var(--surface); border: 1px solid var(--line); border-radius: 999px; padding: 3px; gap: 3px; }
.seg {
display: flex; background: var(--surface); border: 1px solid var(--line); border-radius: 999px; padding: 3px; gap: 3px;
overflow-x: auto; scrollbar-width: none; /* very narrow screens scroll rather than wrap */
}
.seg::-webkit-scrollbar { display: none; }
.seg button {
flex: 1; min-height: 38px; border: 0; border-radius: 999px; background: transparent; color: var(--muted); font-weight: 600; font-size: 0.9rem; padding: 0 8px;
flex: 1 0 auto; white-space: nowrap; min-height: 38px; border: 0; border-radius: 999px; background: transparent; color: var(--muted); font-weight: 600; font-size: 0.9rem; padding: 0 8px;
}
.seg button[aria-pressed='true'] { background: var(--surface-2); color: var(--text); }
@ -223,6 +231,7 @@ dialog.sheet {
padding: 0; border: 0; color: var(--text); background: var(--bg);
width: 100%; max-width: 100%; height: 100%; max-height: 100%; margin: 0;
}
dialog.sheet:focus { outline: none; }
dialog.sheet::backdrop { background: rgb(0 0 0 / 0.5); }
@media (min-width: 760px) {
dialog.sheet {
@ -254,3 +263,10 @@ dialog.sheet::backdrop { background: rgb(0 0 0 / 0.5); }
.fab { bottom: 32px; right: max(32px, calc(50% - 560px + 32px)); }
.page { padding-bottom: 48px; }
}
/* round category icon tinted with its category colour (set --cat inline) */
.cat-icon { background: color-mix(in srgb, var(--cat, var(--muted)) 24%, var(--surface-2)); }
/* money with the whole number emphasised (see moneyParts) */
.money .cur, .money .frac { color: var(--muted); font-size: 0.82em; font-weight: inherit; }
.pos .money .cur, .pos .money .frac, .neg .money .cur, .neg .money .frac { color: inherit; opacity: 0.8; }

View file

@ -42,14 +42,14 @@
<div class="list">
{#each members as { m, i, bal } (m.id)}
<div class="item">
<Avatar member={m} index={i} size={32} />
<Avatar member={m} index={i} size={40} />
<span class="grow">
<span class="title" style:display="block">{m.name}{m.id === session.me ? ` (${t('you')})` : ''}</span>
<span class="bar" aria-hidden="true">
<span class={bal >= 0 ? 'fill pos-fill' : 'fill neg-fill'} style:width="{(Math.abs(bal) / maxAbs) * 100}%"></span>
</span>
</span>
<span class="end num {bal > 0 ? 'pos' : bal < 0 ? 'neg' : 'muted'}">
<span class="end num {bal > 0 ? 'pos' : bal < 0 ? 'neg' : 'muted'}" style:font-weight="650">
{bal === 0 ? t('settled') : (bal > 0 ? '+' : '−') + conv(Math.abs(bal))}
</span>
</div>
@ -62,12 +62,18 @@
{:else}
<div class="list">
{#each transfers as tr}
{@const from = session.state.members.findIndex((m) => m.id === tr.from)}
{@const to = session.state.members.findIndex((m) => m.id === tr.to)}
<div class="item">
<span class="pair" aria-hidden="true">
<Avatar member={session.state.members[from]} index={from} size={34} />
<Avatar member={session.state.members[to]} index={to} size={34} />
</span>
<span class="grow">
<span class="title" style:display="block">{session.memberName(tr.from)} → {session.memberName(tr.to)}</span>
<span class="num" style:font-weight="700">{conv(tr.amount)}</span>
<span class="num sub" style:display="block">{conv(tr.amount)}</span>
</span>
<button class="btn small" onclick={() => record(tr.from, tr.to, tr.amount)}>{t('mark_paid')}</button>
<button class="btn small tint" onclick={() => record(tr.from, tr.to, tr.amount)}>{t('mark_paid')}</button>
</div>
{/each}
</div>
@ -85,7 +91,10 @@
</div>
<style>
.bar { display: block; height: 6px; margin-top: 6px; background: var(--surface-2); border-radius: 3px; overflow: hidden; }
.pair { display: flex; flex-shrink: 0; }
.pair :global(.avatar) { box-shadow: 0 0 0 3px var(--surface); }
.pair :global(.avatar + .avatar) { margin-left: -10px; }
.bar { display: block; height: 5px; margin-top: 7px; background: var(--surface-2); border-radius: 3px; overflow: hidden; }
.fill { display: block; height: 100%; border-radius: 3px; }
.pos-fill { background: var(--accent); }
.neg-fill { background: var(--owe); }

View file

@ -1,7 +1,7 @@
<script lang="ts">
import { inBase, owedOriginal, type Expense } from '@oweme/core';
import { randomId } from '../lib/crypto.ts';
import { CATEGORY_ICONS, fmtDate, fmtDateTime, money } from '../lib/format.ts';
import { CATEGORY_COLORS, CATEGORY_ICONS, fmtDate, fmtDateTime, money } from '../lib/format.ts';
import type { MsgKey } from '../lib/i18n.ts';
import { router } from '../lib/router.svelte.ts';
import type { GroupSession } from '../lib/session.svelte.ts';
@ -82,7 +82,7 @@
{/if}
<div class="card stack" style:align-items="center" style:text-align="center">
<span class="cat-icon" aria-hidden="true">{CATEGORY_ICONS[e.category]}</span>
<span class="cat-icon" style:--cat={CATEGORY_COLORS[e.category]} aria-hidden="true">{CATEGORY_ICONS[e.category]}</span>
<div class="num" style:font-size="2rem" style:font-weight="700">{money(e.amount, e.currency)}</div>
{#if e.currency !== session.base}
<div class="muted small num">{t('converted', { amount: money(b.total, session.base), rate: e.rate })}</div>

View file

@ -38,7 +38,7 @@
let currency = $state(existing?.currency ?? base);
let amountText = $state(existing ? amountInput(existing.amount, existing.currency) : pAmount > 0 ? amountInput(pAmount, base) : '');
let title = $state(existing?.title ?? '');
let category = $state<Category>(existing?.category === 'transfer' ? 'other' : (existing?.category ?? 'food'));
let category = $state<Category>(existing?.category === 'transfer' ? 'other' : (existing?.category ?? session.state.group?.defaultCategory ?? 'other'));
let date = $state(existing?.date ?? today());
let note = $state(existing?.note ?? '');
let rateText = $state(existing && existing.currency !== base ? existing.rate : '1');

View file

@ -1,10 +1,11 @@
<script lang="ts">
import { inBase } from '@oweme/core';
import { addDays, CATEGORY_ICONS, fmtDate, money, today } from '../lib/format.ts';
import { addDays, CATEGORY_COLORS, CATEGORY_ICONS, fmtDate, money, today } from '../lib/format.ts';
import { router } from '../lib/router.svelte.ts';
import type { GroupSession } from '../lib/session.svelte.ts';
import { t } from '../lib/settings.svelte.ts';
import Icon from './Icon.svelte';
import Money from './Money.svelte';
let { session }: { session: GroupSession } = $props();
let query = $state('');
@ -24,12 +25,6 @@
return groups;
});
const total = $derived(
Object.values(session.state.expenses)
.filter((r) => !r.deleted && r.expense.kind === 'expense')
.reduce((a, r) => a + inBase(r.expense, session.base).total, 0),
);
function dayLabel(d: string) {
if (d === today()) return t('today');
if (d === addDays(today(), -1)) return t('yesterday');
@ -53,13 +48,6 @@
</script>
<div class="stack">
<div class="card row">
<div class="grow">
<div class="muted small">{t('total_spent')}</div>
<div class="num" style:font-size="1.6rem" style:font-weight="700">{money(total, session.base)}</div>
</div>
</div>
{#if Object.keys(session.state.expenses).length > 6}
<input type="search" bind:value={query} placeholder={t('search')} aria-label={t('search')} />
{/if}
@ -70,34 +58,50 @@
{#each rows as day (day.date)}
<section class="stack" style:gap="6px">
<h3>{dayLabel(day.date)}</h3>
<h3 class="day">{dayLabel(day.date)}</h3>
<div class="list">
{#each day.items as r (r.expense.id)}
{@const e = r.expense}
{@const m = mine(e)}
<a class="item" href="/g/{session.id}/e/{encodeURIComponent(e.id)}" onclick={(ev) => open(ev, e.id)}>
<span class="cat-icon" aria-hidden="true">{CATEGORY_ICONS[e.category] ?? '🧾'}</span>
<span class="grow">
<span class="title row" style:gap="6px">
{#if e.kind === 'transfer'}
{t('transfer_line', { from: session.memberName(e.payers[0]?.member), to: session.memberName(e.split.entries.find((x) => x.value > 0)?.member) })}
{:else}
{e.title}
{/if}
{#if e.recurringId}<Icon name="repeat" size={14} />{/if}
{#if e.photo}<Icon name="camera" size={14} />{/if}
<span class="cat-icon" style:--cat={CATEGORY_COLORS[e.category]} aria-hidden="true">{CATEGORY_ICONS[e.category] ?? '🧾'}</span>
<!-- Two lines, each splitting its width: title | amount, then payer | your part.
Keeps the title readable on narrow phones. -->
<span class="grow lines">
<span class="line">
<span class="title grow">
<span class="ellipsis">
{#if e.kind === 'transfer'}
{t('transfer_line', { from: session.memberName(e.payers[0]?.member), to: session.memberName(e.split.entries.find((x) => x.value > 0)?.member) })}
{:else}
{e.title}
{/if}
</span>
{#if e.recurringId}<Icon name="repeat" size={14} />{/if}
{#if e.photo}<Icon name="camera" size={14} />{/if}
</span>
<span class="amt"><Money minor={e.amount} currency={e.currency} /></span>
</span>
<span class="sub" style:display="block">
{e.payers.length === 1 ? t('paid_by', { name: session.memberName(e.payers[0].member) }) : t('paid_by_many', { n: e.payers.length })}
<span class="line">
<span class="sub grow">
{e.payers.length === 1 ? t('paid_by', { name: session.memberName(e.payers[0].member) }) : t('paid_by_many', { n: e.payers.length })}
</span>
{#if m}<span class="small num mine {m.cls}">{m.text}</span>{/if}
</span>
</span>
<span class="end">
<span class="num" style:display="block" style:font-weight="600">{money(e.amount, e.currency)}</span>
{#if m}<span class="small num {m.cls}" style:display="block">{m.text}</span>{/if}
</span>
</a>
{/each}
</div>
</section>
{/each}
</div>
<style>
.lines { display: flex; flex-direction: column; gap: 2px; }
.line { display: flex; align-items: baseline; gap: 10px; min-width: 0; }
.title { display: flex; align-items: center; gap: 6px; min-width: 0; }
.title :global(svg) { color: var(--muted); }
.ellipsis { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.amt { flex-shrink: 0; font-weight: 650; }
.mine { flex-shrink: 0; white-space: nowrap; } /* your part matters more than who paid */
</style>

View file

@ -0,0 +1,74 @@
<script lang="ts">
// Top of the group page: your balance as the headline number, the group's
// total, and round quick actions. Reports whether the actions are on
// screen so the page can show the floating Add button only when they aren't.
import { inBase } from '@oweme/core';
import { router } from '../lib/router.svelte.ts';
import type { GroupSession } from '../lib/session.svelte.ts';
import { t } from '../lib/settings.svelte.ts';
import Icon from './Icon.svelte';
import Money from './Money.svelte';
let { session, onactionsvisible }: { session: GroupSession; onactionsvisible: (visible: boolean) => void } = $props();
const base = $derived(`/g/${session.id}`);
const total = $derived(
Object.values(session.state.expenses)
.filter((r) => !r.deleted && r.expense.kind === 'expense')
.reduce((a, r) => a + inBase(r.expense, session.base).total, 0),
);
const mine = $derived(session.me ? (session.balances[session.me] ?? 0) : null);
function go(e: MouseEvent, path: string, replace = false) {
e.preventDefault();
router.go(path, { replace });
}
let actions: HTMLElement;
$effect(() => {
const io = new IntersectionObserver(([entry]) => onactionsvisible(entry.isIntersecting));
io.observe(actions);
return () => io.disconnect();
});
</script>
<section class="hero" aria-label={t('summary')}>
{#if mine === null}
<div class="lbl">{t('total_spent')}</div>
<div class="big"><Money minor={total} currency={session.base} /></div>
{:else}
<div class="lbl">{mine > 0 ? t('hero_owed') : mine < 0 ? t('hero_owe') : t('hero_settled')}</div>
<div class="big {mine > 0 ? 'pos' : mine < 0 ? 'neg' : ''}"><Money minor={Math.abs(mine)} currency={session.base} /></div>
<div class="meta"><span class="dot" aria-hidden="true"></span>{t('total_spent')} <Money minor={total} currency={session.base} /></div>
{/if}
</section>
<nav class="actions" bind:this={actions} aria-label={t('quick_actions')}>
<a class="act primary" href="{base}/e/new" onclick={(e) => go(e, `${base}/e/new`)} aria-label={t('add_expense')}><span class="c"><Icon name="plus" /></span>{t('add')}</a>
<a class="act" href="{base}/e/new?kind=transfer" onclick={(e) => go(e, `${base}/e/new?kind=transfer`)} aria-label={t('add_payment')}><span class="c"><Icon name="swap" /></span>{t('payment_short')}</a>
<a class="act" href="{base}/balances" onclick={(e) => go(e, `${base}/balances`, true)}><span class="c"><Icon name="scale" /></span>{t('settle_up')}</a>
<a class="act" href="{base}/settings" onclick={(e) => go(e, `${base}/settings`)}><span class="c"><Icon name="share" /></span>{t('share_short')}</a>
</nav>
<style>
.hero { text-align: center; padding: 8px 0 0; }
.lbl { color: var(--muted); font-size: 0.92rem; font-weight: 500; }
.big { font-size: 2.75rem; font-weight: 750; letter-spacing: -0.03em; line-height: 1.15; margin: 2px 0; overflow-wrap: anywhere; }
.big :global(.cur), .big :global(.frac) { font-size: 0.55em; letter-spacing: -0.01em; }
.meta {
display: inline-flex; align-items: center; gap: 6px; margin-top: 6px; padding: 6px 12px; border-radius: 999px;
background: var(--surface); color: var(--muted); font-size: 0.84rem; font-weight: 500;
}
.meta :global(.money), .meta :global(.money .cur), .meta :global(.money .frac) { color: var(--text); font-size: 1em; }
.dot { width: 7px; height: 7px; border-radius: 50%; background: var(--accent); }
.actions { display: flex; justify-content: center; gap: 8px; padding: 14px 0 4px; }
.act {
flex: 0 1 84px; display: flex; flex-direction: column; align-items: center; gap: 7px; text-align: center;
font-size: 0.8rem; font-weight: 600; color: var(--text); text-decoration: none; line-height: 1.2;
}
.act .c { width: 52px; height: 52px; border-radius: 50%; background: var(--surface-2); display: grid; place-items: center; }
.act.primary .c { background: var(--accent); color: var(--accent-ink); }
.act:hover .c { filter: brightness(1.12); }
.act:focus-visible { outline: none; }
.act:focus-visible .c { outline: 2px solid var(--accent); outline-offset: 2px; }
</style>

View file

@ -9,6 +9,7 @@
import ExpenseDetail from './ExpenseDetail.svelte';
import ExpenseEditor from './ExpenseEditor.svelte';
import ExpenseList from './ExpenseList.svelte';
import GroupHeader from './GroupHeader.svelte';
import GroupSettings from './GroupSettings.svelte';
import Icon from './Icon.svelte';
import IdentityPicker from './IdentityPicker.svelte';
@ -19,12 +20,16 @@
const id = untrack(() => props.id);
let session = $state<GroupSession | null | undefined>(undefined);
let skippedIdentity = $state(false);
// The floating Add button only appears once the header's actions scroll away.
// Starts true so the button doesn't flash before the observer reports.
let actionsVisible = $state(true);
openSession(id).then((s) => (session = s));
onDestroy(() => closeSession(id));
const route = $derived(router.route);
const tab = $derived(route.name === 'group' ? route.tab : 'expenses');
const withHeader = $derived(tab === 'expenses' || tab === 'balances');
const base = `/g/${id}`;
const tabs = [
{ key: 'expenses', path: base, icon: 'list', label: 'expenses' },
@ -62,7 +67,8 @@
{@const s = session}
<header class="topbar">
<button class="icon-btn" onclick={() => router.go('/')} aria-label={t('back')}><Icon name="back" /></button>
<h1><span aria-hidden="true">{s.state.group?.icon}</span> {s.state.group?.name ?? s.local.name}</h1>
{#if s.state.group?.icon}<span class="group-icon" aria-hidden="true">{s.state.group.icon}</span>{/if}
<h1>{s.state.group?.name ?? s.local.name}</h1>
<a class="icon-btn" href="{base}/settings" onclick={(e) => nav(e, `${base}/settings`)} aria-label={t('group_settings')}><Icon name="settings" /></a>
</header>
@ -80,6 +86,10 @@
{/if}
{#if s.rollback}<p class="banner warn">{t('rollback_warning')}</p>{/if}
{#if withHeader && s.status !== 'gone'}
<GroupHeader session={s} onactionsvisible={(v) => (actionsVisible = v)} />
{/if}
<nav class="tabbar" aria-label={s.state.group?.name}>
{#each tabs as tb}
<a href={tb.path} aria-current={tab === tb.key ? 'page' : undefined} onclick={(e) => nav(e, tb.path, true)}>
@ -107,7 +117,7 @@
</div>
</main>
{#if s.status !== 'gone' && (tab === 'expenses' || tab === 'balances')}
{#if s.status !== 'gone' && withHeader && !actionsVisible}
<a class="fab" href="{base}/e/new" onclick={(e) => nav(e, `${base}/e/new`)} aria-label={t('add_expense')}><Icon name="plus" size={28} /></a>
{/if}
@ -123,7 +133,13 @@
{/if}
<style>
.layout { display: grid; gap: 24px; }
.group-icon {
display: grid; place-items: center; flex-shrink: 0; width: 36px; height: 36px; border-radius: 50%;
background: var(--surface-2); font-size: 1.1rem;
}
/* minmax(0, …): without it a long title or name (nowrap + ellipsis) widens
the column past the screen and phones zoom out. */
.layout { display: grid; grid-template-columns: minmax(0, 1fr); gap: 24px; }
.side-col { display: none; }
@media (min-width: 960px) {
.layout.with-side { grid-template-columns: minmax(0, 1fr) 340px; }

View file

@ -1,11 +1,12 @@
<script lang="ts">
import { untrack } from 'svelte';
import { balancesCsv, expensesCsv, nextOccurrence } from '@oweme/core';
import { balancesCsv, CATEGORIES, expensesCsv, nextOccurrence } from '@oweme/core';
import { renderSVG } from 'uqr';
import { api } from '../lib/api.ts';
import { makeBackup } from '../lib/backup.ts';
import { randomId } from '../lib/crypto.ts';
import { download, fmtDate, MEMBER_COLORS, money, slug, today } from '../lib/format.ts';
import { CATEGORY_ICONS, download, fmtDate, MEMBER_COLORS, money, slug, today } from '../lib/format.ts';
import type { MsgKey } from '../lib/i18n.ts';
import { forgetGroup } from '../lib/idb.ts';
import { disablePush, enablePush, pushSupport, type PushSupport } from '../lib/push.ts';
import { router } from '../lib/router.svelte.ts';
@ -27,6 +28,7 @@
let name = $state(s.state.group?.name ?? '');
let icon = $state(s.state.group?.icon ?? '');
let baseCurrency = $state(s.base);
let defaultCategory = $state<string>(s.state.group?.defaultCategory ?? 'other');
let newMember = $state('');
let deleteConfirm = $state('');
let push = $state<PushSupport | null>(null);
@ -34,7 +36,10 @@
pushSupport().then((p) => (push = p));
const locked = $derived(Object.keys(s.state.expenses).length > 0);
const dirty = $derived(name.trim() !== s.state.group?.name || icon !== s.state.group?.icon || baseCurrency !== s.base);
const dirty = $derived(
name.trim() !== s.state.group?.name || icon !== s.state.group?.icon || baseCurrency !== s.base ||
defaultCategory !== (s.state.group?.defaultCategory ?? 'other'),
);
async function copy() {
await navigator.clipboard.writeText(link);
@ -50,10 +55,11 @@
async function saveGroup(e: SubmitEvent) {
e.preventDefault();
if (!name.trim()) return;
const data: { name?: string; icon?: string; baseCurrency?: string } = {};
const data: { name?: string; icon?: string; baseCurrency?: string; defaultCategory?: (typeof CATEGORIES)[number] } = {};
if (name.trim() !== s.state.group?.name) data.name = name.trim();
if (icon !== s.state.group?.icon) data.icon = icon;
if (!locked && baseCurrency !== s.base) data.baseCurrency = baseCurrency;
if (defaultCategory !== (s.state.group?.defaultCategory ?? 'other')) data.defaultCategory = defaultCategory as (typeof CATEGORIES)[number];
await s.emit({ type: 'group.updated', data });
ui.show(t('saved'));
}
@ -141,6 +147,13 @@
<CurrencySelect bind:value={baseCurrency} disabled={locked} />
<span class="small">{locked ? t('base_currency_locked') : t('base_currency_hint')}</span>
</label>
<label class="field">
{t('default_category')}
<select bind:value={defaultCategory}>
{#each CATEGORIES as c}<option value={c}>{CATEGORY_ICONS[c]} {t(`cat_${c}` as MsgKey)}</option>{/each}
</select>
<span class="small">{t('default_category_hint')}</span>
</label>
<button class="btn primary" type="submit" disabled={!dirty || !name.trim()}>{t('save')}</button>
</form>
</section>

View file

@ -2,6 +2,7 @@
// Inline SVG icons (no icon font: keeps the CSP strict and works offline).
const paths = {
plus: 'M12 5v14M5 12h14',
swap: 'M7 7h11l-3-3M17 17H6l3 3',
back: 'M15 18l-6-6 6-6',
close: 'M18 6L6 18M6 6l12 12',
settings: 'M12 15a3 3 0 1 0 0-6 3 3 0 0 0 0 6zM19.4 15a1.7 1.7 0 0 0 .3 1.8l.1.1a2 2 0 1 1-2.8 2.8l-.1-.1a1.7 1.7 0 0 0-1.8-.3 1.7 1.7 0 0 0-1 1.5V21a2 2 0 1 1-4 0v-.1a1.7 1.7 0 0 0-1.1-1.5 1.7 1.7 0 0 0-1.8.3l-.1.1a2 2 0 1 1-2.8-2.8l.1-.1a1.7 1.7 0 0 0 .3-1.8 1.7 1.7 0 0 0-1.5-1H3a2 2 0 1 1 0-4h.1a1.7 1.7 0 0 0 1.5-1.1 1.7 1.7 0 0 0-.3-1.8l-.1-.1a2 2 0 1 1 2.8-2.8l.1.1a1.7 1.7 0 0 0 1.8.3H9a1.7 1.7 0 0 0 1-1.5V3a2 2 0 1 1 4 0v.1a1.7 1.7 0 0 0 1 1.5 1.7 1.7 0 0 0 1.8-.3l.1-.1a2 2 0 1 1 2.8 2.8l-.1.1a1.7 1.7 0 0 0-.3 1.8V9a1.7 1.7 0 0 0 1.5 1H21a2 2 0 1 1 0 4h-.1a1.7 1.7 0 0 0-1.5 1z',

View file

@ -0,0 +1,10 @@
<script lang="ts">
// An amount with the whole number emphasised and the currency and
// decimals de-emphasised. Reads the same as money() to screen readers.
import { money, moneyParts } from '../lib/format.ts';
let { minor, currency, sign = false }: { minor: number; currency: string; sign?: boolean } = $props();
const p = $derived(moneyParts(minor, currency, { sign }));
</script>
<span class="money num"><span class="sr-only">{money(minor, currency, { sign })}</span><span aria-hidden="true"><span class="cur">{p.before}</span>{p.whole}<span class="frac">{p.frac}</span><span class="cur">{p.after}</span></span></span>

View file

@ -10,12 +10,17 @@
$effect(() => {
dialog.showModal();
// showModal() focuses the first control (the close button), which shows a
// focus ring even after a tap. Focus the dialog itself instead, unless a
// field asked for focus with autofocus. Tab still reaches every control.
if (!dialog.querySelector('[autofocus]')) dialog.focus();
return () => dialog.close();
});
</script>
<dialog
class="sheet"
tabindex="-1"
bind:this={dialog}
aria-label={title}
oncancel={(e) => { e.preventDefault(); onclose(); }}

View file

@ -31,7 +31,7 @@
</script>
<div class="stack">
<div class="seg" role="group" aria-label={t('stats')}>
<div class="seg compact" role="group" aria-label={t('stats')}>
{#each [['all', 'range_all'], ['year', 'range_year'], ['month', 'range_month'], ['30', 'range_30']] as const as [r, label]}
<button aria-pressed={range === r} onclick={() => (range = r)}>{t(label)}</button>
{/each}
@ -118,19 +118,20 @@
</div>
<style>
.seg.compact :global(button) { font-size: 0.84rem; padding: 0 6px; }
.tiles { display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 12px; }
.hero { font-size: 1.6rem; font-weight: 700; }
.s1 { background: var(--chart-1); }
.s2 { background: var(--chart-2); }
.bars { list-style: none; margin: 0; padding: 0; display: flex; flex-direction: column; gap: 10px; }
.bars li { display: grid; grid-template-columns: minmax(90px, 34%) 1fr auto; align-items: center; gap: 10px; }
.bars li { display: grid; grid-template-columns: minmax(90px, 34%) minmax(0, 1fr) auto; align-items: center; gap: 10px; }
.label { font-size: 0.9rem; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.track { display: block; height: 12px; }
.hbar { display: block; height: 100%; min-width: 2px; border-radius: 0 4px 4px 0; }
.value { font-size: 0.85rem; color: var(--text); text-align: right; }
.grouped li { grid-template-columns: minmax(70px, 28%) 1fr; }
.pair { display: flex; flex-direction: column; gap: 2px; }
.line { display: grid; grid-template-columns: 1fr auto; gap: 10px; align-items: center; }
.line { display: grid; grid-template-columns: minmax(0, 1fr) auto; gap: 10px; align-items: center; }
.legend { gap: 16px; }
.swatch { width: 12px; height: 12px; border-radius: 3px; display: inline-block; }
.months { display: flex; align-items: stretch; gap: 2px; height: 160px; }

View file

@ -3,8 +3,7 @@ import { settings } from './settings.svelte.ts';
const cache = new Map<string, Intl.NumberFormat>();
/** Format minor units as money in the current locale ("1 234,50 Kč"). */
export function money(minor: number, currency: string, opts: { sign?: boolean } = {}): string {
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) {
@ -19,7 +18,30 @@ export function money(minor: number, currency: string, opts: { sign?: boolean }
}
cache.set(key, f);
}
return f.format(minor / 10 ** exponent(currency));
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. */
@ -63,6 +85,13 @@ export function currencyName(code: string): string {
}
}
/** 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: '💊',

View file

@ -64,6 +64,15 @@ const cs: Messages = {
add_expense: 'Přidat výdaj',
no_expenses: 'Zatím žádné výdaje. Klepněte na + a přidejte první.',
total_spent: 'Celkem utraceno',
summary: 'Přehled',
hero_owed: 'Dluží vám',
hero_owe: 'Dlužíte',
hero_settled: 'Máte vyrovnáno',
quick_actions: 'Rychlé akce',
add: 'Přidat',
share_short: 'Sdílet',
payment_short: 'Platba',
add_payment: 'Zaznamenat platbu',
paid_by: 'Platil(a) {name}',
paid_by_many: 'Platilo {n} lidí',
your_share: 'váš podíl {amount}',
@ -97,6 +106,8 @@ const cs: Messages = {
title: 'Za co?',
title_ph: 'Večeře',
category: 'Kategorie',
default_category: 'Výchozí kategorie',
default_category_hint: 'Nové výdaje začnou v této kategorii.',
date: 'Datum',
currency: 'Měna',
rate: 'Směnný kurz',
@ -179,10 +190,10 @@ const cs: Messages = {
changed_fields: 'Změněno: {fields}',
no_activity: 'Zatím žádná aktivita.',
range_all: 'Celé období',
range_all: 'Vše',
range_month: 'Tento měsíc',
range_30: 'Posledních 30 dní',
range_year: 'Tento rok',
range_30: '30 dní',
range_year: 'Letos',
by_category: 'Podle kategorie',
by_month: 'Podle měsíce',
per_member: 'Zaplaceno vs. podíl',

View file

@ -70,6 +70,15 @@ const en = {
add_expense: 'Add expense',
no_expenses: 'No expenses yet. Tap + to add the first one.',
total_spent: 'Total spent',
summary: 'Summary',
hero_owed: 'You’re owed',
hero_owe: 'You owe',
hero_settled: 'You’re settled up',
quick_actions: 'Quick actions',
add: 'Add',
share_short: 'Share',
payment_short: 'Payment',
add_payment: 'Record a payment',
paid_by: 'Paid by {name}',
paid_by_many: 'Paid by {n} people',
your_share: 'your share {amount}',
@ -105,6 +114,8 @@ const en = {
title: 'What was it for?',
title_ph: 'Dinner',
category: 'Category',
default_category: 'Default category',
default_category_hint: 'New expenses start in this category.',
date: 'Date',
currency: 'Currency',
rate: 'Exchange rate',
@ -190,9 +201,9 @@ const en = {
no_activity: 'No activity yet.',
// stats
range_all: 'All time',
range_all: 'All',
range_month: 'This month',
range_30: 'Last 30 days',
range_30: '30 days',
range_year: 'This year',
by_category: 'By category',
by_month: 'By month',

View file

@ -99,7 +99,7 @@ test('two devices share a group end to end', async ({ browser }) => {
const fmt = (minor: number) => (minor / 100).toLocaleString('en-US', { minimumFractionDigits: 2 });
const shown = `${annaBal > 0 ? '+' : '−'}CZK ${fmt(Math.abs(annaBal))}`;
await expect(anna.getByText(shown).first()).toBeVisible();
await expect(anna.getByText('Settle up')).toBeVisible();
await expect(anna.getByRole('heading', { name: 'Settle up' })).toBeVisible();
const recordButtons = anna.getByRole('button', { name: 'Record payment' });
const transfers = await recordButtons.count();
expect(transfers).toBeGreaterThan(0);

View file

@ -4,7 +4,9 @@
// after its target event; nothing is ever erased from the log. See SPEC.md §6.
import { validateExpense } from './expense.ts';
import { isCurrencyCode } from './money.ts';
import type { Activity, GroupEvent, GroupState, Recurring } from './types.ts';
import { CATEGORIES, type Activity, type GroupEvent, type GroupState, type Recurring } from './types.ts';
const isCategory = (c: unknown): c is (typeof CATEGORIES)[number] => (CATEGORIES as readonly unknown[]).includes(c);
export function emptyState(): GroupState {
return { group: null, members: [], expenses: {}, comments: {}, recurring: {} };
@ -40,18 +42,22 @@ function apply(s: GroupState, ev: GroupEvent, snapshots: Map<string, GroupState>
const d = ev.data;
if (s.group || !str(d?.name, 100) || !isCurrencyCode(d.baseCurrency)) return ignore();
s.group = { name: d.name, baseCurrency: d.baseCurrency, icon: typeof d.icon === 'string' ? d.icon.slice(0, 16) : '' };
if (isCategory(d.defaultCategory)) s.group.defaultCategory = d.defaultCategory;
act.after = { ...s.group };
break;
}
case 'group.updated': {
if (!s.group) return ignore();
const d = ev.data ?? {};
// Validate before changing anything, so an invalid event has no effect.
if (d.defaultCategory !== undefined && !isCategory(d.defaultCategory)) return ignore();
act.before = { ...s.group };
if (d.name !== undefined) {
if (!str(d.name, 100)) return ignore();
s.group.name = d.name;
}
if (typeof d.icon === 'string') s.group.icon = d.icon.slice(0, 16);
if (d.defaultCategory !== undefined) s.group.defaultCategory = d.defaultCategory;
if (d.baseCurrency !== undefined && d.baseCurrency !== s.group.baseCurrency) {
// Locked once the group has any expense (SPEC §7.1).
if (hasExpenses || !isCurrencyCode(d.baseCurrency)) return ignore();

View file

@ -81,6 +81,8 @@ export interface GroupInfo {
name: string;
baseCurrency: string;
icon: string;
/** category new expenses start with; absent = 'other' */
defaultCategory?: (typeof CATEGORIES)[number];
}
export type EventBody =

View file

@ -149,6 +149,15 @@ describe('replay', () => {
expect(replay(locked).state.group!.baseCurrency).toBe('CZK');
});
it('sets a default category and ignores invalid ones', () => {
const set = [...baseGroup(), ev({ type: 'group.updated', data: { defaultCategory: 'travel' } })];
expect(replay(set).state.group!.defaultCategory).toBe('travel');
const bad = [...set, ev({ type: 'group.updated', data: { defaultCategory: 'transfer' as never, name: 'Renamed' } })];
const g = replay(bad).state.group!;
expect(g.defaultCategory).toBe('travel');
expect(g.name).not.toBe('Renamed'); // the whole invalid event is ignored
});
it('revert restores an earlier state, and can itself be reverted', () => {
const evs = [...baseGroup(), ev({ type: 'expense.created', data: expense() }, 'a', 'keep')];
evs.push(ev({ type: 'expense.updated', data: expense({ amount: 99900, payers: [{ member: 'a', amount: 99900 }] }) }, 'b', 'vandal'));