Family bookkeeping PWA modelled on 木木记账
Hono + SQLite server and a React/shadcn PWA with two-level categories, who-spent/who-paid splits, settlement, one-line and voice entry, budget alerts (Web Push and Bark), monthly/annual reports, and 木木 import tools. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
+103
@@ -0,0 +1,103 @@
|
||||
import { createContext, lazy, Suspense, useContext, useState, type ReactNode } from 'react';
|
||||
import { NavLink, Route, Routes } from 'react-router';
|
||||
import { useQuery } from '@tanstack/react-query';
|
||||
import { BarChart3, Handshake, List, Plus, User } from 'lucide-react';
|
||||
import { ApiError, api, type Bill } from '@/lib/api';
|
||||
import { MetaProvider } from '@/lib/meta';
|
||||
import { cn } from '@/lib/utils';
|
||||
import { BillEditor } from '@/components/bill-editor';
|
||||
import LoginPage from '@/pages/login';
|
||||
import HomePage from '@/pages/home';
|
||||
import SettlePage from '@/pages/settle';
|
||||
import MePage from '@/pages/me';
|
||||
|
||||
// Chart pages carry the charting library, so load them on demand.
|
||||
const StatsPage = lazy(() => import('@/pages/stats'));
|
||||
const ReportPage = lazy(() => import('@/pages/report'));
|
||||
|
||||
interface EditorApi {
|
||||
open: (opts?: { bill?: Bill; text?: string }) => void;
|
||||
}
|
||||
const EditorCtx = createContext<EditorApi>({ open: () => {} });
|
||||
export const useEditor = () => useContext(EditorCtx);
|
||||
|
||||
export default function App() {
|
||||
const meta = useQuery({ queryKey: ['meta'], queryFn: api.meta });
|
||||
|
||||
if (meta.isPending) return <div className="flex h-full items-center justify-center text-muted-foreground">加载中…</div>;
|
||||
if (meta.error instanceof ApiError && meta.error.status === 401) return <LoginPage />;
|
||||
if (meta.error) {
|
||||
return (
|
||||
<div className="flex h-full flex-col items-center justify-center gap-3 p-6 text-center text-muted-foreground">
|
||||
<p>无法连接服务器</p>
|
||||
<button className="text-primary" onClick={() => meta.refetch()}>重试</button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<MetaProvider meta={meta.data}>
|
||||
<Shell>
|
||||
<Suspense fallback={null}>
|
||||
<Routes>
|
||||
<Route path="/" element={<HomePage />} />
|
||||
<Route path="/stats" element={<StatsPage />} />
|
||||
<Route path="/report/:year" element={<ReportPage />} />
|
||||
<Route path="/settle" element={<SettlePage />} />
|
||||
<Route path="/me" element={<MePage />} />
|
||||
</Routes>
|
||||
</Suspense>
|
||||
</Shell>
|
||||
</MetaProvider>
|
||||
);
|
||||
}
|
||||
|
||||
function Shell({ children }: { children: ReactNode }) {
|
||||
const [editor, setEditor] = useState<{ open: boolean; bill?: Bill; text?: string }>({ open: false });
|
||||
|
||||
return (
|
||||
<EditorCtx.Provider value={{ open: (o) => setEditor({ open: true, ...o }) }}>
|
||||
<div className="mx-auto flex min-h-full max-w-lg flex-col">
|
||||
<main className="flex-1 pb-24">{children}</main>
|
||||
<nav className="pb-safe fixed inset-x-0 bottom-0 z-40 border-t bg-card/95 backdrop-blur">
|
||||
<div className="mx-auto grid h-14 max-w-lg grid-cols-5">
|
||||
<Tab to="/" icon={<List className="size-5" />} label="明细" />
|
||||
<Tab to="/stats" icon={<BarChart3 className="size-5" />} label="统计" />
|
||||
<div className="flex items-center justify-center">
|
||||
<button
|
||||
onClick={() => setEditor({ open: true })}
|
||||
aria-label="记一笔"
|
||||
className="-mt-5 flex size-13 items-center justify-center rounded-full bg-primary text-primary-foreground shadow-lg shadow-primary/30 active:scale-95"
|
||||
>
|
||||
<Plus className="size-7" />
|
||||
</button>
|
||||
</div>
|
||||
<Tab to="/settle" icon={<Handshake className="size-5" />} label="结算" />
|
||||
<Tab to="/me" icon={<User className="size-5" />} label="我的" />
|
||||
</div>
|
||||
</nav>
|
||||
</div>
|
||||
<BillEditor
|
||||
open={editor.open}
|
||||
bill={editor.bill}
|
||||
initialText={editor.text}
|
||||
onClose={() => setEditor((e) => ({ ...e, open: false }))}
|
||||
/>
|
||||
</EditorCtx.Provider>
|
||||
);
|
||||
}
|
||||
|
||||
function Tab({ to, icon, label }: { to: string; icon: ReactNode; label: string }) {
|
||||
return (
|
||||
<NavLink
|
||||
to={to}
|
||||
end={to === '/'}
|
||||
className={({ isActive }) =>
|
||||
cn('flex flex-col items-center justify-center gap-0.5 text-[11px]', isActive ? 'text-primary' : 'text-muted-foreground')
|
||||
}
|
||||
>
|
||||
{icon}
|
||||
{label}
|
||||
</NavLink>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,505 @@
|
||||
import { Fragment, useCallback, useEffect, useMemo, useState } from 'react';
|
||||
import { useMutation, useQueryClient } from '@tanstack/react-query';
|
||||
import { toast } from 'sonner';
|
||||
import { ChevronLeft, Delete, Mic, Sparkles, Trash2 } from 'lucide-react';
|
||||
import { api, type Bill, type BillInput, type BillType, type BudgetAlert } from '@/lib/api';
|
||||
import { useMeta } from '@/lib/meta';
|
||||
import { fromLocalInput, money, toLocalInput } from '@/lib/format';
|
||||
import { speechSupported, useSpeech } from '@/lib/speech';
|
||||
import { cn } from '@/lib/utils';
|
||||
import { CategoryIcon } from './category-icon';
|
||||
import { SheetPage } from './sheet-page';
|
||||
import { Button } from './ui/button';
|
||||
import {
|
||||
AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogFooter,
|
||||
AlertDialogHeader, AlertDialogTitle,
|
||||
} from './ui/alert-dialog';
|
||||
|
||||
interface Props {
|
||||
open: boolean;
|
||||
onClose: () => void;
|
||||
bill?: Bill | null;
|
||||
// A phrase to fill the form from, e.g. from the quick entry box.
|
||||
initialText?: string;
|
||||
}
|
||||
|
||||
const COLS = 5;
|
||||
|
||||
// Evaluates "12+3.5-1" into cents. Returns null when incomplete.
|
||||
function evalAmount(expr: string): number | null {
|
||||
if (!expr) return null;
|
||||
const tokens = expr.match(/[+-]?[^+-]+/g);
|
||||
if (!tokens) return null;
|
||||
let total = 0;
|
||||
for (const t of tokens) {
|
||||
const v = Number(t);
|
||||
if (Number.isNaN(v)) return null;
|
||||
total += Math.round(v * 100);
|
||||
}
|
||||
return total;
|
||||
}
|
||||
|
||||
function lastCategory(type: BillType): number | null {
|
||||
try {
|
||||
const v = localStorage.getItem(`lastCategory:${type}`);
|
||||
return v ? Number(v) : null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export function useAlertToasts() {
|
||||
const meta = useMeta();
|
||||
return useCallback(
|
||||
(alerts: BudgetAlert[]) => {
|
||||
for (const a of alerts) {
|
||||
const what = a.budget.categoryId ? `「${meta.category(a.budget.categoryId)?.name}」预算` : '本月总预算';
|
||||
const detail = `已花 ¥${money(a.budget.spent)} / 预算 ¥${money(a.budget.amount)}`;
|
||||
if (a.level >= 100) toast.error(`${what}已超支`, { description: detail, duration: 6000 });
|
||||
else toast.warning(`${what}已用 ${a.budget.percent}%`, { description: detail, duration: 6000 });
|
||||
}
|
||||
},
|
||||
[meta],
|
||||
);
|
||||
}
|
||||
|
||||
export function BillEditor({ open, onClose, bill, initialText }: Props) {
|
||||
const meta = useMeta();
|
||||
const qc = useQueryClient();
|
||||
const showAlerts = useAlertToasts();
|
||||
const me = meta.me.memberId;
|
||||
|
||||
const [type, setType] = useState<BillType>('expense');
|
||||
const [categoryId, setCategoryId] = useState<number | null>(null);
|
||||
const [expanded, setExpanded] = useState<number | null>(null);
|
||||
const [expr, setExpr] = useState('');
|
||||
const [time, setTime] = useState(Date.now());
|
||||
const [note, setNote] = useState('');
|
||||
const [payerId, setPayerId] = useState<number | null>(me);
|
||||
const [memberIds, setMemberIds] = useState<number[]>([me]);
|
||||
const [shares, setShares] = useState<Record<number, string> | null>(null);
|
||||
const [excludeBudget, setExcludeBudget] = useState(false);
|
||||
const [bookId, setBookId] = useState(meta.bookId);
|
||||
const [quick, setQuick] = useState('');
|
||||
const [confirmDelete, setConfirmDelete] = useState(false);
|
||||
|
||||
const selectCategory = useCallback(
|
||||
(id: number | null) => {
|
||||
setCategoryId(id);
|
||||
const c = meta.category(id);
|
||||
if (c) setExpanded(meta.parentOf(c).id);
|
||||
},
|
||||
[meta],
|
||||
);
|
||||
|
||||
const reset = useCallback(
|
||||
(keepContext = false) => {
|
||||
setExpr('');
|
||||
setNote('');
|
||||
setShares(null);
|
||||
setQuick('');
|
||||
if (!keepContext) {
|
||||
setType('expense');
|
||||
selectCategory(lastCategory('expense'));
|
||||
setTime(Date.now());
|
||||
setPayerId(me);
|
||||
setMemberIds([me]);
|
||||
setExcludeBudget(false);
|
||||
setBookId(meta.bookId);
|
||||
}
|
||||
},
|
||||
[me, meta.bookId, selectCategory],
|
||||
);
|
||||
|
||||
const applyParsed = useCallback(
|
||||
async (text: string) => {
|
||||
try {
|
||||
const p = await api.quick(text);
|
||||
setType(p.type);
|
||||
if (p.categoryId) selectCategory(p.categoryId);
|
||||
else selectCategory(lastCategory(p.type));
|
||||
if (p.amount) setExpr(String(p.amount / 100));
|
||||
setTime(p.time);
|
||||
setNote(p.note);
|
||||
setMemberIds(p.memberIds);
|
||||
setPayerId(p.type === 'expense' ? p.payerId : null);
|
||||
setShares(null);
|
||||
setQuick('');
|
||||
if (!p.amount) toast.info('没听出金额,请在键盘上输入');
|
||||
else if (!p.categoryId) toast.info('请选择一个分类');
|
||||
} catch (e) {
|
||||
toast.error((e as Error).message);
|
||||
}
|
||||
},
|
||||
[selectCategory],
|
||||
);
|
||||
|
||||
// Fill the form whenever the sheet opens.
|
||||
useEffect(() => {
|
||||
if (!open) return;
|
||||
if (bill) {
|
||||
setType(bill.type);
|
||||
selectCategory(bill.categoryId);
|
||||
setExpr(String(bill.amount / 100));
|
||||
setTime(bill.time);
|
||||
setNote(bill.note);
|
||||
setPayerId(bill.payerId);
|
||||
setMemberIds(bill.members.map((m) => m.memberId));
|
||||
const even = bill.members.every((m) => Math.abs(m.share - bill.amount / bill.members.length) < 1);
|
||||
setShares(even ? null : Object.fromEntries(bill.members.map((m) => [m.memberId, String(m.share / 100)])));
|
||||
setExcludeBudget(bill.excludeBudget);
|
||||
setBookId(bill.bookId);
|
||||
setQuick('');
|
||||
} else {
|
||||
reset();
|
||||
if (initialText) applyParsed(initialText);
|
||||
}
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [open, bill?.id]);
|
||||
|
||||
const speech = useSpeech(applyParsed);
|
||||
const canSpeak = useMemo(speechSupported, []);
|
||||
|
||||
const amount = evalAmount(expr);
|
||||
const roots = meta.roots(type);
|
||||
const children = expanded ? meta.childrenOf(expanded) : [];
|
||||
|
||||
const switchType = (t: BillType) => {
|
||||
setType(t);
|
||||
selectCategory(lastCategory(t));
|
||||
if (t === 'income') setPayerId(null);
|
||||
else setPayerId(me);
|
||||
};
|
||||
|
||||
const allMembers = meta.members.map((m) => m.id);
|
||||
const isShared = memberIds.length === allMembers.length && allMembers.length > 1;
|
||||
|
||||
const press = (key: string) => {
|
||||
setExpr((e) => {
|
||||
if (key === 'back') return e.slice(0, -1);
|
||||
if (key === '+' || key === '-') {
|
||||
if (!e) return e;
|
||||
return /[+-]$/.test(e) ? e.slice(0, -1) + key : e + key;
|
||||
}
|
||||
const last = e.split(/[+-]/).at(-1) ?? '';
|
||||
if (key === '.') return last.includes('.') ? e : e + (last ? '.' : '0.');
|
||||
if (/\.\d{2}$/.test(last)) return e;
|
||||
if (last === '0' && key !== '.') return e.slice(0, -1) + key;
|
||||
if (last.replace('.', '').length >= 9) return e;
|
||||
return e + key;
|
||||
});
|
||||
};
|
||||
|
||||
const save = useMutation({
|
||||
mutationFn: async (again: boolean) => {
|
||||
if (!categoryId) throw new Error('请选择分类');
|
||||
if (!amount || amount <= 0) throw new Error('请输入金额');
|
||||
let members: BillInput['members'] = memberIds.map((memberId) => ({ memberId }));
|
||||
if (shares && memberIds.length > 1) {
|
||||
members = memberIds.map((memberId) => ({ memberId, share: Math.round(Number(shares[memberId] || 0) * 100) }));
|
||||
const sum = members.reduce((s, m) => s + (m.share ?? 0), 0);
|
||||
if (sum !== amount) throw new Error(`分摊合计 ¥${money(sum)},与金额 ¥${money(amount)} 不一致`);
|
||||
}
|
||||
const input: BillInput = {
|
||||
bookId, type, categoryId, amount, time, note: note.trim(),
|
||||
payerId: type === 'expense' ? payerId : null, members, excludeBudget,
|
||||
};
|
||||
const res = bill ? await api.updateBill(bill.id, input) : await api.createBill(input);
|
||||
return { res, again };
|
||||
},
|
||||
onSuccess: ({ res, again }) => {
|
||||
try { localStorage.setItem(`lastCategory:${type}`, String(categoryId)); } catch { /* ignore */ }
|
||||
qc.invalidateQueries();
|
||||
showAlerts(res.alerts);
|
||||
if (again) {
|
||||
toast.success('已保存,继续记下一笔');
|
||||
reset(true);
|
||||
} else {
|
||||
toast.success(bill ? '已修改' : '已记录');
|
||||
onClose();
|
||||
}
|
||||
},
|
||||
onError: (e) => toast.error((e as Error).message),
|
||||
});
|
||||
|
||||
const remove = useMutation({
|
||||
mutationFn: () => api.deleteBill(bill!.id),
|
||||
onSuccess: () => {
|
||||
qc.invalidateQueries();
|
||||
toast.success('已删除');
|
||||
onClose();
|
||||
},
|
||||
});
|
||||
|
||||
// Category rows, with the children panel inserted under the row of the open parent.
|
||||
const rows: (typeof roots)[] = [];
|
||||
for (let i = 0; i < roots.length; i += COLS) rows.push(roots.slice(i, i + COLS));
|
||||
|
||||
return (
|
||||
<SheetPage open={open}>
|
||||
{/* Header */}
|
||||
<div className="pt-safe shrink-0 border-b bg-card">
|
||||
<div className="flex h-12 items-center gap-2 px-2">
|
||||
<Button variant="ghost" size="icon" onClick={onClose} aria-label="返回">
|
||||
<ChevronLeft className="size-5" />
|
||||
</Button>
|
||||
<div className="mx-auto flex rounded-full bg-muted p-0.5 text-sm">
|
||||
{(['expense', 'income'] as const).map((t) => (
|
||||
<button
|
||||
key={t}
|
||||
onClick={() => switchType(t)}
|
||||
className={cn('rounded-full px-5 py-1 transition-colors', type === t && 'bg-card font-medium shadow-sm')}
|
||||
>
|
||||
{t === 'expense' ? '支出' : '收入'}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
{bill ? (
|
||||
<Button variant="ghost" size="icon" onClick={() => setConfirmDelete(true)} aria-label="删除">
|
||||
<Trash2 className="size-5 text-destructive" />
|
||||
</Button>
|
||||
) : (
|
||||
<div className="size-9" />
|
||||
)}
|
||||
</div>
|
||||
{/* Quick entry */}
|
||||
{!bill && (
|
||||
<form
|
||||
className="flex items-center gap-2 px-3 pb-2"
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
if (quick.trim()) applyParsed(quick.trim());
|
||||
}}
|
||||
>
|
||||
<div className="flex h-9 flex-1 items-center gap-2 rounded-full bg-muted px-3">
|
||||
<Sparkles className="size-4 shrink-0 text-primary" />
|
||||
<input
|
||||
value={speech.listening ? speech.text : quick}
|
||||
onChange={(e) => setQuick(e.target.value)}
|
||||
placeholder={speech.listening ? '正在听…' : '一句话记账:和猪猪打车35'}
|
||||
className="min-w-0 flex-1 bg-transparent text-sm outline-none placeholder:text-muted-foreground"
|
||||
enterKeyHint="done"
|
||||
/>
|
||||
</div>
|
||||
{canSpeak && (
|
||||
<Button
|
||||
type="button"
|
||||
size="icon"
|
||||
variant={speech.listening ? 'default' : 'secondary'}
|
||||
className={cn('rounded-full', speech.listening && 'animate-pulse')}
|
||||
onClick={() => (speech.listening ? speech.stop() : speech.start())}
|
||||
aria-label="语音记账"
|
||||
>
|
||||
<Mic className="size-4" />
|
||||
</Button>
|
||||
)}
|
||||
</form>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Category grid */}
|
||||
<div className="min-h-0 flex-1 overflow-y-auto px-2 py-3">
|
||||
{rows.map((row, i) => (
|
||||
<Fragment key={i}>
|
||||
<div className="grid grid-cols-5 gap-y-3">
|
||||
{row.map((c) => {
|
||||
const active = expanded === c.id;
|
||||
const chosen = categoryId === c.id || meta.category(categoryId)?.parentId === c.id;
|
||||
return (
|
||||
<button
|
||||
key={c.id}
|
||||
onClick={() => {
|
||||
setExpanded(active ? null : c.id);
|
||||
if (!chosen) setCategoryId(c.id);
|
||||
}}
|
||||
className="flex flex-col items-center gap-1"
|
||||
>
|
||||
<CategoryIcon
|
||||
category={c}
|
||||
className={cn('size-12 transition-all', chosen && 'bg-primary/15 ring-2 ring-primary')}
|
||||
/>
|
||||
<span className={cn('text-xs', chosen ? 'font-medium text-primary' : 'text-muted-foreground')}>
|
||||
{c.name}
|
||||
</span>
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
{row.some((c) => c.id === expanded) && children.length > 0 && (
|
||||
<div className="my-3 grid grid-cols-5 gap-y-3 rounded-2xl bg-card p-3 shadow-sm">
|
||||
{children.map((c) => (
|
||||
<button key={c.id} onClick={() => setCategoryId(c.id)} className="flex flex-col items-center gap-1">
|
||||
<CategoryIcon
|
||||
category={c}
|
||||
className={cn('size-10', categoryId === c.id && 'bg-primary/15 ring-2 ring-primary')}
|
||||
/>
|
||||
<span
|
||||
className={cn(
|
||||
'line-clamp-1 text-[11px]',
|
||||
categoryId === c.id ? 'font-medium text-primary' : 'text-muted-foreground',
|
||||
)}
|
||||
>
|
||||
{c.name}
|
||||
</span>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
{i < rows.length - 1 && <div className="h-3" />}
|
||||
</Fragment>
|
||||
))}
|
||||
</div>
|
||||
|
||||
{/* Details + keypad */}
|
||||
<div className="pb-safe shrink-0 border-t bg-card">
|
||||
<div className="space-y-2 px-3 pt-2">
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="w-12 shrink-0 text-xs text-muted-foreground">谁花的</span>
|
||||
<div className="flex flex-wrap gap-1.5">
|
||||
{meta.members.map((m) => (
|
||||
<Chip key={m.id} active={memberIds.includes(m.id) && !isShared} color={m.color} onClick={() => setMemberIds([m.id])}>
|
||||
{m.name}
|
||||
</Chip>
|
||||
))}
|
||||
{allMembers.length > 1 && (
|
||||
<Chip active={isShared} onClick={() => { setShares(null); setMemberIds(allMembers); }}>
|
||||
共同
|
||||
</Chip>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
{type === 'expense' && (
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="w-12 shrink-0 text-xs text-muted-foreground">谁付的</span>
|
||||
<div className="flex flex-wrap gap-1.5">
|
||||
{meta.members.map((m) => (
|
||||
<Chip key={m.id} active={payerId === m.id} color={m.color} onClick={() => setPayerId(m.id)}>
|
||||
{m.name}
|
||||
</Chip>
|
||||
))}
|
||||
</div>
|
||||
{memberIds.length > 1 && (
|
||||
<button
|
||||
className="ml-auto text-xs text-primary"
|
||||
onClick={() =>
|
||||
setShares((s) =>
|
||||
s ? null : Object.fromEntries(memberIds.map((id) => [id, amount ? String(Math.round(amount / memberIds.length) / 100) : ''])),
|
||||
)
|
||||
}
|
||||
>
|
||||
{shares ? '改回平分' : '平分 · 修改'}
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
{shares && memberIds.length > 1 && (
|
||||
<div className="flex gap-2">
|
||||
{memberIds.map((id) => (
|
||||
<label key={id} className="flex flex-1 items-center gap-1 rounded-lg bg-muted px-2 py-1 text-xs">
|
||||
<span className="shrink-0" style={{ color: meta.member(id)?.color }}>{meta.member(id)?.name}</span>
|
||||
<input
|
||||
inputMode="decimal"
|
||||
value={shares[id] ?? ''}
|
||||
onChange={(e) => setShares({ ...shares, [id]: e.target.value })}
|
||||
className="w-full min-w-0 bg-transparent text-right outline-none"
|
||||
/>
|
||||
</label>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
<div className="flex items-center gap-2">
|
||||
<input
|
||||
type="datetime-local"
|
||||
value={toLocalInput(time)}
|
||||
onChange={(e) => e.target.value && setTime(fromLocalInput(e.target.value))}
|
||||
className="h-8 shrink-0 rounded-lg bg-muted px-2 text-xs outline-none"
|
||||
/>
|
||||
{meta.books.length > 1 && (
|
||||
<select
|
||||
value={bookId}
|
||||
onChange={(e) => setBookId(Number(e.target.value))}
|
||||
className="h-8 max-w-24 shrink-0 truncate rounded-lg bg-muted px-2 text-xs outline-none"
|
||||
>
|
||||
{meta.books.map((b) => <option key={b.id} value={b.id}>{b.name}</option>)}
|
||||
</select>
|
||||
)}
|
||||
{type === 'expense' && (
|
||||
<Chip active={excludeBudget} onClick={() => setExcludeBudget(!excludeBudget)}>不计预算</Chip>
|
||||
)}
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<input
|
||||
value={note}
|
||||
onChange={(e) => setNote(e.target.value)}
|
||||
placeholder="备注"
|
||||
maxLength={200}
|
||||
className="h-9 min-w-0 flex-1 rounded-lg bg-muted px-3 text-sm outline-none"
|
||||
/>
|
||||
<div className={cn('tabular shrink-0 text-right text-2xl font-semibold', type === 'expense' ? 'text-expense' : 'text-income')}>
|
||||
{expr ? (/[+-]/.test(expr.slice(1)) ? `${expr} = ${amount !== null ? money(amount) : '…'}` : expr) : '0'}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="mt-2 grid grid-cols-4 gap-px bg-border">
|
||||
{['1', '2', '3', 'back', '4', '5', '6', '+', '7', '8', '9', '-', '.', '0'].map((k) => (
|
||||
<button
|
||||
key={k}
|
||||
onClick={() => press(k)}
|
||||
className="flex h-12 items-center justify-center bg-card text-xl active:bg-muted"
|
||||
>
|
||||
{k === 'back' ? <Delete className="size-5" /> : k}
|
||||
</button>
|
||||
))}
|
||||
{bill ? (
|
||||
<div className="bg-card" />
|
||||
) : (
|
||||
<button
|
||||
onClick={() => save.mutate(true)}
|
||||
disabled={save.isPending}
|
||||
className="h-12 bg-card text-base active:bg-muted"
|
||||
>
|
||||
再记
|
||||
</button>
|
||||
)}
|
||||
<button
|
||||
onClick={() => save.mutate(false)}
|
||||
disabled={save.isPending}
|
||||
className="h-12 bg-primary text-base font-medium text-primary-foreground active:opacity-80"
|
||||
>
|
||||
{save.isPending ? '保存中' : '完成'}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<AlertDialog open={confirmDelete} onOpenChange={setConfirmDelete}>
|
||||
<AlertDialogContent>
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle>删除这笔账单?</AlertDialogTitle>
|
||||
</AlertDialogHeader>
|
||||
<AlertDialogFooter>
|
||||
<AlertDialogCancel>取消</AlertDialogCancel>
|
||||
<AlertDialogAction variant="destructive" onClick={() => remove.mutate()}>删除</AlertDialogAction>
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogContent>
|
||||
</AlertDialog>
|
||||
</SheetPage>
|
||||
);
|
||||
}
|
||||
|
||||
function Chip({
|
||||
active, color, onClick, children,
|
||||
}: { active: boolean; color?: string; onClick: () => void; children: React.ReactNode }) {
|
||||
return (
|
||||
<button
|
||||
onClick={onClick}
|
||||
className={cn(
|
||||
'h-7 rounded-full border px-3 text-xs transition-colors',
|
||||
active ? 'border-transparent font-medium text-white' : 'border-border text-muted-foreground',
|
||||
)}
|
||||
style={active ? { backgroundColor: color ?? 'var(--primary)' } : undefined}
|
||||
>
|
||||
{children}
|
||||
</button>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
import { useEditor } from '@/App';
|
||||
import type { Bill } from '@/lib/api';
|
||||
import { dayKey, dayLabel, money, timeLabel } from '@/lib/format';
|
||||
import { useMeta } from '@/lib/meta';
|
||||
import { cn } from '@/lib/utils';
|
||||
import { CategoryIcon } from './category-icon';
|
||||
import { MemberChips } from './member-chips';
|
||||
|
||||
// Bills grouped by day, with per-day expense/income totals.
|
||||
export function BillList({ bills, memberId }: { bills: Bill[]; memberId?: number | null }) {
|
||||
const groups: { key: string; time: number; bills: Bill[] }[] = [];
|
||||
for (const b of bills) {
|
||||
const key = dayKey(b.time);
|
||||
if (groups.at(-1)?.key !== key) groups.push({ key, time: b.time, bills: [] });
|
||||
groups.at(-1)!.bills.push(b);
|
||||
}
|
||||
|
||||
// When filtering by member, show that member's share instead of the whole bill.
|
||||
const amountOf = (b: Bill) => (memberId ? b.members.find((m) => m.memberId === memberId)?.share ?? 0 : b.amount);
|
||||
|
||||
return (
|
||||
<div className="space-y-3">
|
||||
{groups.map((g) => {
|
||||
const out = g.bills.filter((b) => b.type === 'expense').reduce((s, b) => s + amountOf(b), 0);
|
||||
const inc = g.bills.filter((b) => b.type === 'income').reduce((s, b) => s + amountOf(b), 0);
|
||||
return (
|
||||
<section key={g.key} className="overflow-hidden rounded-2xl bg-card shadow-sm">
|
||||
<header className="flex items-center justify-between px-4 pt-3 pb-1 text-xs text-muted-foreground">
|
||||
<span>{dayLabel(g.time)}</span>
|
||||
<span className="tabular space-x-2">
|
||||
{out > 0 && <span>支 {money(out)}</span>}
|
||||
{inc > 0 && <span>收 {money(inc)}</span>}
|
||||
</span>
|
||||
</header>
|
||||
{g.bills.map((b) => <BillRow key={b.id} bill={b} amount={amountOf(b)} />)}
|
||||
</section>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function BillRow({ bill, amount }: { bill: Bill; amount: number }) {
|
||||
const meta = useMeta();
|
||||
const editor = useEditor();
|
||||
const cat = meta.category(bill.categoryId);
|
||||
const payer = meta.member(bill.payerId);
|
||||
const shared = bill.members.length > 1;
|
||||
return (
|
||||
<button onClick={() => editor.open({ bill })} className="flex w-full items-center gap-3 px-4 py-2.5 text-left active:bg-muted">
|
||||
<CategoryIcon category={cat} />
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="flex items-center gap-1.5">
|
||||
<span className="truncate text-[15px]">{cat?.name ?? '未知'}</span>
|
||||
<MemberChips members={bill.members} />
|
||||
</div>
|
||||
<div className="truncate text-xs text-muted-foreground">
|
||||
{timeLabel(bill.time)}
|
||||
{shared && payer && <> · {payer.name}付</>}
|
||||
{bill.note && <> · {bill.note}</>}
|
||||
</div>
|
||||
</div>
|
||||
<span className={cn('tabular shrink-0 text-[15px] font-medium', bill.type === 'income' ? 'text-income' : 'text-foreground')}>
|
||||
{bill.type === 'income' ? '+' : '-'}
|
||||
{money(amount)}
|
||||
</span>
|
||||
</button>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
import { useState } from 'react';
|
||||
import { cn } from '@/lib/utils';
|
||||
import type { Category } from '@/lib/api';
|
||||
import { iconUrl, useIconStyle } from '@/lib/icon-style';
|
||||
|
||||
export function CategoryIcon({ category, className }: { category?: Category; className?: string }) {
|
||||
const style = useIconStyle();
|
||||
const icon = category?.icon;
|
||||
const [failed, setFailed] = useState<string | null>(null);
|
||||
const src = icon ? iconUrl(icon, style) : null;
|
||||
return (
|
||||
<span className={cn('inline-flex size-10 shrink-0 items-center justify-center rounded-2xl bg-muted', className)}>
|
||||
{src && failed !== src ? (
|
||||
<img
|
||||
src={src}
|
||||
alt=""
|
||||
className="size-[70%] object-contain"
|
||||
loading="lazy"
|
||||
draggable={false}
|
||||
onError={() => setFailed(src)}
|
||||
/>
|
||||
) : (
|
||||
<span className="text-sm font-medium text-muted-foreground">{category?.name.slice(0, 1) ?? '?'}</span>
|
||||
)}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
import { useMeta } from '@/lib/meta';
|
||||
import type { BillShare } from '@/lib/api';
|
||||
|
||||
// Small coloured name tags showing who a bill is for.
|
||||
export function MemberChips({ members, max = 3 }: { members: BillShare[]; max?: number }) {
|
||||
const meta = useMeta();
|
||||
if (members.length === meta.members.length && members.length > 1) {
|
||||
return <span className="rounded-full bg-amber-500/15 px-1.5 py-px text-[11px] text-amber-700 dark:text-amber-300">共同</span>;
|
||||
}
|
||||
return (
|
||||
<>
|
||||
{members.slice(0, max).map((s) => {
|
||||
const m = meta.member(s.memberId);
|
||||
if (!m) return null;
|
||||
return (
|
||||
<span
|
||||
key={s.memberId}
|
||||
className="rounded-full px-1.5 py-px text-[11px]"
|
||||
style={{ backgroundColor: `${m.color}22`, color: m.color }}
|
||||
>
|
||||
{m.name}
|
||||
</span>
|
||||
);
|
||||
})}
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
import { useState } from 'react';
|
||||
import { Check, ChevronDown, ChevronLeft, ChevronRight } from 'lucide-react';
|
||||
import { useMeta } from '@/lib/meta';
|
||||
import { monthKey, monthLabel, shiftMonth } from '@/lib/format';
|
||||
import { cn } from '@/lib/utils';
|
||||
import { Dialog, DialogContent, DialogHeader, DialogTitle } from './ui/dialog';
|
||||
|
||||
export function MonthSwitcher({ month, onChange }: { month: string; onChange: (m: string) => void }) {
|
||||
const isCurrent = month >= monthKey();
|
||||
return (
|
||||
<div className="flex items-center gap-1">
|
||||
<button className="p-1 text-muted-foreground" onClick={() => onChange(shiftMonth(month, -1))} aria-label="上个月">
|
||||
<ChevronLeft className="size-5" />
|
||||
</button>
|
||||
<span className="tabular min-w-24 text-center text-sm font-medium">{monthLabel(month)}</span>
|
||||
<button
|
||||
className="p-1 text-muted-foreground disabled:opacity-30"
|
||||
disabled={isCurrent}
|
||||
onClick={() => onChange(shiftMonth(month, 1))}
|
||||
aria-label="下个月"
|
||||
>
|
||||
<ChevronRight className="size-5" />
|
||||
</button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function YearSwitcher({ year, onChange }: { year: number; onChange: (y: number) => void }) {
|
||||
const current = new Date().getFullYear();
|
||||
return (
|
||||
<div className="flex items-center gap-1">
|
||||
<button className="p-1 text-muted-foreground" onClick={() => onChange(year - 1)} aria-label="上一年">
|
||||
<ChevronLeft className="size-5" />
|
||||
</button>
|
||||
<span className="tabular min-w-16 text-center text-sm font-medium">{year}年</span>
|
||||
<button
|
||||
className="p-1 text-muted-foreground disabled:opacity-30"
|
||||
disabled={year >= current}
|
||||
onClick={() => onChange(year + 1)}
|
||||
aria-label="下一年"
|
||||
>
|
||||
<ChevronRight className="size-5" />
|
||||
</button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function BookSwitcher() {
|
||||
const meta = useMeta();
|
||||
const [open, setOpen] = useState(false);
|
||||
const book = meta.books.find((b) => b.id === meta.bookId);
|
||||
return (
|
||||
<>
|
||||
<button className="flex items-center gap-0.5 text-base font-semibold" onClick={() => setOpen(true)}>
|
||||
{book?.name ?? '账本'}
|
||||
{meta.books.length > 1 && <ChevronDown className="size-4 text-muted-foreground" />}
|
||||
</button>
|
||||
<Dialog open={open && meta.books.length > 1} onOpenChange={setOpen}>
|
||||
<DialogContent className="max-w-xs">
|
||||
<DialogHeader>
|
||||
<DialogTitle>切换账本</DialogTitle>
|
||||
</DialogHeader>
|
||||
<div className="space-y-1">
|
||||
{meta.books.map((b) => (
|
||||
<button
|
||||
key={b.id}
|
||||
onClick={() => { meta.setBookId(b.id); setOpen(false); }}
|
||||
className={cn('flex w-full items-center justify-between rounded-lg px-3 py-2.5 text-left', b.id === meta.bookId && 'bg-muted')}
|
||||
>
|
||||
{b.name}
|
||||
{b.id === meta.bookId && <Check className="size-4 text-primary" />}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
// "全部 / dyc / 猪猪" filter.
|
||||
export function MemberFilter({ value, onChange }: { value: number | null; onChange: (id: number | null) => void }) {
|
||||
const meta = useMeta();
|
||||
const items = [{ id: null as number | null, name: '全部', color: '' }, ...meta.members];
|
||||
return (
|
||||
<div className="flex rounded-full bg-muted p-0.5 text-xs">
|
||||
{items.map((m) => (
|
||||
<button
|
||||
key={m.id ?? 0}
|
||||
onClick={() => onChange(m.id)}
|
||||
className={cn('rounded-full px-3 py-1 transition-colors', value === m.id && 'bg-card font-medium shadow-sm')}
|
||||
style={value === m.id && m.color ? { color: m.color } : undefined}
|
||||
>
|
||||
{m.name}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
import { useEffect, useState, type ReactNode } from 'react';
|
||||
import { createPortal } from 'react-dom';
|
||||
import { cn } from '@/lib/utils';
|
||||
|
||||
// A full-screen panel that slides up from the bottom. Used for forms that need
|
||||
// the whole phone screen (bill editor), where drag-to-dismiss would fight scrolling.
|
||||
export function SheetPage({ open, children, className }: { open: boolean; children: ReactNode; className?: string }) {
|
||||
const [mounted, setMounted] = useState(open);
|
||||
const [shown, setShown] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
if (open) {
|
||||
setMounted(true);
|
||||
const id = requestAnimationFrame(() => requestAnimationFrame(() => setShown(true)));
|
||||
return () => cancelAnimationFrame(id);
|
||||
}
|
||||
setShown(false);
|
||||
const t = setTimeout(() => setMounted(false), 250);
|
||||
return () => clearTimeout(t);
|
||||
}, [open]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!mounted) return;
|
||||
const prev = document.body.style.overflow;
|
||||
document.body.style.overflow = 'hidden';
|
||||
return () => { document.body.style.overflow = prev; };
|
||||
}, [mounted]);
|
||||
|
||||
if (!mounted) return null;
|
||||
return createPortal(
|
||||
<div
|
||||
className={cn(
|
||||
'fixed inset-0 z-50 flex flex-col bg-background transition-transform duration-250 ease-out',
|
||||
shown ? 'translate-y-0' : 'translate-y-full',
|
||||
className,
|
||||
)}
|
||||
>
|
||||
{children}
|
||||
</div>,
|
||||
document.body,
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,187 @@
|
||||
"use client"
|
||||
|
||||
import * as React from "react"
|
||||
import { AlertDialog as AlertDialogPrimitive } from "@base-ui/react/alert-dialog"
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
import { Button } from "@/components/ui/button"
|
||||
|
||||
function AlertDialog({ ...props }: AlertDialogPrimitive.Root.Props) {
|
||||
return <AlertDialogPrimitive.Root data-slot="alert-dialog" {...props} />
|
||||
}
|
||||
|
||||
function AlertDialogTrigger({ ...props }: AlertDialogPrimitive.Trigger.Props) {
|
||||
return (
|
||||
<AlertDialogPrimitive.Trigger data-slot="alert-dialog-trigger" {...props} />
|
||||
)
|
||||
}
|
||||
|
||||
function AlertDialogPortal({ ...props }: AlertDialogPrimitive.Portal.Props) {
|
||||
return (
|
||||
<AlertDialogPrimitive.Portal data-slot="alert-dialog-portal" {...props} />
|
||||
)
|
||||
}
|
||||
|
||||
function AlertDialogOverlay({
|
||||
className,
|
||||
...props
|
||||
}: AlertDialogPrimitive.Backdrop.Props) {
|
||||
return (
|
||||
<AlertDialogPrimitive.Backdrop
|
||||
data-slot="alert-dialog-overlay"
|
||||
className={cn(
|
||||
"fixed inset-0 isolate z-50 bg-black/10 duration-100 supports-backdrop-filter:backdrop-blur-xs data-open:animate-in data-open:fade-in-0 data-closed:animate-out data-closed:fade-out-0",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function AlertDialogContent({
|
||||
className,
|
||||
size = "default",
|
||||
...props
|
||||
}: AlertDialogPrimitive.Popup.Props & {
|
||||
size?: "default" | "sm"
|
||||
}) {
|
||||
return (
|
||||
<AlertDialogPortal>
|
||||
<AlertDialogOverlay />
|
||||
<AlertDialogPrimitive.Popup
|
||||
data-slot="alert-dialog-content"
|
||||
data-size={size}
|
||||
className={cn(
|
||||
"group/alert-dialog-content fixed top-1/2 left-1/2 z-50 grid w-full -translate-x-1/2 -translate-y-1/2 gap-4 rounded-xl bg-popover p-4 text-popover-foreground ring-1 ring-foreground/10 duration-100 outline-none data-[size=default]:max-w-xs data-[size=sm]:max-w-xs data-[size=default]:sm:max-w-sm data-open:animate-in data-open:fade-in-0 data-open:zoom-in-95 data-closed:animate-out data-closed:fade-out-0 data-closed:zoom-out-95",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
</AlertDialogPortal>
|
||||
)
|
||||
}
|
||||
|
||||
function AlertDialogHeader({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="alert-dialog-header"
|
||||
className={cn(
|
||||
"grid grid-rows-[auto_1fr] place-items-center gap-1.5 text-center has-data-[slot=alert-dialog-media]:grid-rows-[auto_auto_1fr] has-data-[slot=alert-dialog-media]:gap-x-4 sm:group-data-[size=default]/alert-dialog-content:place-items-start sm:group-data-[size=default]/alert-dialog-content:text-left sm:group-data-[size=default]/alert-dialog-content:has-data-[slot=alert-dialog-media]:grid-rows-[auto_1fr]",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function AlertDialogFooter({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="alert-dialog-footer"
|
||||
className={cn(
|
||||
"-mx-4 -mb-4 flex flex-col-reverse gap-2 rounded-b-xl border-t bg-muted/50 p-4 group-data-[size=sm]/alert-dialog-content:grid group-data-[size=sm]/alert-dialog-content:grid-cols-2 sm:flex-row sm:justify-end",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function AlertDialogMedia({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="alert-dialog-media"
|
||||
className={cn(
|
||||
"mb-2 inline-flex size-10 items-center justify-center rounded-md bg-muted sm:group-data-[size=default]/alert-dialog-content:row-span-2 *:[svg:not([class*='size-'])]:size-6",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function AlertDialogTitle({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof AlertDialogPrimitive.Title>) {
|
||||
return (
|
||||
<AlertDialogPrimitive.Title
|
||||
data-slot="alert-dialog-title"
|
||||
className={cn(
|
||||
"font-heading text-base font-medium sm:group-data-[size=default]/alert-dialog-content:group-has-data-[slot=alert-dialog-media]/alert-dialog-content:col-start-2",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function AlertDialogDescription({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof AlertDialogPrimitive.Description>) {
|
||||
return (
|
||||
<AlertDialogPrimitive.Description
|
||||
data-slot="alert-dialog-description"
|
||||
className={cn(
|
||||
"text-sm text-balance text-muted-foreground md:text-pretty *:[a]:underline *:[a]:underline-offset-3 *:[a]:hover:text-foreground",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function AlertDialogAction({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof Button>) {
|
||||
return (
|
||||
<Button
|
||||
data-slot="alert-dialog-action"
|
||||
className={cn(className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function AlertDialogCancel({
|
||||
className,
|
||||
variant = "outline",
|
||||
size = "default",
|
||||
...props
|
||||
}: AlertDialogPrimitive.Close.Props &
|
||||
Pick<React.ComponentProps<typeof Button>, "variant" | "size">) {
|
||||
return (
|
||||
<AlertDialogPrimitive.Close
|
||||
data-slot="alert-dialog-cancel"
|
||||
className={cn(className)}
|
||||
render={<Button variant={variant} size={size} />}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export {
|
||||
AlertDialog,
|
||||
AlertDialogAction,
|
||||
AlertDialogCancel,
|
||||
AlertDialogContent,
|
||||
AlertDialogDescription,
|
||||
AlertDialogFooter,
|
||||
AlertDialogHeader,
|
||||
AlertDialogMedia,
|
||||
AlertDialogOverlay,
|
||||
AlertDialogPortal,
|
||||
AlertDialogTitle,
|
||||
AlertDialogTrigger,
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
import { mergeProps } from "@base-ui/react/merge-props"
|
||||
import { useRender } from "@base-ui/react/use-render"
|
||||
import { cva, type VariantProps } from "class-variance-authority"
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
const badgeVariants = cva(
|
||||
"group/badge inline-flex h-5 w-fit shrink-0 items-center justify-center gap-1 overflow-hidden rounded-4xl border border-transparent px-2 py-0.5 text-xs font-medium whitespace-nowrap transition-all focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 has-data-[icon=inline-end]:pr-1.5 has-data-[icon=inline-start]:pl-1.5 aria-invalid:border-destructive aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 [&>svg]:pointer-events-none [&>svg]:size-3!",
|
||||
{
|
||||
variants: {
|
||||
variant: {
|
||||
default: "bg-primary text-primary-foreground [a]:hover:bg-primary/80",
|
||||
secondary:
|
||||
"bg-secondary text-secondary-foreground [a]:hover:bg-secondary/80",
|
||||
destructive:
|
||||
"bg-destructive/10 text-destructive focus-visible:ring-destructive/20 dark:bg-destructive/20 dark:focus-visible:ring-destructive/40 [a]:hover:bg-destructive/20",
|
||||
outline:
|
||||
"border-border text-foreground [a]:hover:bg-muted [a]:hover:text-muted-foreground",
|
||||
ghost:
|
||||
"hover:bg-muted hover:text-muted-foreground dark:hover:bg-muted/50",
|
||||
link: "text-primary underline-offset-4 hover:underline",
|
||||
},
|
||||
},
|
||||
defaultVariants: {
|
||||
variant: "default",
|
||||
},
|
||||
}
|
||||
)
|
||||
|
||||
function Badge({
|
||||
className,
|
||||
variant = "default",
|
||||
render,
|
||||
...props
|
||||
}: useRender.ComponentProps<"span"> & VariantProps<typeof badgeVariants>) {
|
||||
return useRender({
|
||||
defaultTagName: "span",
|
||||
props: mergeProps<"span">(
|
||||
{
|
||||
className: cn(badgeVariants({ variant }), className),
|
||||
},
|
||||
props
|
||||
),
|
||||
render,
|
||||
state: {
|
||||
slot: "badge",
|
||||
variant,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
export { Badge, badgeVariants }
|
||||
@@ -0,0 +1,57 @@
|
||||
import { Button as ButtonPrimitive } from "@base-ui/react/button"
|
||||
import { cva, type VariantProps } from "class-variance-authority"
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
const buttonVariants = cva(
|
||||
"group/button inline-flex shrink-0 items-center justify-center rounded-lg border border-transparent bg-clip-padding text-sm font-medium whitespace-nowrap transition-all outline-none select-none focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 active:not-aria-[haspopup]:translate-y-px disabled:pointer-events-none disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-3 aria-invalid:ring-destructive/20 dark:aria-invalid:border-destructive/50 dark:aria-invalid:ring-destructive/40 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
|
||||
{
|
||||
variants: {
|
||||
variant: {
|
||||
default: "bg-primary text-primary-foreground hover:bg-primary/80",
|
||||
outline:
|
||||
"border-border bg-background hover:bg-muted hover:text-foreground aria-expanded:bg-muted aria-expanded:text-foreground dark:border-input dark:bg-input/30 dark:hover:bg-input/50",
|
||||
secondary:
|
||||
"bg-secondary text-secondary-foreground hover:bg-[color-mix(in_oklch,var(--secondary),var(--foreground)_5%)] aria-expanded:bg-secondary aria-expanded:text-secondary-foreground",
|
||||
ghost:
|
||||
"hover:bg-muted hover:text-foreground aria-expanded:bg-muted aria-expanded:text-foreground dark:hover:bg-muted/50",
|
||||
destructive:
|
||||
"bg-destructive/10 text-destructive hover:bg-destructive/20 focus-visible:border-destructive/40 focus-visible:ring-destructive/20 dark:bg-destructive/20 dark:hover:bg-destructive/30 dark:focus-visible:ring-destructive/40",
|
||||
link: "text-primary underline-offset-4 hover:underline",
|
||||
},
|
||||
size: {
|
||||
default:
|
||||
"h-8 gap-1.5 px-2.5 has-data-[icon=inline-end]:pr-2 has-data-[icon=inline-start]:pl-2",
|
||||
xs: "h-6 gap-1 rounded-[min(var(--radius-md),10px)] px-2 text-xs in-data-[slot=button-group]:rounded-lg has-data-[icon=inline-end]:pr-1.5 has-data-[icon=inline-start]:pl-1.5 [&_svg:not([class*='size-'])]:size-3",
|
||||
sm: "h-7 gap-1 rounded-[min(var(--radius-md),12px)] px-2.5 text-[0.8rem] in-data-[slot=button-group]:rounded-lg has-data-[icon=inline-end]:pr-1.5 has-data-[icon=inline-start]:pl-1.5 [&_svg:not([class*='size-'])]:size-3.5",
|
||||
lg: "h-9 gap-1.5 px-2.5 has-data-[icon=inline-end]:pr-2 has-data-[icon=inline-start]:pl-2",
|
||||
icon: "size-8",
|
||||
"icon-xs":
|
||||
"size-6 rounded-[min(var(--radius-md),10px)] in-data-[slot=button-group]:rounded-lg [&_svg:not([class*='size-'])]:size-3",
|
||||
"icon-sm":
|
||||
"size-7 rounded-[min(var(--radius-md),12px)] in-data-[slot=button-group]:rounded-lg",
|
||||
"icon-lg": "size-9",
|
||||
},
|
||||
},
|
||||
defaultVariants: {
|
||||
variant: "default",
|
||||
size: "default",
|
||||
},
|
||||
}
|
||||
)
|
||||
|
||||
function Button({
|
||||
className,
|
||||
variant = "default",
|
||||
size = "default",
|
||||
...props
|
||||
}: ButtonPrimitive.Props & VariantProps<typeof buttonVariants>) {
|
||||
return (
|
||||
<ButtonPrimitive
|
||||
data-slot="button"
|
||||
className={cn(buttonVariants({ variant, size, className }))}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export { Button, buttonVariants }
|
||||
@@ -0,0 +1,102 @@
|
||||
import * as React from "react"
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
function Card({
|
||||
className,
|
||||
size = "default",
|
||||
...props
|
||||
}: React.ComponentProps<"div"> & { size?: "default" | "sm" }) {
|
||||
return (
|
||||
<div
|
||||
data-slot="card"
|
||||
data-size={size}
|
||||
className={cn(
|
||||
"group/card flex flex-col gap-(--card-spacing) overflow-hidden rounded-xl bg-card py-(--card-spacing) text-sm text-card-foreground ring-1 ring-foreground/10 [--card-spacing:--spacing(4)] has-data-[slot=card-footer]:pb-0 has-[>img:first-child]:pt-0 data-[size=sm]:[--card-spacing:--spacing(3)] data-[size=sm]:has-data-[slot=card-footer]:pb-0 *:[img:first-child]:rounded-t-xl *:[img:last-child]:rounded-b-xl",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function CardHeader({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="card-header"
|
||||
className={cn(
|
||||
"group/card-header @container/card-header grid auto-rows-min items-start gap-1 rounded-t-xl px-(--card-spacing) has-data-[slot=card-action]:grid-cols-[1fr_auto] has-data-[slot=card-description]:grid-rows-[auto_auto] [.border-b]:pb-(--card-spacing)",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function CardTitle({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="card-title"
|
||||
className={cn(
|
||||
"font-heading text-base leading-snug font-medium group-data-[size=sm]/card:text-sm",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function CardDescription({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="card-description"
|
||||
className={cn("text-sm text-muted-foreground", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function CardAction({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="card-action"
|
||||
className={cn(
|
||||
"col-start-2 row-span-2 row-start-1 self-start justify-self-end",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function CardContent({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="card-content"
|
||||
className={cn("px-(--card-spacing)", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function CardFooter({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="card-footer"
|
||||
className={cn(
|
||||
"flex items-center rounded-b-xl border-t bg-muted/50 p-(--card-spacing)",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export {
|
||||
Card,
|
||||
CardHeader,
|
||||
CardFooter,
|
||||
CardTitle,
|
||||
CardAction,
|
||||
CardDescription,
|
||||
CardContent,
|
||||
}
|
||||
@@ -0,0 +1,158 @@
|
||||
import * as React from "react"
|
||||
import { Dialog as DialogPrimitive } from "@base-ui/react/dialog"
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { XIcon } from "lucide-react"
|
||||
|
||||
function Dialog({ ...props }: DialogPrimitive.Root.Props) {
|
||||
return <DialogPrimitive.Root data-slot="dialog" {...props} />
|
||||
}
|
||||
|
||||
function DialogTrigger({ ...props }: DialogPrimitive.Trigger.Props) {
|
||||
return <DialogPrimitive.Trigger data-slot="dialog-trigger" {...props} />
|
||||
}
|
||||
|
||||
function DialogPortal({ ...props }: DialogPrimitive.Portal.Props) {
|
||||
return <DialogPrimitive.Portal data-slot="dialog-portal" {...props} />
|
||||
}
|
||||
|
||||
function DialogClose({ ...props }: DialogPrimitive.Close.Props) {
|
||||
return <DialogPrimitive.Close data-slot="dialog-close" {...props} />
|
||||
}
|
||||
|
||||
function DialogOverlay({
|
||||
className,
|
||||
...props
|
||||
}: DialogPrimitive.Backdrop.Props) {
|
||||
return (
|
||||
<DialogPrimitive.Backdrop
|
||||
data-slot="dialog-overlay"
|
||||
className={cn(
|
||||
"fixed inset-0 isolate z-50 bg-black/10 duration-100 supports-backdrop-filter:backdrop-blur-xs data-open:animate-in data-open:fade-in-0 data-closed:animate-out data-closed:fade-out-0",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function DialogContent({
|
||||
className,
|
||||
children,
|
||||
showCloseButton = true,
|
||||
...props
|
||||
}: DialogPrimitive.Popup.Props & {
|
||||
showCloseButton?: boolean
|
||||
}) {
|
||||
return (
|
||||
<DialogPortal>
|
||||
<DialogOverlay />
|
||||
<DialogPrimitive.Popup
|
||||
data-slot="dialog-content"
|
||||
className={cn(
|
||||
"fixed top-1/2 left-1/2 z-50 grid w-full max-w-[calc(100%-2rem)] -translate-x-1/2 -translate-y-1/2 gap-4 rounded-xl bg-popover p-4 text-sm text-popover-foreground ring-1 ring-foreground/10 duration-100 outline-none sm:max-w-sm data-open:animate-in data-open:fade-in-0 data-open:zoom-in-95 data-closed:animate-out data-closed:fade-out-0 data-closed:zoom-out-95",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
{children}
|
||||
{showCloseButton && (
|
||||
<DialogPrimitive.Close
|
||||
data-slot="dialog-close"
|
||||
render={
|
||||
<Button
|
||||
variant="ghost"
|
||||
className="absolute top-2 right-2"
|
||||
size="icon-sm"
|
||||
/>
|
||||
}
|
||||
>
|
||||
<XIcon
|
||||
/>
|
||||
<span className="sr-only">Close</span>
|
||||
</DialogPrimitive.Close>
|
||||
)}
|
||||
</DialogPrimitive.Popup>
|
||||
</DialogPortal>
|
||||
)
|
||||
}
|
||||
|
||||
function DialogHeader({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="dialog-header"
|
||||
className={cn("flex flex-col gap-2", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function DialogFooter({
|
||||
className,
|
||||
showCloseButton = false,
|
||||
children,
|
||||
...props
|
||||
}: React.ComponentProps<"div"> & {
|
||||
showCloseButton?: boolean
|
||||
}) {
|
||||
return (
|
||||
<div
|
||||
data-slot="dialog-footer"
|
||||
className={cn(
|
||||
"-mx-4 -mb-4 flex flex-col-reverse gap-2 rounded-b-xl border-t bg-muted/50 p-4 sm:flex-row sm:justify-end",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
{children}
|
||||
{showCloseButton && (
|
||||
<DialogPrimitive.Close render={<Button variant="outline" />}>
|
||||
Close
|
||||
</DialogPrimitive.Close>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function DialogTitle({ className, ...props }: DialogPrimitive.Title.Props) {
|
||||
return (
|
||||
<DialogPrimitive.Title
|
||||
data-slot="dialog-title"
|
||||
className={cn(
|
||||
"font-heading text-base leading-none font-medium",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function DialogDescription({
|
||||
className,
|
||||
...props
|
||||
}: DialogPrimitive.Description.Props) {
|
||||
return (
|
||||
<DialogPrimitive.Description
|
||||
data-slot="dialog-description"
|
||||
className={cn(
|
||||
"text-sm text-muted-foreground *:[a]:underline *:[a]:underline-offset-3 *:[a]:hover:text-foreground",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export {
|
||||
Dialog,
|
||||
DialogClose,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogOverlay,
|
||||
DialogPortal,
|
||||
DialogTitle,
|
||||
DialogTrigger,
|
||||
}
|
||||
@@ -0,0 +1,227 @@
|
||||
"use client"
|
||||
|
||||
import * as React from "react"
|
||||
import { Drawer as DrawerPrimitive } from "@base-ui/react/drawer"
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
type DrawerContextProps = {
|
||||
hasSnapPoints: boolean
|
||||
modal: DrawerPrimitive.Root.Props["modal"]
|
||||
showSwipeHandle: boolean
|
||||
swipeDirection: NonNullable<DrawerPrimitive.Root.Props["swipeDirection"]>
|
||||
}
|
||||
|
||||
const DrawerContext = React.createContext<DrawerContextProps | null>(null)
|
||||
|
||||
function useDrawer() {
|
||||
const context = React.useContext(DrawerContext)
|
||||
|
||||
if (!context) {
|
||||
throw new Error("useDrawer must be used within a Drawer.")
|
||||
}
|
||||
|
||||
return context
|
||||
}
|
||||
|
||||
function Drawer({
|
||||
modal = true,
|
||||
showSwipeHandle = false,
|
||||
snapPoints,
|
||||
swipeDirection = "down",
|
||||
...props
|
||||
}: DrawerPrimitive.Root.Props & {
|
||||
showSwipeHandle?: boolean
|
||||
}) {
|
||||
const hasSnapPoints = snapPoints != null && snapPoints.length > 0
|
||||
const contextValue = React.useMemo(
|
||||
() => ({ hasSnapPoints, modal, showSwipeHandle, swipeDirection }),
|
||||
[hasSnapPoints, modal, showSwipeHandle, swipeDirection]
|
||||
)
|
||||
|
||||
return (
|
||||
<DrawerContext.Provider value={contextValue}>
|
||||
<DrawerPrimitive.Root
|
||||
data-slot="drawer"
|
||||
modal={modal}
|
||||
snapPoints={snapPoints}
|
||||
swipeDirection={swipeDirection}
|
||||
{...props}
|
||||
/>
|
||||
</DrawerContext.Provider>
|
||||
)
|
||||
}
|
||||
|
||||
function DrawerTrigger({ ...props }: DrawerPrimitive.Trigger.Props) {
|
||||
return <DrawerPrimitive.Trigger data-slot="drawer-trigger" {...props} />
|
||||
}
|
||||
|
||||
function DrawerPortal({ ...props }: DrawerPrimitive.Portal.Props) {
|
||||
return <DrawerPrimitive.Portal data-slot="drawer-portal" {...props} />
|
||||
}
|
||||
|
||||
function DrawerClose({ ...props }: DrawerPrimitive.Close.Props) {
|
||||
return <DrawerPrimitive.Close data-slot="drawer-close" {...props} />
|
||||
}
|
||||
|
||||
function DrawerOverlay({
|
||||
className,
|
||||
...props
|
||||
}: DrawerPrimitive.Backdrop.Props) {
|
||||
return (
|
||||
<DrawerPrimitive.Backdrop
|
||||
data-slot="drawer-overlay"
|
||||
className={cn(
|
||||
"fixed inset-0 z-50 min-h-dvh bg-black/10 opacity-[max(var(--drawer-overlay-min-opacity,0),calc(1-var(--drawer-swipe-progress)))] transition-opacity duration-450 ease-[cubic-bezier(0.32,0.72,0,1)] select-none data-ending-style:pointer-events-none data-ending-style:opacity-0 data-ending-style:duration-[calc(var(--drawer-swipe-strength)*400ms)] data-snap-points:[--drawer-overlay-min-opacity:0.5] data-starting-style:opacity-0 data-swiping:duration-0 supports-backdrop-filter:backdrop-blur-xs supports-[-webkit-touch-callout:none]:absolute",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function DrawerSwipeHandle({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="drawer-swipe-handle"
|
||||
aria-hidden="true"
|
||||
className={cn(
|
||||
"relative z-10 flex shrink-0 cursor-grab transition-opacity duration-200 group-data-nested-drawer-open/drawer-popup:opacity-0 group-data-nested-drawer-swiping/drawer-popup:opacity-100 group-data-[swipe-axis=x]/drawer-popup:h-full group-data-[swipe-axis=x]/drawer-popup:w-3 group-data-[swipe-axis=x]/drawer-popup:items-center group-data-[swipe-axis=y]/drawer-popup:h-3 group-data-[swipe-axis=y]/drawer-popup:w-full group-data-[swipe-axis=y]/drawer-popup:justify-center group-data-[swipe-direction=down]/drawer-popup:items-end group-data-[swipe-direction=left]/drawer-popup:order-last group-data-[swipe-direction=left]/drawer-popup:justify-start group-data-[swipe-direction=right]/drawer-popup:justify-end group-data-[swipe-direction=up]/drawer-popup:order-last group-data-[swipe-direction=up]/drawer-popup:items-start after:block after:shrink-0 after:rounded-full after:bg-muted group-data-[swipe-axis=x]/drawer-popup:after:h-24 group-data-[swipe-axis=x]/drawer-popup:after:w-1 group-data-[swipe-axis=y]/drawer-popup:after:h-1 group-data-[swipe-axis=y]/drawer-popup:after:w-24 active:cursor-grabbing",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function DrawerContent({
|
||||
className,
|
||||
children,
|
||||
...props
|
||||
}: DrawerPrimitive.Popup.Props) {
|
||||
const { hasSnapPoints, modal, showSwipeHandle, swipeDirection } = useDrawer()
|
||||
const swipeAxis =
|
||||
swipeDirection === "down" || swipeDirection === "up" ? "y" : "x"
|
||||
|
||||
return (
|
||||
<DrawerPortal data-slot="drawer-portal">
|
||||
{modal === true && (
|
||||
<DrawerOverlay data-snap-points={hasSnapPoints ? "" : undefined} />
|
||||
)}
|
||||
<DrawerPrimitive.Viewport
|
||||
data-slot="drawer-viewport"
|
||||
data-modal={modal}
|
||||
className="pointer-events-none fixed inset-0 z-50 select-none data-[modal=true]:pointer-events-auto"
|
||||
>
|
||||
<DrawerPrimitive.Popup
|
||||
data-slot="drawer-popup"
|
||||
data-swipe-axis={swipeAxis}
|
||||
data-snap-points={hasSnapPoints ? "" : undefined}
|
||||
className={cn(
|
||||
// Base.
|
||||
"group/drawer-popup pointer-events-auto fixed z-50 m-(--drawer-inset,0px) flex h-(--drawer-content-height) max-h-(--drawer-content-max-height,none) min-h-0 w-(--drawer-content-width,auto) transform-[translate3d(var(--translate-x,0px),var(--translate-y,0px),0)_scale(var(--stack-scale))] flex-col bg-popover text-sm text-popover-foreground transition-[transform,height,opacity,filter] duration-450 ease-[cubic-bezier(0.22,1,0.36,1)] will-change-transform outline-none select-none [interpolate-size:allow-keywords] data-[swipe-direction=down]:rounded-t-xl data-[swipe-direction=down]:border-t data-[swipe-direction=left]:rounded-r-xl data-[swipe-direction=left]:border-r data-[swipe-direction=right]:rounded-l-xl data-[swipe-direction=right]:border-l data-[swipe-direction=up]:rounded-b-xl data-[swipe-direction=up]:border-b",
|
||||
// Nested.
|
||||
"data-nested-drawer-open:overflow-hidden data-nested-drawer-open:brightness-95",
|
||||
// Bleed.
|
||||
"after:pointer-events-none after:absolute after:bg-(--drawer-bleed-background,var(--color-popover)) data-[swipe-axis=x]:after:inset-y-0 data-[swipe-axis=x]:after:w-(--bleed) data-[swipe-axis=y]:after:inset-x-0 data-[swipe-axis=y]:after:h-(--bleed) data-[swipe-direction=down]:after:top-full data-[swipe-direction=left]:after:right-full data-[swipe-direction=right]:after:left-full data-[swipe-direction=up]:after:bottom-full",
|
||||
// Sizing.
|
||||
"[--drawer-content-height:var(--drawer-height,auto)] data-[swipe-axis=x]:[--drawer-content-width:75%] data-[swipe-axis=y]:[--drawer-content-max-height:calc(100dvh-6rem)] data-[swipe-axis=y]:data-snap-points:[--drawer-content-height:100dvh] data-[swipe-axis=x]:sm:[--drawer-content-width:24rem]",
|
||||
// Stack.
|
||||
"[--bleed:3rem] [--peek:1rem] [--stack-height:var(--drawer-frontmost-height,var(--drawer-height,0px))] [--stack-peek-offset:max(0px,calc((var(--nested-drawers)-var(--stack-progress))*var(--peek)))] [--stack-progress:clamp(0,var(--drawer-swipe-progress),1)] [--stack-scale-base:max(0,calc(1-(var(--nested-drawers)*var(--stack-step))))] [--stack-scale:clamp(0,calc(var(--stack-scale-base)+(var(--stack-step)*var(--stack-progress))),1)] [--stack-shrink:calc(1-var(--stack-scale))] [--stack-step:0.05]",
|
||||
// Transitions.
|
||||
"data-ending-style:transform-(--closed-transform) data-ending-style:opacity-[0.9999] data-ending-style:duration-[calc(var(--drawer-swipe-strength)*400ms)] data-nested-drawer-swiping:duration-0 data-ending-style:data-nested-drawer-swiping:duration-[calc(var(--drawer-swipe-strength)*400ms)] data-starting-style:transform-(--closed-transform) data-swiping:duration-0 data-ending-style:data-swiping:duration-[calc(var(--drawer-swipe-strength)*400ms)]",
|
||||
// Axis: y.
|
||||
"data-[swipe-axis=y]:inset-x-0 data-[swipe-axis=y]:data-nested-drawer-open:h-(--stack-height)",
|
||||
// Axis: x.
|
||||
"data-[swipe-axis=x]:inset-y-0 data-[swipe-axis=x]:flex-row",
|
||||
// Direction: down.
|
||||
"data-[swipe-direction=down]:bottom-0 data-[swipe-direction=down]:origin-bottom data-[swipe-direction=down]:[--closed-transform:translate3d(0,calc(100%+var(--drawer-inset,0px)+2px),0)] data-[swipe-direction=down]:[--translate-y:calc(var(--drawer-snap-point-offset,0px)+var(--drawer-swipe-movement-y)-var(--stack-peek-offset)-(var(--stack-shrink)*var(--stack-height)))]",
|
||||
// Direction: up.
|
||||
"data-[swipe-direction=up]:top-0 data-[swipe-direction=up]:origin-top data-[swipe-direction=up]:[--closed-transform:translate3d(0,calc(-100%-var(--drawer-inset,0px)-2px),0)] data-[swipe-direction=up]:[--translate-y:calc(var(--drawer-snap-point-offset,0px)+var(--drawer-swipe-movement-y)+var(--stack-peek-offset)+(var(--stack-shrink)*var(--stack-height)))]",
|
||||
// Direction: left.
|
||||
"data-[swipe-direction=left]:left-0 data-[swipe-direction=left]:origin-left data-[swipe-direction=left]:[--closed-transform:translate3d(calc(-100%-var(--drawer-inset,0px)-2px),0,0)] data-[swipe-direction=left]:[--translate-x:calc(var(--drawer-swipe-movement-x)+var(--stack-peek-offset)+(var(--stack-shrink)*100%))]",
|
||||
// Direction: right.
|
||||
"data-[swipe-direction=right]:right-0 data-[swipe-direction=right]:origin-right data-[swipe-direction=right]:[--closed-transform:translate3d(calc(100%+var(--drawer-inset,0px)+2px),0,0)] data-[swipe-direction=right]:[--translate-x:calc(var(--drawer-swipe-movement-x)-var(--stack-peek-offset)-(var(--stack-shrink)*100%))]",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
{showSwipeHandle && <DrawerSwipeHandle />}
|
||||
<DrawerPrimitive.Content
|
||||
data-slot="drawer-content"
|
||||
className={cn(
|
||||
"flex min-h-0 flex-1 flex-col overflow-hidden overscroll-contain rounded-[inherit] transition-opacity duration-300 ease-[cubic-bezier(0.45,1.005,0,1.005)] select-text group-data-nested-drawer-open/drawer-popup:opacity-0 group-data-nested-drawer-swiping/drawer-popup:opacity-100 group-data-swiping/drawer-popup:select-none"
|
||||
)}
|
||||
>
|
||||
{children}
|
||||
</DrawerPrimitive.Content>
|
||||
</DrawerPrimitive.Popup>
|
||||
</DrawerPrimitive.Viewport>
|
||||
</DrawerPortal>
|
||||
)
|
||||
}
|
||||
|
||||
function DrawerHeader({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="drawer-header"
|
||||
className={cn(
|
||||
"flex shrink-0 flex-col gap-0.5 p-4 pb-0 group-data-[swipe-axis=y]/drawer-popup:text-center md:gap-0.5 md:text-left",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function DrawerFooter({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="drawer-footer"
|
||||
className={cn("mt-auto flex shrink-0 flex-col gap-2 p-4 pt-0", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function DrawerTitle({ className, ...props }: DrawerPrimitive.Title.Props) {
|
||||
return (
|
||||
<DrawerPrimitive.Title
|
||||
data-slot="drawer-title"
|
||||
className={cn(
|
||||
"font-heading text-base font-medium text-foreground",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function DrawerDescription({
|
||||
className,
|
||||
...props
|
||||
}: DrawerPrimitive.Description.Props) {
|
||||
return (
|
||||
<DrawerPrimitive.Description
|
||||
data-slot="drawer-description"
|
||||
className={cn("text-sm text-balance text-muted-foreground", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export {
|
||||
Drawer,
|
||||
DrawerPortal,
|
||||
DrawerOverlay,
|
||||
DrawerSwipeHandle,
|
||||
DrawerTrigger,
|
||||
DrawerClose,
|
||||
DrawerContent,
|
||||
DrawerHeader,
|
||||
DrawerFooter,
|
||||
DrawerTitle,
|
||||
DrawerDescription,
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
import * as React from "react"
|
||||
import { Input as InputPrimitive } from "@base-ui/react/input"
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
function Input({ className, type, ...props }: React.ComponentProps<"input">) {
|
||||
return (
|
||||
<InputPrimitive
|
||||
type={type}
|
||||
data-slot="input"
|
||||
className={cn(
|
||||
"h-8 w-full min-w-0 rounded-lg border border-input bg-transparent px-2.5 py-1 text-base transition-colors outline-none file:inline-flex file:h-6 file:border-0 file:bg-transparent file:text-sm file:font-medium file:text-foreground placeholder:text-muted-foreground focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 disabled:pointer-events-none disabled:cursor-not-allowed disabled:bg-input/50 disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-3 aria-invalid:ring-destructive/20 md:text-sm dark:bg-input/30 dark:disabled:bg-input/80 dark:aria-invalid:border-destructive/50 dark:aria-invalid:ring-destructive/40",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export { Input }
|
||||
@@ -0,0 +1,17 @@
|
||||
import * as React from "react"
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
function Label({ className, ...props }: React.ComponentProps<"label">) {
|
||||
return (
|
||||
<label
|
||||
data-slot="label"
|
||||
className={cn(
|
||||
"flex items-center gap-2 text-sm leading-none font-medium select-none group-data-[disabled=true]:pointer-events-none group-data-[disabled=true]:opacity-50 peer-disabled:cursor-not-allowed peer-disabled:opacity-50",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export { Label }
|
||||
@@ -0,0 +1,82 @@
|
||||
"use client"
|
||||
|
||||
import { Progress as ProgressPrimitive } from "@base-ui/react/progress"
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
function Progress({
|
||||
className,
|
||||
children,
|
||||
value,
|
||||
...props
|
||||
}: ProgressPrimitive.Root.Props) {
|
||||
return (
|
||||
<ProgressPrimitive.Root
|
||||
value={value}
|
||||
data-slot="progress"
|
||||
className={cn("flex flex-wrap gap-3", className)}
|
||||
{...props}
|
||||
>
|
||||
{children}
|
||||
<ProgressTrack>
|
||||
<ProgressIndicator />
|
||||
</ProgressTrack>
|
||||
</ProgressPrimitive.Root>
|
||||
)
|
||||
}
|
||||
|
||||
function ProgressTrack({ className, ...props }: ProgressPrimitive.Track.Props) {
|
||||
return (
|
||||
<ProgressPrimitive.Track
|
||||
className={cn(
|
||||
"relative flex h-1 w-full items-center overflow-x-hidden rounded-full bg-muted",
|
||||
className
|
||||
)}
|
||||
data-slot="progress-track"
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function ProgressIndicator({
|
||||
className,
|
||||
...props
|
||||
}: ProgressPrimitive.Indicator.Props) {
|
||||
return (
|
||||
<ProgressPrimitive.Indicator
|
||||
data-slot="progress-indicator"
|
||||
className={cn("h-full bg-primary transition-all", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function ProgressLabel({ className, ...props }: ProgressPrimitive.Label.Props) {
|
||||
return (
|
||||
<ProgressPrimitive.Label
|
||||
className={cn("text-sm font-medium", className)}
|
||||
data-slot="progress-label"
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function ProgressValue({ className, ...props }: ProgressPrimitive.Value.Props) {
|
||||
return (
|
||||
<ProgressPrimitive.Value
|
||||
className={cn(
|
||||
"ml-auto text-sm text-muted-foreground tabular-nums",
|
||||
className
|
||||
)}
|
||||
data-slot="progress-value"
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export {
|
||||
Progress,
|
||||
ProgressTrack,
|
||||
ProgressIndicator,
|
||||
ProgressLabel,
|
||||
ProgressValue,
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
import { Separator as SeparatorPrimitive } from "@base-ui/react/separator"
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
function Separator({
|
||||
className,
|
||||
orientation = "horizontal",
|
||||
...props
|
||||
}: SeparatorPrimitive.Props) {
|
||||
return (
|
||||
<SeparatorPrimitive
|
||||
data-slot="separator"
|
||||
orientation={orientation}
|
||||
className={cn(
|
||||
"shrink-0 bg-border data-horizontal:h-px data-horizontal:w-full data-vertical:w-px data-vertical:self-stretch",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export { Separator }
|
||||
@@ -0,0 +1,13 @@
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
function Skeleton({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="skeleton"
|
||||
className={cn("animate-pulse rounded-md bg-muted", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export { Skeleton }
|
||||
@@ -0,0 +1,46 @@
|
||||
import { Toaster as Sonner, type ToasterProps } from "sonner"
|
||||
import { CircleCheckIcon, InfoIcon, TriangleAlertIcon, OctagonXIcon, Loader2Icon } from "lucide-react"
|
||||
|
||||
const Toaster = ({ ...props }: ToasterProps) => {
|
||||
|
||||
|
||||
return (
|
||||
<Sonner
|
||||
theme="system"
|
||||
className="toaster group"
|
||||
icons={{
|
||||
success: (
|
||||
<CircleCheckIcon className="size-4" />
|
||||
),
|
||||
info: (
|
||||
<InfoIcon className="size-4" />
|
||||
),
|
||||
warning: (
|
||||
<TriangleAlertIcon className="size-4" />
|
||||
),
|
||||
error: (
|
||||
<OctagonXIcon className="size-4" />
|
||||
),
|
||||
loading: (
|
||||
<Loader2Icon className="size-4 animate-spin" />
|
||||
),
|
||||
}}
|
||||
style={
|
||||
{
|
||||
"--normal-bg": "var(--popover)",
|
||||
"--normal-text": "var(--popover-foreground)",
|
||||
"--normal-border": "var(--border)",
|
||||
"--border-radius": "var(--radius)",
|
||||
} as React.CSSProperties
|
||||
}
|
||||
toastOptions={{
|
||||
classNames: {
|
||||
toast: "cn-toast",
|
||||
},
|
||||
}}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export { Toaster }
|
||||
@@ -0,0 +1,31 @@
|
||||
"use client"
|
||||
|
||||
import { Switch as SwitchPrimitive } from "@base-ui/react/switch"
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
function Switch({
|
||||
className,
|
||||
size = "default",
|
||||
...props
|
||||
}: SwitchPrimitive.Root.Props & {
|
||||
size?: "sm" | "default"
|
||||
}) {
|
||||
return (
|
||||
<SwitchPrimitive.Root
|
||||
data-slot="switch"
|
||||
data-size={size}
|
||||
className={cn(
|
||||
"peer group/switch relative inline-flex shrink-0 items-center rounded-full border border-transparent transition-all outline-none group-has-[:focus-visible]/field-label:border-transparent group-has-[:focus-visible]/field-label:ring-0 after:absolute after:-inset-x-3 after:-inset-y-2 focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 aria-invalid:border-destructive aria-invalid:ring-3 aria-invalid:ring-destructive/20 data-[size=default]:h-[18.4px] data-[size=default]:w-[32px] data-[size=sm]:h-[14px] data-[size=sm]:w-[24px] dark:aria-invalid:border-destructive/50 dark:aria-invalid:ring-destructive/40 data-checked:bg-primary data-unchecked:bg-input dark:data-unchecked:bg-input/80 data-disabled:cursor-not-allowed data-disabled:opacity-50",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
<SwitchPrimitive.Thumb
|
||||
data-slot="switch-thumb"
|
||||
className="pointer-events-none block rounded-full bg-background ring-0 transition-transform group-data-[size=default]/switch:size-4 group-data-[size=sm]/switch:size-3 group-data-[size=default]/switch:data-checked:translate-x-[calc(100%-2px)] group-data-[size=sm]/switch:data-checked:translate-x-[calc(100%-2px)] dark:data-checked:bg-primary-foreground group-data-[size=default]/switch:data-unchecked:translate-x-0 group-data-[size=sm]/switch:data-unchecked:translate-x-0 dark:data-unchecked:bg-foreground"
|
||||
/>
|
||||
</SwitchPrimitive.Root>
|
||||
)
|
||||
}
|
||||
|
||||
export { Switch }
|
||||
@@ -0,0 +1,79 @@
|
||||
import { Tabs as TabsPrimitive } from "@base-ui/react/tabs"
|
||||
import { cva, type VariantProps } from "class-variance-authority"
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
function Tabs({
|
||||
className,
|
||||
orientation = "horizontal",
|
||||
...props
|
||||
}: TabsPrimitive.Root.Props) {
|
||||
return (
|
||||
<TabsPrimitive.Root
|
||||
data-slot="tabs"
|
||||
data-orientation={orientation}
|
||||
className={cn(
|
||||
"group/tabs flex gap-2 data-horizontal:flex-col",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
const tabsListVariants = cva(
|
||||
"group/tabs-list inline-flex w-fit items-center justify-center rounded-lg p-[3px] text-muted-foreground group-data-horizontal/tabs:h-8 group-data-vertical/tabs:h-fit group-data-vertical/tabs:flex-col data-[variant=line]:rounded-none",
|
||||
{
|
||||
variants: {
|
||||
variant: {
|
||||
default: "bg-muted",
|
||||
line: "gap-1 bg-transparent",
|
||||
},
|
||||
},
|
||||
defaultVariants: {
|
||||
variant: "default",
|
||||
},
|
||||
}
|
||||
)
|
||||
|
||||
function TabsList({
|
||||
className,
|
||||
variant = "default",
|
||||
...props
|
||||
}: TabsPrimitive.List.Props & VariantProps<typeof tabsListVariants>) {
|
||||
return (
|
||||
<TabsPrimitive.List
|
||||
data-slot="tabs-list"
|
||||
data-variant={variant}
|
||||
className={cn(tabsListVariants({ variant }), className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function TabsTrigger({ className, ...props }: TabsPrimitive.Tab.Props) {
|
||||
return (
|
||||
<TabsPrimitive.Tab
|
||||
data-slot="tabs-trigger"
|
||||
className={cn(
|
||||
"relative inline-flex h-[calc(100%-1px)] flex-1 items-center justify-center gap-1.5 rounded-md border border-transparent px-1.5 py-0.5 text-sm font-medium whitespace-nowrap text-foreground/60 transition-all group-data-vertical/tabs:w-full group-data-vertical/tabs:justify-start hover:text-foreground focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 focus-visible:outline-1 focus-visible:outline-ring disabled:pointer-events-none disabled:opacity-50 has-data-[icon=inline-end]:pr-1 has-data-[icon=inline-start]:pl-1 aria-disabled:pointer-events-none aria-disabled:opacity-50 dark:text-muted-foreground dark:hover:text-foreground group-data-[variant=default]/tabs-list:data-active:shadow-sm group-data-[variant=line]/tabs-list:data-active:shadow-none [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
|
||||
"group-data-[variant=line]/tabs-list:bg-transparent group-data-[variant=line]/tabs-list:data-active:bg-transparent dark:group-data-[variant=line]/tabs-list:data-active:border-transparent dark:group-data-[variant=line]/tabs-list:data-active:bg-transparent",
|
||||
"data-active:bg-background data-active:text-foreground dark:data-active:border-input dark:data-active:bg-input/30 dark:data-active:text-foreground",
|
||||
"after:absolute after:bg-foreground after:opacity-0 after:transition-opacity group-data-horizontal/tabs:after:inset-x-0 group-data-horizontal/tabs:after:bottom-[-5px] group-data-horizontal/tabs:after:h-0.5 group-data-vertical/tabs:after:inset-y-0 group-data-vertical/tabs:after:-right-1 group-data-vertical/tabs:after:w-0.5 group-data-[variant=line]/tabs-list:data-active:after:opacity-100",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function TabsContent({ className, ...props }: TabsPrimitive.Panel.Props) {
|
||||
return (
|
||||
<TabsPrimitive.Panel
|
||||
data-slot="tabs-content"
|
||||
className={cn("flex-1 text-sm outline-none", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export { Tabs, TabsList, TabsTrigger, TabsContent, tabsListVariants }
|
||||
@@ -0,0 +1,17 @@
|
||||
import * as React from "react"
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
function Textarea({ className, ...props }: React.ComponentProps<"textarea">) {
|
||||
return (
|
||||
<textarea
|
||||
data-slot="textarea"
|
||||
className={cn(
|
||||
"flex field-sizing-content min-h-16 w-full rounded-lg border border-input bg-transparent px-2.5 py-2 text-base transition-colors outline-none placeholder:text-muted-foreground focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 disabled:cursor-not-allowed disabled:bg-input/50 disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-3 aria-invalid:ring-destructive/20 md:text-sm dark:bg-input/30 dark:disabled:bg-input/80 dark:aria-invalid:border-destructive/50 dark:aria-invalid:ring-destructive/40",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export { Textarea }
|
||||
@@ -0,0 +1,87 @@
|
||||
import * as React from "react"
|
||||
import { Toggle as TogglePrimitive } from "@base-ui/react/toggle"
|
||||
import { ToggleGroup as ToggleGroupPrimitive } from "@base-ui/react/toggle-group"
|
||||
import { type VariantProps } from "class-variance-authority"
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
import { toggleVariants } from "@/components/ui/toggle"
|
||||
|
||||
const ToggleGroupContext = React.createContext<
|
||||
VariantProps<typeof toggleVariants> & {
|
||||
spacing?: number
|
||||
orientation?: "horizontal" | "vertical"
|
||||
}
|
||||
>({
|
||||
size: "default",
|
||||
variant: "default",
|
||||
spacing: 2,
|
||||
orientation: "horizontal",
|
||||
})
|
||||
|
||||
function ToggleGroup({
|
||||
className,
|
||||
variant,
|
||||
size,
|
||||
spacing = 2,
|
||||
orientation = "horizontal",
|
||||
children,
|
||||
...props
|
||||
}: ToggleGroupPrimitive.Props &
|
||||
VariantProps<typeof toggleVariants> & {
|
||||
spacing?: number
|
||||
orientation?: "horizontal" | "vertical"
|
||||
}) {
|
||||
return (
|
||||
<ToggleGroupPrimitive
|
||||
data-slot="toggle-group"
|
||||
data-variant={variant}
|
||||
data-size={size}
|
||||
data-spacing={spacing}
|
||||
data-orientation={orientation}
|
||||
style={{ "--gap": spacing } as React.CSSProperties}
|
||||
className={cn(
|
||||
"group/toggle-group flex w-fit flex-row items-center gap-[--spacing(var(--gap))] rounded-lg data-[size=sm]:rounded-[min(var(--radius-md),10px)] data-vertical:flex-col data-vertical:items-stretch",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
<ToggleGroupContext.Provider
|
||||
value={{ variant, size, spacing, orientation }}
|
||||
>
|
||||
{children}
|
||||
</ToggleGroupContext.Provider>
|
||||
</ToggleGroupPrimitive>
|
||||
)
|
||||
}
|
||||
|
||||
function ToggleGroupItem({
|
||||
className,
|
||||
children,
|
||||
variant = "default",
|
||||
size = "default",
|
||||
...props
|
||||
}: TogglePrimitive.Props & VariantProps<typeof toggleVariants>) {
|
||||
const context = React.useContext(ToggleGroupContext)
|
||||
|
||||
return (
|
||||
<TogglePrimitive
|
||||
data-slot="toggle-group-item"
|
||||
data-variant={context.variant || variant}
|
||||
data-size={context.size || size}
|
||||
data-spacing={context.spacing}
|
||||
className={cn(
|
||||
"shrink-0 group-data-[spacing=0]/toggle-group:rounded-none group-data-[spacing=0]/toggle-group:px-2 focus:z-10 focus-visible:z-10 group-data-[spacing=0]/toggle-group:has-data-[icon=inline-end]:pr-1.5 group-data-[spacing=0]/toggle-group:has-data-[icon=inline-start]:pl-1.5 group-data-horizontal/toggle-group:data-[spacing=0]:first:rounded-l-lg group-data-vertical/toggle-group:data-[spacing=0]:first:rounded-t-lg group-data-horizontal/toggle-group:data-[spacing=0]:last:rounded-r-lg group-data-vertical/toggle-group:data-[spacing=0]:last:rounded-b-lg group-data-horizontal/toggle-group:data-[spacing=0]:data-[variant=outline]:border-l-0 group-data-vertical/toggle-group:data-[spacing=0]:data-[variant=outline]:border-t-0 group-data-horizontal/toggle-group:data-[spacing=0]:data-[variant=outline]:first:border-l group-data-vertical/toggle-group:data-[spacing=0]:data-[variant=outline]:first:border-t",
|
||||
toggleVariants({
|
||||
variant: context.variant || variant,
|
||||
size: context.size || size,
|
||||
}),
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
{children}
|
||||
</TogglePrimitive>
|
||||
)
|
||||
}
|
||||
|
||||
export { ToggleGroup, ToggleGroupItem }
|
||||
@@ -0,0 +1,44 @@
|
||||
"use client"
|
||||
|
||||
import { Toggle as TogglePrimitive } from "@base-ui/react/toggle"
|
||||
import { cva, type VariantProps } from "class-variance-authority"
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
const toggleVariants = cva(
|
||||
"group/toggle inline-flex items-center justify-center gap-1 rounded-lg text-sm font-medium whitespace-nowrap transition-all outline-none hover:bg-muted hover:text-foreground focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 disabled:pointer-events-none disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-destructive/20 aria-pressed:bg-muted data-[state=on]:bg-muted dark:aria-invalid:ring-destructive/40 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
|
||||
{
|
||||
variants: {
|
||||
variant: {
|
||||
default: "bg-transparent",
|
||||
outline: "border border-input bg-transparent hover:bg-muted",
|
||||
},
|
||||
size: {
|
||||
default:
|
||||
"h-8 min-w-8 px-2.5 has-data-[icon=inline-end]:pr-2 has-data-[icon=inline-start]:pl-2",
|
||||
sm: "h-7 min-w-7 rounded-[min(var(--radius-md),12px)] px-2.5 text-[0.8rem] has-data-[icon=inline-end]:pr-1.5 has-data-[icon=inline-start]:pl-1.5 [&_svg:not([class*='size-'])]:size-3.5",
|
||||
lg: "h-9 min-w-9 px-2.5 has-data-[icon=inline-end]:pr-2 has-data-[icon=inline-start]:pl-2",
|
||||
},
|
||||
},
|
||||
defaultVariants: {
|
||||
variant: "default",
|
||||
size: "default",
|
||||
},
|
||||
}
|
||||
)
|
||||
|
||||
function Toggle({
|
||||
className,
|
||||
variant = "default",
|
||||
size = "default",
|
||||
...props
|
||||
}: TogglePrimitive.Props & VariantProps<typeof toggleVariants>) {
|
||||
return (
|
||||
<TogglePrimitive
|
||||
data-slot="toggle"
|
||||
className={cn(toggleVariants({ variant, size, className }))}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export { Toggle, toggleVariants }
|
||||
@@ -0,0 +1,173 @@
|
||||
@import "tailwindcss";
|
||||
@import "tw-animate-css";
|
||||
@import "shadcn/tailwind.css";
|
||||
|
||||
@custom-variant dark (&:is(.dark *));
|
||||
|
||||
@theme inline {
|
||||
--font-heading: var(--font-sans);
|
||||
--font-sans: -apple-system, BlinkMacSystemFont, 'PingFang SC', 'Hiragino Sans GB', 'Microsoft YaHei', sans-serif;
|
||||
--color-sidebar-ring: var(--sidebar-ring);
|
||||
--color-sidebar-border: var(--sidebar-border);
|
||||
--color-sidebar-accent-foreground: var(--sidebar-accent-foreground);
|
||||
--color-sidebar-accent: var(--sidebar-accent);
|
||||
--color-sidebar-primary-foreground: var(--sidebar-primary-foreground);
|
||||
--color-sidebar-primary: var(--sidebar-primary);
|
||||
--color-sidebar-foreground: var(--sidebar-foreground);
|
||||
--color-sidebar: var(--sidebar);
|
||||
--color-chart-5: var(--chart-5);
|
||||
--color-chart-4: var(--chart-4);
|
||||
--color-chart-3: var(--chart-3);
|
||||
--color-chart-2: var(--chart-2);
|
||||
--color-chart-1: var(--chart-1);
|
||||
--color-ring: var(--ring);
|
||||
--color-input: var(--input);
|
||||
--color-border: var(--border);
|
||||
--color-destructive: var(--destructive);
|
||||
--color-accent-foreground: var(--accent-foreground);
|
||||
--color-accent: var(--accent);
|
||||
--color-muted-foreground: var(--muted-foreground);
|
||||
--color-muted: var(--muted);
|
||||
--color-secondary-foreground: var(--secondary-foreground);
|
||||
--color-secondary: var(--secondary);
|
||||
--color-primary-foreground: var(--primary-foreground);
|
||||
--color-primary: var(--primary);
|
||||
--color-popover-foreground: var(--popover-foreground);
|
||||
--color-popover: var(--popover);
|
||||
--color-card-foreground: var(--card-foreground);
|
||||
--color-card: var(--card);
|
||||
--color-foreground: var(--foreground);
|
||||
--color-background: var(--background);
|
||||
--radius-sm: calc(var(--radius) * 0.6);
|
||||
--radius-md: calc(var(--radius) * 0.8);
|
||||
--radius-lg: var(--radius);
|
||||
--radius-xl: calc(var(--radius) * 1.4);
|
||||
--radius-2xl: calc(var(--radius) * 1.8);
|
||||
--radius-3xl: calc(var(--radius) * 2.2);
|
||||
--radius-4xl: calc(var(--radius) * 2.6);
|
||||
}
|
||||
|
||||
:root {
|
||||
--background: oklch(1 0 0);
|
||||
--foreground: oklch(0.145 0 0);
|
||||
--card: oklch(1 0 0);
|
||||
--card-foreground: oklch(0.145 0 0);
|
||||
--popover: oklch(1 0 0);
|
||||
--popover-foreground: oklch(0.145 0 0);
|
||||
--primary: oklch(0.205 0 0);
|
||||
--primary-foreground: oklch(0.985 0 0);
|
||||
--secondary: oklch(0.97 0 0);
|
||||
--secondary-foreground: oklch(0.205 0 0);
|
||||
--muted: oklch(0.97 0 0);
|
||||
--muted-foreground: oklch(0.556 0 0);
|
||||
--accent: oklch(0.97 0 0);
|
||||
--accent-foreground: oklch(0.205 0 0);
|
||||
--destructive: oklch(0.577 0.245 27.325);
|
||||
--border: oklch(0.922 0 0);
|
||||
--input: oklch(0.922 0 0);
|
||||
--ring: oklch(0.708 0 0);
|
||||
--chart-1: oklch(0.87 0 0);
|
||||
--chart-2: oklch(0.556 0 0);
|
||||
--chart-3: oklch(0.439 0 0);
|
||||
--chart-4: oklch(0.371 0 0);
|
||||
--chart-5: oklch(0.269 0 0);
|
||||
--radius: 0.625rem;
|
||||
--sidebar: oklch(0.985 0 0);
|
||||
--sidebar-foreground: oklch(0.145 0 0);
|
||||
--sidebar-primary: oklch(0.205 0 0);
|
||||
--sidebar-primary-foreground: oklch(0.985 0 0);
|
||||
--sidebar-accent: oklch(0.97 0 0);
|
||||
--sidebar-accent-foreground: oklch(0.205 0 0);
|
||||
--sidebar-border: oklch(0.922 0 0);
|
||||
--sidebar-ring: oklch(0.708 0 0);
|
||||
}
|
||||
|
||||
.dark {
|
||||
--background: oklch(0.145 0 0);
|
||||
--foreground: oklch(0.985 0 0);
|
||||
--card: oklch(0.205 0 0);
|
||||
--card-foreground: oklch(0.985 0 0);
|
||||
--popover: oklch(0.205 0 0);
|
||||
--popover-foreground: oklch(0.985 0 0);
|
||||
--primary: oklch(0.922 0 0);
|
||||
--primary-foreground: oklch(0.205 0 0);
|
||||
--secondary: oklch(0.269 0 0);
|
||||
--secondary-foreground: oklch(0.985 0 0);
|
||||
--muted: oklch(0.269 0 0);
|
||||
--muted-foreground: oklch(0.708 0 0);
|
||||
--accent: oklch(0.269 0 0);
|
||||
--accent-foreground: oklch(0.985 0 0);
|
||||
--destructive: oklch(0.704 0.191 22.216);
|
||||
--border: oklch(1 0 0 / 10%);
|
||||
--input: oklch(1 0 0 / 15%);
|
||||
--ring: oklch(0.556 0 0);
|
||||
--chart-1: oklch(0.87 0 0);
|
||||
--chart-2: oklch(0.556 0 0);
|
||||
--chart-3: oklch(0.439 0 0);
|
||||
--chart-4: oklch(0.371 0 0);
|
||||
--chart-5: oklch(0.269 0 0);
|
||||
--sidebar: oklch(0.205 0 0);
|
||||
--sidebar-foreground: oklch(0.985 0 0);
|
||||
--sidebar-primary: oklch(0.488 0.243 264.376);
|
||||
--sidebar-primary-foreground: oklch(0.985 0 0);
|
||||
--sidebar-accent: oklch(0.269 0 0);
|
||||
--sidebar-accent-foreground: oklch(0.985 0 0);
|
||||
--sidebar-border: oklch(1 0 0 / 10%);
|
||||
--sidebar-ring: oklch(0.556 0 0);
|
||||
}
|
||||
|
||||
@layer base {
|
||||
* {
|
||||
@apply border-border outline-ring/50;
|
||||
}
|
||||
body {
|
||||
@apply bg-background text-foreground;
|
||||
}
|
||||
html {
|
||||
@apply font-sans;
|
||||
}
|
||||
}
|
||||
/* App theme: warm orange accent, soft grey page, white cards. */
|
||||
:root {
|
||||
--primary: oklch(0.7 0.17 50);
|
||||
--primary-foreground: oklch(0.99 0 0);
|
||||
--ring: oklch(0.7 0.17 50);
|
||||
--background: oklch(0.975 0.003 260);
|
||||
--card: oklch(1 0 0);
|
||||
--radius: 0.9rem;
|
||||
--expense: oklch(0.6 0.2 25);
|
||||
--income: oklch(0.6 0.15 155);
|
||||
}
|
||||
@media (prefers-color-scheme: dark) {
|
||||
:root {
|
||||
--background: oklch(0.16 0 0);
|
||||
--foreground: oklch(0.96 0 0);
|
||||
--card: oklch(0.21 0 0);
|
||||
--card-foreground: oklch(0.96 0 0);
|
||||
--popover: oklch(0.21 0 0);
|
||||
--popover-foreground: oklch(0.96 0 0);
|
||||
--muted: oklch(0.27 0 0);
|
||||
--muted-foreground: oklch(0.7 0 0);
|
||||
--secondary: oklch(0.27 0 0);
|
||||
--secondary-foreground: oklch(0.96 0 0);
|
||||
--accent: oklch(0.27 0 0);
|
||||
--accent-foreground: oklch(0.96 0 0);
|
||||
--border: oklch(1 0 0 / 10%);
|
||||
--input: oklch(1 0 0 / 15%);
|
||||
--expense: oklch(0.72 0.17 25);
|
||||
--income: oklch(0.75 0.15 155);
|
||||
}
|
||||
}
|
||||
@theme inline {
|
||||
--color-expense: var(--expense);
|
||||
--color-income: var(--income);
|
||||
}
|
||||
|
||||
html, body, #root { height: 100%; }
|
||||
body {
|
||||
-webkit-tap-highlight-color: transparent;
|
||||
overscroll-behavior-y: none;
|
||||
}
|
||||
.pb-safe { padding-bottom: env(safe-area-inset-bottom); }
|
||||
.pt-safe { padding-top: env(safe-area-inset-top); }
|
||||
.tabular { font-variant-numeric: tabular-nums; }
|
||||
@@ -0,0 +1,160 @@
|
||||
export type BillType = 'expense' | 'income';
|
||||
|
||||
export interface Member { id: number; name: string; color: string }
|
||||
export interface Book { id: number; name: string }
|
||||
export interface Category {
|
||||
id: number;
|
||||
parentId: number | null;
|
||||
type: BillType;
|
||||
name: string;
|
||||
icon: string | null;
|
||||
sort: number;
|
||||
hidden: number;
|
||||
}
|
||||
export interface Me { id: number; username: string; memberId: number }
|
||||
export interface Meta {
|
||||
me: Me;
|
||||
members: Member[];
|
||||
books: Book[];
|
||||
categories: Category[];
|
||||
vapidPublicKey: string;
|
||||
}
|
||||
|
||||
export interface BillShare { memberId: number; share: number }
|
||||
export interface Bill {
|
||||
id: number;
|
||||
bookId: number;
|
||||
type: BillType;
|
||||
categoryId: number;
|
||||
amount: number;
|
||||
time: number;
|
||||
note: string;
|
||||
payerId: number | null;
|
||||
excludeBudget: boolean;
|
||||
createdBy: number | null;
|
||||
members: BillShare[];
|
||||
}
|
||||
|
||||
export interface BillInput {
|
||||
bookId: number;
|
||||
type: BillType;
|
||||
categoryId: number;
|
||||
amount: number;
|
||||
time: number;
|
||||
note: string;
|
||||
payerId: number | null;
|
||||
members: { memberId: number; share?: number }[];
|
||||
excludeBudget: boolean;
|
||||
}
|
||||
|
||||
export interface BudgetStatus {
|
||||
id: number;
|
||||
bookId: number;
|
||||
categoryId: number | null;
|
||||
amount: number;
|
||||
spent: number;
|
||||
percent: number;
|
||||
}
|
||||
export interface BudgetAlert { budget: BudgetStatus; level: number }
|
||||
|
||||
export interface ParsedBill {
|
||||
type: BillType;
|
||||
amount: number | null;
|
||||
categoryId: number | null;
|
||||
time: number;
|
||||
memberIds: number[];
|
||||
payerId: number;
|
||||
note: string;
|
||||
}
|
||||
|
||||
export interface Totals { expense: number; income: number; count: number }
|
||||
export interface CategoryTotal { categoryId: number; amount: number; count: number }
|
||||
|
||||
export interface SettleInfo {
|
||||
balances: { memberId: number; paid: number; consumed: number; net: number }[];
|
||||
transfers: { from: number; to: number; amount: number }[];
|
||||
history: { id: number; fromId: number; toId: number; amount: number; time: number; note: string }[];
|
||||
}
|
||||
|
||||
export interface AnnualReport {
|
||||
year: number;
|
||||
totals: Totals;
|
||||
previous: Totals;
|
||||
monthly: { month: string; expense: number; income: number }[];
|
||||
categories: CategoryTotal[];
|
||||
incomeCategories: CategoryTotal[];
|
||||
members: { memberId: number; own: number; shared: number }[];
|
||||
topBills: { id: number; categoryId: number; amount: number; time: number; note: string }[];
|
||||
busiestDay: { day: string; amount: number; count: number } | null;
|
||||
activeDays: number;
|
||||
habits: CategoryTotal[];
|
||||
}
|
||||
|
||||
export class ApiError extends Error {
|
||||
status: number;
|
||||
constructor(status: number, message: string) {
|
||||
super(message);
|
||||
this.status = status;
|
||||
}
|
||||
}
|
||||
|
||||
async function request<T>(method: string, path: string, body?: unknown): Promise<T> {
|
||||
const res = await fetch(`/api${path}`, {
|
||||
method,
|
||||
headers: body === undefined ? undefined : { 'Content-Type': 'application/json' },
|
||||
body: body === undefined ? undefined : JSON.stringify(body),
|
||||
credentials: 'same-origin',
|
||||
});
|
||||
const data = await res.json().catch(() => ({}));
|
||||
if (!res.ok) throw new ApiError(res.status, data.error ?? `请求失败 (${res.status})`);
|
||||
return data as T;
|
||||
}
|
||||
|
||||
const qs = (params: Record<string, string | number | undefined | null>) => {
|
||||
const s = new URLSearchParams();
|
||||
for (const [k, v] of Object.entries(params)) if (v !== undefined && v !== null && v !== '') s.set(k, String(v));
|
||||
const str = s.toString();
|
||||
return str ? `?${str}` : '';
|
||||
};
|
||||
|
||||
export const api = {
|
||||
login: (username: string, password: string) => request<{ ok: true }>('POST', '/login', { username, password }),
|
||||
logout: () => request('POST', '/logout'),
|
||||
meta: () => request<Meta>('GET', '/meta'),
|
||||
|
||||
bills: (p: { bookId?: number; month?: string; from?: number; to?: number; categoryId?: number; memberId?: number; q?: string }) =>
|
||||
request<Bill[]>('GET', `/bills${qs(p)}`),
|
||||
createBill: (b: BillInput) => request<{ id: number; alerts: BudgetAlert[] }>('POST', '/bills', b),
|
||||
updateBill: (id: number, b: BillInput) => request<{ alerts: BudgetAlert[] }>('PUT', `/bills/${id}`, b),
|
||||
deleteBill: (id: number) => request('DELETE', `/bills/${id}`),
|
||||
quick: (text: string) => request<ParsedBill>('POST', '/quick', { text }),
|
||||
|
||||
overview: (p: { bookId?: number; month: string }) =>
|
||||
request<{ totals: Totals; budgets: BudgetStatus[] }>('GET', `/stats/overview${qs(p)}`),
|
||||
categoryStats: (p: { bookId?: number; month?: string; from?: number; to?: number; type: BillType; parentId?: number; memberId?: number }) =>
|
||||
request<CategoryTotal[]>('GET', `/stats/categories${qs(p)}`),
|
||||
memberStats: (p: { bookId?: number; from?: number; to?: number; month?: string }) =>
|
||||
request<{ monthly: { month: string; memberId: number; amount: number }[]; breakdown: { memberId: number; own: number; shared: number }[] }>(
|
||||
'GET', `/stats/members${qs(p)}`),
|
||||
report: (year: number, bookId?: number) => request<AnnualReport>('GET', `/report/${year}${qs({ bookId })}`),
|
||||
|
||||
settle: () => request<SettleInfo>('GET', '/settle'),
|
||||
addSettlement: (b: { fromId: number; toId: number; amount: number; note: string }) => request('POST', '/settle', b),
|
||||
deleteSettlement: (id: number) => request('DELETE', `/settle/${id}`),
|
||||
|
||||
budgets: (bookId: number, month?: string) => request<BudgetStatus[]>('GET', `/budgets${qs({ bookId, month })}`),
|
||||
setBudget: (b: { bookId: number; categoryId: number | null; amount: number }) => request('PUT', '/budgets', b),
|
||||
deleteBudget: (id: number) => request('DELETE', `/budgets/${id}`),
|
||||
|
||||
addCategory: (c: { parentId: number | null; type: BillType; name: string; icon: string | null }) =>
|
||||
request<{ id: number }>('POST', '/categories', c),
|
||||
updateCategory: (id: number, c: { name?: string; icon?: string | null; hidden?: boolean; sort?: number }) =>
|
||||
request('PUT', `/categories/${id}`, c),
|
||||
addBook: (name: string) => request<{ id: number }>('POST', '/books', { name }),
|
||||
|
||||
icons: () => request<{ styles: string[]; names: string[] }>('GET', '/icons'),
|
||||
|
||||
subscribePush: (sub: PushSubscriptionJSON) => request('POST', '/push/subscribe', sub),
|
||||
unsubscribePush: (endpoint: string) => request('POST', '/push/unsubscribe', { endpoint }),
|
||||
testPush: () => request('POST', '/push/test'),
|
||||
};
|
||||
@@ -0,0 +1,97 @@
|
||||
// Calendar math in China Standard Time, matching the server.
|
||||
const OFFSET = 8 * 3600 * 1000;
|
||||
|
||||
export function cst(ts: number) {
|
||||
const d = new Date(ts + OFFSET);
|
||||
return {
|
||||
year: d.getUTCFullYear(),
|
||||
month: d.getUTCMonth() + 1,
|
||||
day: d.getUTCDate(),
|
||||
hour: d.getUTCHours(),
|
||||
minute: d.getUTCMinutes(),
|
||||
weekday: d.getUTCDay(),
|
||||
};
|
||||
}
|
||||
|
||||
export const pad = (n: number) => String(n).padStart(2, '0');
|
||||
|
||||
export function monthKey(ts = Date.now()) {
|
||||
const d = cst(ts);
|
||||
return `${d.year}-${pad(d.month)}`;
|
||||
}
|
||||
|
||||
export function shiftMonth(month: string, delta: number) {
|
||||
const [y, m] = month.split('-').map(Number);
|
||||
const d = new Date(Date.UTC(y, m - 1 + delta, 1));
|
||||
return `${d.getUTCFullYear()}-${pad(d.getUTCMonth() + 1)}`;
|
||||
}
|
||||
|
||||
export function monthLabel(month: string) {
|
||||
const [y, m] = month.split('-').map(Number);
|
||||
return `${y}年${m}月`;
|
||||
}
|
||||
|
||||
export function monthStart(month: string) {
|
||||
const [y, m] = month.split('-').map(Number);
|
||||
return Date.UTC(y, m - 1, 1) - OFFSET;
|
||||
}
|
||||
|
||||
export function yearRange(year: number) {
|
||||
return { from: Date.UTC(year, 0, 1) - OFFSET, to: Date.UTC(year + 1, 0, 1) - OFFSET };
|
||||
}
|
||||
|
||||
const WEEK = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];
|
||||
|
||||
export function dayLabel(ts: number) {
|
||||
const d = cst(ts);
|
||||
const today = cst(Date.now());
|
||||
const yesterday = cst(Date.now() - 86400000);
|
||||
const same = (a: typeof d) => a.year === d.year && a.month === d.month && a.day === d.day;
|
||||
const prefix = same(today) ? '今天' : same(yesterday) ? '昨天' : WEEK[d.weekday];
|
||||
return `${d.month}月${d.day}日 ${prefix}`;
|
||||
}
|
||||
|
||||
export function dayKey(ts: number) {
|
||||
const d = cst(ts);
|
||||
return `${d.year}-${pad(d.month)}-${pad(d.day)}`;
|
||||
}
|
||||
|
||||
export function timeLabel(ts: number) {
|
||||
const d = cst(ts);
|
||||
return `${pad(d.hour)}:${pad(d.minute)}`;
|
||||
}
|
||||
|
||||
// Value for <input type="datetime-local"> in CST, and back.
|
||||
export function toLocalInput(ts: number) {
|
||||
const d = cst(ts);
|
||||
return `${d.year}-${pad(d.month)}-${pad(d.day)}T${pad(d.hour)}:${pad(d.minute)}`;
|
||||
}
|
||||
export function fromLocalInput(v: string) {
|
||||
const [date, time = '00:00'] = v.split('T');
|
||||
const [y, m, d] = date.split('-').map(Number);
|
||||
const [h, mi] = time.split(':').map(Number);
|
||||
return Date.UTC(y, m - 1, d, h, mi) - OFFSET;
|
||||
}
|
||||
|
||||
// Cents to "1,234.5" style text.
|
||||
export function money(cents: number, opts: { sign?: boolean; decimals?: boolean } = {}) {
|
||||
const v = cents / 100;
|
||||
const text = Math.abs(v).toLocaleString('zh-CN', {
|
||||
minimumFractionDigits: opts.decimals ? 2 : 0,
|
||||
maximumFractionDigits: 2,
|
||||
});
|
||||
if (!opts.sign) return v < 0 ? `-${text}` : text;
|
||||
return `${v < 0 ? '-' : '+'}${text}`;
|
||||
}
|
||||
|
||||
// Compact form for chart axes: 1.2万
|
||||
export function moneyShort(cents: number) {
|
||||
const v = cents / 100;
|
||||
if (Math.abs(v) >= 10000) return `${(v / 10000).toFixed(v >= 100000 ? 0 : 1)}万`;
|
||||
return String(Math.round(v));
|
||||
}
|
||||
|
||||
export function percentChange(now: number, before: number) {
|
||||
if (!before) return null;
|
||||
return Math.round(((now - before) / before) * 100);
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
// Generated from public/icons by: ls public/icons
|
||||
export const ICON_LIST = [
|
||||
'adhesive-bandage',
|
||||
'airplane',
|
||||
'automobile',
|
||||
'baby-bottle',
|
||||
'baby',
|
||||
'bank',
|
||||
'barber-pole',
|
||||
'basket',
|
||||
'bathtub',
|
||||
'bento-box',
|
||||
'bicycle',
|
||||
'books',
|
||||
'brick',
|
||||
'briefcase',
|
||||
'broom',
|
||||
'bubble-tea',
|
||||
'bus',
|
||||
'cat-face',
|
||||
'chair',
|
||||
'clapper-board',
|
||||
'clinking-glasses',
|
||||
'coin',
|
||||
'construction-worker',
|
||||
'couch-and-lamp',
|
||||
'croissant',
|
||||
'crown',
|
||||
'delivery-truck',
|
||||
'door',
|
||||
'dress',
|
||||
'droplet',
|
||||
'egg',
|
||||
'fire',
|
||||
'fork-and-knife-with-plate',
|
||||
'framed-picture',
|
||||
'game-die',
|
||||
'gem-stone',
|
||||
'globe-with-meridians',
|
||||
'hammer-and-wrench',
|
||||
'handbag',
|
||||
'high-speed-train',
|
||||
'high-voltage',
|
||||
'hot-beverage',
|
||||
'hotel',
|
||||
'house',
|
||||
'laptop',
|
||||
'leafy-green',
|
||||
'light-bulb',
|
||||
'lipstick',
|
||||
'lotion-bottle',
|
||||
'luggage',
|
||||
'metro',
|
||||
'microphone',
|
||||
'mobile-phone',
|
||||
'money-bag',
|
||||
'money-with-wings',
|
||||
'office-building',
|
||||
'old-woman',
|
||||
'oncoming-automobile',
|
||||
'p-button',
|
||||
'package',
|
||||
'people-hugging',
|
||||
'person-in-lotus-position',
|
||||
'pill',
|
||||
'pot-of-food',
|
||||
'receipt',
|
||||
'red-apple',
|
||||
'red-envelope',
|
||||
'red-heart',
|
||||
'roll-of-paper',
|
||||
'running-shoe',
|
||||
'shield',
|
||||
'shopping-bags',
|
||||
'shopping-cart',
|
||||
'shortcake',
|
||||
'soap',
|
||||
'sparkles',
|
||||
'sponge',
|
||||
'steaming-bowl',
|
||||
'stethoscope',
|
||||
'syringe',
|
||||
't-shirt',
|
||||
'taxi',
|
||||
'teddy-bear',
|
||||
'television',
|
||||
'ticket',
|
||||
'trophy',
|
||||
'video-game',
|
||||
'woman-feeding-baby',
|
||||
'wrapped-gift',
|
||||
];
|
||||
@@ -0,0 +1,41 @@
|
||||
import { useSyncExternalStore } from 'react';
|
||||
|
||||
export const ICON_STYLES = [
|
||||
{ id: '3d', label: '3D' },
|
||||
{ id: 'flat', label: '扁平' },
|
||||
{ id: 'filled', label: '线条' },
|
||||
{ id: 'lineal', label: '彩色线条' },
|
||||
{ id: 'outline', label: '描边' },
|
||||
] as const;
|
||||
export type IconStyle = (typeof ICON_STYLES)[number]['id'];
|
||||
|
||||
const KEY = 'iconStyle';
|
||||
const listeners = new Set<() => void>();
|
||||
|
||||
function read(): IconStyle {
|
||||
try {
|
||||
const v = localStorage.getItem(KEY);
|
||||
if (ICON_STYLES.some((s) => s.id === v)) return v as IconStyle;
|
||||
} catch { /* private mode */ }
|
||||
return '3d';
|
||||
}
|
||||
|
||||
let current = read();
|
||||
|
||||
export function setIconStyle(style: IconStyle) {
|
||||
current = style;
|
||||
try { localStorage.setItem(KEY, style); } catch { /* private mode */ }
|
||||
listeners.forEach((l) => l());
|
||||
}
|
||||
|
||||
export function useIconStyle(): IconStyle {
|
||||
return useSyncExternalStore(
|
||||
(l) => { listeners.add(l); return () => listeners.delete(l); },
|
||||
() => current,
|
||||
);
|
||||
}
|
||||
|
||||
// "mumu:<name>" icons come from the signed-in icon route; anything else is a bundled Fluent icon.
|
||||
export function iconUrl(icon: string, style: IconStyle) {
|
||||
return icon.startsWith('mumu:') ? `/api/icons/${style}/${icon.slice(5)}.webp` : `/icons/${icon}.png`;
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
import { createContext, useContext, useMemo, useState, type ReactNode } from 'react';
|
||||
import type { BillType, Category, Member, Meta } from './api';
|
||||
|
||||
interface MetaValue extends Meta {
|
||||
bookId: number;
|
||||
setBookId: (id: number) => void;
|
||||
category: (id: number | null | undefined) => Category | undefined;
|
||||
parentOf: (c: Category) => Category;
|
||||
childrenOf: (id: number) => Category[];
|
||||
roots: (type: BillType) => Category[];
|
||||
member: (id: number | null | undefined) => Member | undefined;
|
||||
categoryLabel: (id: number) => string;
|
||||
}
|
||||
|
||||
const Ctx = createContext<MetaValue | null>(null);
|
||||
|
||||
function readBook(): number | null {
|
||||
try {
|
||||
const v = localStorage.getItem('bookId');
|
||||
return v ? Number(v) : null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export function MetaProvider({ meta, children }: { meta: Meta; children: ReactNode }) {
|
||||
const [stored, setStored] = useState(readBook);
|
||||
const bookId = meta.books.some((b) => b.id === stored) ? stored! : meta.books[0]?.id ?? 0;
|
||||
|
||||
const value = useMemo<MetaValue>(() => {
|
||||
const byId = new Map(meta.categories.map((c) => [c.id, c]));
|
||||
const members = new Map(meta.members.map((m) => [m.id, m]));
|
||||
const visible = meta.categories.filter((c) => !c.hidden);
|
||||
const category = (id: number | null | undefined) => (id ? byId.get(id) : undefined);
|
||||
const parentOf = (c: Category) => (c.parentId ? byId.get(c.parentId) ?? c : c);
|
||||
return {
|
||||
...meta,
|
||||
bookId,
|
||||
setBookId: (id) => {
|
||||
setStored(id);
|
||||
try { localStorage.setItem('bookId', String(id)); } catch { /* private mode */ }
|
||||
},
|
||||
category,
|
||||
parentOf,
|
||||
childrenOf: (id) => visible.filter((c) => c.parentId === id),
|
||||
roots: (type) => visible.filter((c) => c.parentId === null && c.type === type),
|
||||
member: (id) => (id ? members.get(id) : undefined),
|
||||
categoryLabel: (id) => {
|
||||
const c = byId.get(id);
|
||||
if (!c) return '未知分类';
|
||||
const p = parentOf(c);
|
||||
return p.id === c.id ? c.name : `${p.name} · ${c.name}`;
|
||||
},
|
||||
};
|
||||
}, [meta, bookId]);
|
||||
|
||||
return <Ctx.Provider value={value}>{children}</Ctx.Provider>;
|
||||
}
|
||||
|
||||
export function useMeta() {
|
||||
const v = useContext(Ctx);
|
||||
if (!v) throw new Error('useMeta outside MetaProvider');
|
||||
return v;
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
import { useCallback, useRef, useState } from 'react';
|
||||
|
||||
// Minimal typing for the (webkit) Web Speech API.
|
||||
interface Recognition {
|
||||
lang: string;
|
||||
interimResults: boolean;
|
||||
continuous: boolean;
|
||||
start(): void;
|
||||
stop(): void;
|
||||
onresult: ((e: { results: ArrayLike<ArrayLike<{ transcript: string }> & { isFinal: boolean }> }) => void) | null;
|
||||
onerror: ((e: { error: string }) => void) | null;
|
||||
onend: (() => void) | null;
|
||||
}
|
||||
|
||||
function recognitionClass(): (new () => Recognition) | null {
|
||||
const w = window as unknown as { SpeechRecognition?: new () => Recognition; webkitSpeechRecognition?: new () => Recognition };
|
||||
return w.SpeechRecognition ?? w.webkitSpeechRecognition ?? null;
|
||||
}
|
||||
|
||||
export const speechSupported = () => recognitionClass() !== null;
|
||||
|
||||
// Listens in Mandarin and reports the live transcript. Calls onFinal once the
|
||||
// user stops talking.
|
||||
export function useSpeech(onFinal: (text: string) => void) {
|
||||
const [listening, setListening] = useState(false);
|
||||
const [text, setText] = useState('');
|
||||
const ref = useRef<Recognition | null>(null);
|
||||
const latest = useRef('');
|
||||
|
||||
const start = useCallback(() => {
|
||||
const Cls = recognitionClass();
|
||||
if (!Cls) return false;
|
||||
const r = new Cls();
|
||||
r.lang = 'zh-CN';
|
||||
r.interimResults = true;
|
||||
r.continuous = false;
|
||||
latest.current = '';
|
||||
setText('');
|
||||
r.onresult = (e) => {
|
||||
let t = '';
|
||||
for (let i = 0; i < e.results.length; i++) t += e.results[i][0].transcript;
|
||||
latest.current = t;
|
||||
setText(t);
|
||||
};
|
||||
r.onerror = () => setListening(false);
|
||||
r.onend = () => {
|
||||
setListening(false);
|
||||
if (latest.current.trim()) onFinal(latest.current.trim());
|
||||
};
|
||||
ref.current = r;
|
||||
r.start();
|
||||
setListening(true);
|
||||
return true;
|
||||
}, [onFinal]);
|
||||
|
||||
const stop = useCallback(() => ref.current?.stop(), []);
|
||||
|
||||
return { listening, text, start, stop };
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
export { cn } from "cn"
|
||||
@@ -0,0 +1,31 @@
|
||||
import { StrictMode } from 'react';
|
||||
import { createRoot } from 'react-dom/client';
|
||||
import { BrowserRouter } from 'react-router';
|
||||
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
|
||||
import { registerSW } from 'virtual:pwa-register';
|
||||
import { Toaster } from '@/components/ui/sonner';
|
||||
import { ApiError } from '@/lib/api';
|
||||
import App from './App';
|
||||
import './index.css';
|
||||
|
||||
registerSW({ immediate: true });
|
||||
|
||||
const queryClient = new QueryClient({
|
||||
defaultOptions: {
|
||||
queries: {
|
||||
staleTime: 30_000,
|
||||
retry: (count, err) => !(err instanceof ApiError && err.status === 401) && count < 2,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
createRoot(document.getElementById('root')!).render(
|
||||
<StrictMode>
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<BrowserRouter>
|
||||
<App />
|
||||
<Toaster position="top-center" richColors />
|
||||
</BrowserRouter>
|
||||
</QueryClientProvider>
|
||||
</StrictMode>,
|
||||
);
|
||||
@@ -0,0 +1,156 @@
|
||||
import { useMemo, useState } from 'react';
|
||||
import { useQuery } from '@tanstack/react-query';
|
||||
import { Mic, Search, Sparkles, X } from 'lucide-react';
|
||||
import { useEditor } from '@/App';
|
||||
import { api } from '@/lib/api';
|
||||
import { money, monthKey } from '@/lib/format';
|
||||
import { useMeta } from '@/lib/meta';
|
||||
import { speechSupported, useSpeech } from '@/lib/speech';
|
||||
import { cn } from '@/lib/utils';
|
||||
import { BillList } from '@/components/bill-list';
|
||||
import { BookSwitcher, MemberFilter, MonthSwitcher } from '@/components/pickers';
|
||||
import { Skeleton } from '@/components/ui/skeleton';
|
||||
|
||||
export default function HomePage() {
|
||||
const meta = useMeta();
|
||||
const editor = useEditor();
|
||||
const [month, setMonth] = useState(monthKey());
|
||||
const [memberId, setMemberId] = useState<number | null>(null);
|
||||
const [searching, setSearching] = useState(false);
|
||||
const [q, setQ] = useState('');
|
||||
const [quick, setQuick] = useState('');
|
||||
const speech = useSpeech((text) => editor.open({ text }));
|
||||
const canSpeak = useMemo(speechSupported, []);
|
||||
|
||||
const query = q.trim();
|
||||
const bills = useQuery({
|
||||
queryKey: ['bills', meta.bookId, query ? 'search' : month, memberId, query],
|
||||
queryFn: () => api.bills({ bookId: meta.bookId, month: query ? undefined : month, memberId: memberId ?? undefined, q: query || undefined }),
|
||||
});
|
||||
const overview = useQuery({
|
||||
queryKey: ['overview', meta.bookId, month],
|
||||
queryFn: () => api.overview({ bookId: meta.bookId, month }),
|
||||
});
|
||||
|
||||
// Totals follow the member filter: a member's figures are their shares.
|
||||
const totals = useMemo(() => {
|
||||
if (!memberId || !bills.data || query) return overview.data?.totals;
|
||||
let expense = 0, income = 0;
|
||||
for (const b of bills.data) {
|
||||
const share = b.members.find((m) => m.memberId === memberId)?.share ?? 0;
|
||||
if (b.type === 'expense') expense += share; else income += share;
|
||||
}
|
||||
return { expense, income, count: bills.data.length };
|
||||
}, [memberId, bills.data, overview.data, query]);
|
||||
|
||||
const totalBudget = overview.data?.budgets.find((b) => b.categoryId === null);
|
||||
|
||||
return (
|
||||
<div>
|
||||
<header className="pt-safe sticky top-0 z-30 bg-background/95 backdrop-blur">
|
||||
<div className="flex h-12 items-center justify-between px-4">
|
||||
<BookSwitcher />
|
||||
{searching ? null : <MonthSwitcher month={month} onChange={setMonth} />}
|
||||
<button
|
||||
onClick={() => { setSearching(!searching); setQ(''); }}
|
||||
className="p-1 text-muted-foreground"
|
||||
aria-label="搜索"
|
||||
>
|
||||
{searching ? <X className="size-5" /> : <Search className="size-5" />}
|
||||
</button>
|
||||
</div>
|
||||
{searching && (
|
||||
<div className="px-4 pb-2">
|
||||
<input
|
||||
autoFocus
|
||||
value={q}
|
||||
onChange={(e) => setQ(e.target.value)}
|
||||
placeholder="搜索备注或分类(全部时间)"
|
||||
className="h-9 w-full rounded-full bg-muted px-4 text-sm outline-none"
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
</header>
|
||||
|
||||
<div className="space-y-3 px-4">
|
||||
{!query && (
|
||||
<div className="rounded-3xl bg-gradient-to-br from-orange-400 to-amber-500 p-5 text-white shadow-md shadow-orange-500/20">
|
||||
<div className="text-xs opacity-85">本月支出{memberId ? ` · ${meta.member(memberId)?.name}` : ''}</div>
|
||||
<div className="tabular mt-1 text-3xl font-semibold">¥{totals ? money(totals.expense, { decimals: true }) : '—'}</div>
|
||||
<div className="mt-3 flex gap-6 text-xs">
|
||||
<div>
|
||||
<span className="opacity-85">收入 </span>
|
||||
<span className="tabular font-medium">{totals ? money(totals.income) : '—'}</span>
|
||||
</div>
|
||||
<div>
|
||||
<span className="opacity-85">结余 </span>
|
||||
<span className="tabular font-medium">{totals ? money(totals.income - totals.expense) : '—'}</span>
|
||||
</div>
|
||||
</div>
|
||||
{totalBudget && !memberId && (
|
||||
<div className="mt-3">
|
||||
<div className="h-1.5 overflow-hidden rounded-full bg-white/30">
|
||||
<div
|
||||
className={cn('h-full rounded-full', totalBudget.percent >= 100 ? 'bg-red-200' : 'bg-white')}
|
||||
style={{ width: `${Math.min(100, totalBudget.percent)}%` }}
|
||||
/>
|
||||
</div>
|
||||
<div className="mt-1 text-[11px] opacity-90">
|
||||
{totalBudget.percent >= 100
|
||||
? `已超预算 ¥${money(totalBudget.spent - totalBudget.amount)}`
|
||||
: `预算剩余 ¥${money(totalBudget.amount - totalBudget.spent)} · 已用 ${totalBudget.percent}%`}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* One-line entry: type or speak, then confirm in the editor. */}
|
||||
{!query && (
|
||||
<form
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
if (quick.trim()) { editor.open({ text: quick.trim() }); setQuick(''); }
|
||||
}}
|
||||
className="flex h-11 items-center gap-2 rounded-full bg-card px-4 shadow-sm"
|
||||
>
|
||||
<Sparkles className="size-4 shrink-0 text-primary" />
|
||||
<input
|
||||
value={speech.listening ? speech.text : quick}
|
||||
onChange={(e) => setQuick(e.target.value)}
|
||||
placeholder={speech.listening ? '正在听…' : '一句话记账:午餐 24 / 昨天一起打车35'}
|
||||
className="min-w-0 flex-1 bg-transparent text-sm outline-none placeholder:text-muted-foreground"
|
||||
enterKeyHint="go"
|
||||
/>
|
||||
{canSpeak && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => (speech.listening ? speech.stop() : speech.start())}
|
||||
className={cn('-mr-2 rounded-full p-2', speech.listening ? 'animate-pulse bg-primary text-primary-foreground' : 'text-muted-foreground')}
|
||||
aria-label="语音记账"
|
||||
>
|
||||
<Mic className="size-4" />
|
||||
</button>
|
||||
)}
|
||||
</form>
|
||||
)}
|
||||
|
||||
<div className="flex justify-center">
|
||||
<MemberFilter value={memberId} onChange={setMemberId} />
|
||||
</div>
|
||||
|
||||
{bills.isPending ? (
|
||||
<div className="space-y-2">
|
||||
{[0, 1, 2].map((i) => <Skeleton key={i} className="h-24 rounded-2xl" />)}
|
||||
</div>
|
||||
) : bills.data && bills.data.length > 0 ? (
|
||||
<BillList bills={bills.data} memberId={memberId} />
|
||||
) : (
|
||||
<div className="py-16 text-center text-sm text-muted-foreground">
|
||||
{query ? '没有找到相关账单' : '这个月还没有记账,点下方 + 记一笔'}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
import { useState } from 'react';
|
||||
import { useQueryClient } from '@tanstack/react-query';
|
||||
import { api } from '@/lib/api';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Input } from '@/components/ui/input';
|
||||
|
||||
export default function LoginPage() {
|
||||
const qc = useQueryClient();
|
||||
const [username, setUsername] = useState('');
|
||||
const [password, setPassword] = useState('');
|
||||
const [error, setError] = useState('');
|
||||
const [busy, setBusy] = useState(false);
|
||||
|
||||
const submit = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
setBusy(true);
|
||||
setError('');
|
||||
try {
|
||||
await api.login(username, password);
|
||||
await qc.invalidateQueries();
|
||||
} catch (err) {
|
||||
setError((err as Error).message);
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="flex min-h-full flex-col items-center justify-center px-8">
|
||||
<img src="/app-icon-192.png" alt="" className="mb-4 size-20 rounded-3xl shadow-md" />
|
||||
<h1 className="mb-8 text-xl font-semibold">家庭记账</h1>
|
||||
<form onSubmit={submit} className="w-full max-w-xs space-y-3">
|
||||
<Input
|
||||
value={username}
|
||||
onChange={(e) => setUsername(e.target.value)}
|
||||
placeholder="用户名"
|
||||
autoCapitalize="none"
|
||||
autoComplete="username"
|
||||
className="h-11"
|
||||
/>
|
||||
<Input
|
||||
type="password"
|
||||
value={password}
|
||||
onChange={(e) => setPassword(e.target.value)}
|
||||
placeholder="密码"
|
||||
autoComplete="current-password"
|
||||
className="h-11"
|
||||
/>
|
||||
{error && <p className="text-sm text-destructive">{error}</p>}
|
||||
<Button type="submit" className="h-11 w-full" disabled={busy || !username || !password}>
|
||||
{busy ? '登录中…' : '登录'}
|
||||
</Button>
|
||||
</form>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,375 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
|
||||
import { toast } from 'sonner';
|
||||
import { Bell, BookOpen, ChevronRight, LogOut, Palette, PiggyBank, Plus, Shapes, Smartphone } from 'lucide-react';
|
||||
import { api, type BillType, type Category } from '@/lib/api';
|
||||
import { money, monthKey } from '@/lib/format';
|
||||
import { ICON_LIST } from '@/lib/icon-list';
|
||||
import { ICON_STYLES, iconUrl, setIconStyle, useIconStyle } from '@/lib/icon-style';
|
||||
import { useMeta } from '@/lib/meta';
|
||||
import { cn } from '@/lib/utils';
|
||||
import { CategoryIcon } from '@/components/category-icon';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle } from '@/components/ui/dialog';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Switch } from '@/components/ui/switch';
|
||||
|
||||
type Panel = 'budget' | 'categories' | 'books' | 'install' | null;
|
||||
|
||||
export default function MePage() {
|
||||
const meta = useMeta();
|
||||
const qc = useQueryClient();
|
||||
const [panel, setPanel] = useState<Panel>(null);
|
||||
const me = meta.member(meta.me.memberId);
|
||||
|
||||
const logout = async () => {
|
||||
await api.logout();
|
||||
qc.clear();
|
||||
location.reload();
|
||||
};
|
||||
|
||||
return (
|
||||
<div>
|
||||
<header className="pt-safe px-4 pt-6 pb-4">
|
||||
<div className="flex items-center gap-3">
|
||||
<span className="flex size-12 items-center justify-center rounded-full text-lg font-semibold text-white" style={{ backgroundColor: me?.color }}>
|
||||
{me?.name.slice(0, 1)}
|
||||
</span>
|
||||
<div>
|
||||
<div className="font-semibold">{me?.name}</div>
|
||||
<div className="text-xs text-muted-foreground">账号 {meta.me.username}</div>
|
||||
</div>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<div className="space-y-3 px-4">
|
||||
<div className="overflow-hidden rounded-2xl bg-card shadow-sm">
|
||||
<Row icon={<PiggyBank className="size-5 text-emerald-500" />} label="预算设置" onClick={() => setPanel('budget')} />
|
||||
<Row icon={<Shapes className="size-5 text-orange-500" />} label="分类管理" onClick={() => setPanel('categories')} />
|
||||
<Row icon={<BookOpen className="size-5 text-sky-500" />} label="账本" onClick={() => setPanel('books')} />
|
||||
</div>
|
||||
<IconStylePicker />
|
||||
<PushSettings />
|
||||
<div className="overflow-hidden rounded-2xl bg-card shadow-sm">
|
||||
<Row icon={<Smartphone className="size-5 text-violet-500" />} label="添加到手机桌面" onClick={() => setPanel('install')} />
|
||||
<Row icon={<LogOut className="size-5 text-muted-foreground" />} label="退出登录" onClick={logout} />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<BudgetDialog open={panel === 'budget'} onClose={() => setPanel(null)} />
|
||||
<CategoryDialog open={panel === 'categories'} onClose={() => setPanel(null)} />
|
||||
<BooksDialog open={panel === 'books'} onClose={() => setPanel(null)} />
|
||||
<Dialog open={panel === 'install'} onOpenChange={(o) => !o && setPanel(null)}>
|
||||
<DialogContent className="max-w-sm">
|
||||
<DialogHeader><DialogTitle>添加到手机桌面</DialogTitle></DialogHeader>
|
||||
<ol className="list-decimal space-y-2 pl-5 text-sm leading-relaxed">
|
||||
<li>用 iPhone 自带的 <b>Safari</b> 打开本网站</li>
|
||||
<li>点底部的「分享」按钮(方框加向上箭头)</li>
|
||||
<li>选择「添加到主屏幕」</li>
|
||||
<li>之后从桌面图标打开,就像 App 一样全屏使用,也能收到预算提醒</li>
|
||||
</ol>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function Row({ icon, label, onClick, right }: { icon: React.ReactNode; label: string; onClick?: () => void; right?: React.ReactNode }) {
|
||||
return (
|
||||
<button onClick={onClick} className="flex w-full items-center gap-3 border-b px-4 py-3.5 text-left last:border-b-0 active:bg-muted">
|
||||
{icon}
|
||||
<span className="flex-1 text-sm">{label}</span>
|
||||
{right ?? <ChevronRight className="size-4 text-muted-foreground" />}
|
||||
</button>
|
||||
);
|
||||
}
|
||||
|
||||
function urlBase64ToUint8Array(base64: string) {
|
||||
const padding = '='.repeat((4 - (base64.length % 4)) % 4);
|
||||
const raw = atob((base64 + padding).replace(/-/g, '+').replace(/_/g, '/'));
|
||||
return Uint8Array.from(raw, (c) => c.charCodeAt(0));
|
||||
}
|
||||
|
||||
function PushSettings() {
|
||||
const meta = useMeta();
|
||||
const supported = typeof window !== 'undefined' && 'serviceWorker' in navigator && 'PushManager' in window;
|
||||
const [enabled, setEnabled] = useState(false);
|
||||
const [busy, setBusy] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
if (!supported) return;
|
||||
navigator.serviceWorker.ready.then((reg) => reg.pushManager.getSubscription()).then((s) => setEnabled(!!s));
|
||||
}, [supported]);
|
||||
|
||||
const toggle = async (on: boolean) => {
|
||||
setBusy(true);
|
||||
try {
|
||||
const reg = await navigator.serviceWorker.ready;
|
||||
if (on) {
|
||||
const permission = await Notification.requestPermission();
|
||||
if (permission !== 'granted') throw new Error('没有获得通知权限,请在系统设置中允许');
|
||||
const sub = await reg.pushManager.subscribe({
|
||||
userVisibleOnly: true,
|
||||
applicationServerKey: urlBase64ToUint8Array(meta.vapidPublicKey),
|
||||
});
|
||||
await api.subscribePush(sub.toJSON());
|
||||
setEnabled(true);
|
||||
toast.success('预算提醒已开启');
|
||||
} else {
|
||||
const sub = await reg.pushManager.getSubscription();
|
||||
if (sub) {
|
||||
await api.unsubscribePush(sub.endpoint);
|
||||
await sub.unsubscribe();
|
||||
}
|
||||
setEnabled(false);
|
||||
}
|
||||
} catch (e) {
|
||||
toast.error((e as Error).message);
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="overflow-hidden rounded-2xl bg-card shadow-sm">
|
||||
<div className="flex items-center gap-3 px-4 py-3.5">
|
||||
<Bell className="size-5 text-amber-500" />
|
||||
<div className="flex-1">
|
||||
<div className="text-sm">预算提醒推送</div>
|
||||
<div className="text-[11px] text-muted-foreground">
|
||||
{supported ? '预算用到 80% 和超支时通知两个人' : 'iPhone 需先「添加到主屏幕」并从桌面打开'}
|
||||
</div>
|
||||
</div>
|
||||
<Switch checked={enabled} disabled={!supported || busy} onCheckedChange={toggle} />
|
||||
</div>
|
||||
{enabled && (
|
||||
<button className="w-full border-t px-4 py-2.5 text-left text-xs text-primary" onClick={() => api.testPush().then(() => toast.success('已发送测试通知'))}>
|
||||
发送一条测试通知
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function BudgetDialog({ open, onClose }: { open: boolean; onClose: () => void }) {
|
||||
const meta = useMeta();
|
||||
const qc = useQueryClient();
|
||||
const budgets = useQuery({ queryKey: ['budgets', meta.bookId, monthKey()], queryFn: () => api.budgets(meta.bookId), enabled: open });
|
||||
const [editing, setEditing] = useState<{ categoryId: number | null; amount: string } | null>(null);
|
||||
|
||||
const save = useMutation({
|
||||
mutationFn: () => api.setBudget({ bookId: meta.bookId, categoryId: editing!.categoryId, amount: Math.round(Number(editing!.amount) * 100) }),
|
||||
onSuccess: () => { qc.invalidateQueries(); setEditing(null); toast.success('预算已保存'); },
|
||||
onError: (e) => toast.error((e as Error).message),
|
||||
});
|
||||
const remove = useMutation({
|
||||
mutationFn: (id: number) => api.deleteBudget(id),
|
||||
onSuccess: () => qc.invalidateQueries(),
|
||||
});
|
||||
|
||||
const usedCats = new Set(budgets.data?.map((b) => b.categoryId));
|
||||
const book = meta.books.find((b) => b.id === meta.bookId);
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={(o) => !o && onClose()}>
|
||||
<DialogContent className="max-h-[85dvh] max-w-sm overflow-y-auto">
|
||||
<DialogHeader><DialogTitle>每月预算 · {book?.name}</DialogTitle></DialogHeader>
|
||||
{editing ? (
|
||||
<div className="space-y-3">
|
||||
<div className="text-sm">{editing.categoryId ? meta.category(editing.categoryId)?.name : '总预算'}</div>
|
||||
<Input autoFocus inputMode="decimal" placeholder="每月金额" value={editing.amount} onChange={(e) => setEditing({ ...editing, amount: e.target.value })} />
|
||||
<DialogFooter className="flex-row gap-2">
|
||||
<Button variant="outline" className="flex-1" onClick={() => setEditing(null)}>取消</Button>
|
||||
<Button className="flex-1" disabled={!(Number(editing.amount) > 0) || save.isPending} onClick={() => save.mutate()}>保存</Button>
|
||||
</DialogFooter>
|
||||
</div>
|
||||
) : (
|
||||
<div className="space-y-4">
|
||||
<ul className="space-y-2">
|
||||
{budgets.data?.map((b) => (
|
||||
<li key={b.id} className="flex items-center gap-2 text-sm">
|
||||
{b.categoryId ? <CategoryIcon category={meta.category(b.categoryId)} className="size-8" /> : <PiggyBank className="size-8 p-1.5 text-emerald-500" />}
|
||||
<button className="flex-1 text-left" onClick={() => setEditing({ categoryId: b.categoryId, amount: String(b.amount / 100) })}>
|
||||
{b.categoryId ? meta.category(b.categoryId)?.name : '总预算'}
|
||||
<div className="tabular text-xs text-muted-foreground">¥{money(b.amount)} / 月 · 本月已用 {b.percent}%</div>
|
||||
</button>
|
||||
<button className="text-xs text-destructive" onClick={() => remove.mutate(b.id)}>删除</button>
|
||||
</li>
|
||||
))}
|
||||
{budgets.data?.length === 0 && <li className="text-sm text-muted-foreground">还没有设置预算</li>}
|
||||
</ul>
|
||||
<div>
|
||||
<div className="mb-2 text-xs text-muted-foreground">添加预算</div>
|
||||
<div className="grid grid-cols-5 gap-2">
|
||||
{!usedCats.has(null) && (
|
||||
<button className="flex flex-col items-center gap-1" onClick={() => setEditing({ categoryId: null, amount: '' })}>
|
||||
<span className="flex size-10 items-center justify-center rounded-2xl bg-emerald-500/15"><PiggyBank className="size-5 text-emerald-600" /></span>
|
||||
<span className="text-[11px]">总预算</span>
|
||||
</button>
|
||||
)}
|
||||
{meta.roots('expense').filter((c) => !usedCats.has(c.id)).map((c) => (
|
||||
<button key={c.id} className="flex flex-col items-center gap-1" onClick={() => setEditing({ categoryId: c.id, amount: '' })}>
|
||||
<CategoryIcon category={c} />
|
||||
<span className="line-clamp-1 text-[11px]">{c.name}</span>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
|
||||
function CategoryDialog({ open, onClose }: { open: boolean; onClose: () => void }) {
|
||||
const meta = useMeta();
|
||||
const qc = useQueryClient();
|
||||
const [type, setType] = useState<BillType>('expense');
|
||||
const [edit, setEdit] = useState<{ id?: number; parentId: number | null; name: string; icon: string | null; hidden: boolean } | null>(null);
|
||||
const style = useIconStyle();
|
||||
const mumu = useQuery({ queryKey: ['icons'], queryFn: api.icons, enabled: open, staleTime: Infinity });
|
||||
const choices = [...(mumu.data?.names ?? []).map((n) => `mumu:${n}`), ...ICON_LIST];
|
||||
|
||||
const all = meta.categories.filter((c) => c.type === type);
|
||||
const roots = all.filter((c) => c.parentId === null);
|
||||
|
||||
const save = useMutation({
|
||||
mutationFn: async () => {
|
||||
if (!edit) return;
|
||||
if (edit.id) await api.updateCategory(edit.id, { name: edit.name, icon: edit.icon, hidden: edit.hidden });
|
||||
else await api.addCategory({ parentId: edit.parentId, type, name: edit.name, icon: edit.icon });
|
||||
},
|
||||
onSuccess: () => { qc.invalidateQueries({ queryKey: ['meta'] }); setEdit(null); },
|
||||
onError: (e) => toast.error((e as Error).message),
|
||||
});
|
||||
|
||||
const open_ = (c: Category) => setEdit({ id: c.id, parentId: c.parentId, name: c.name, icon: c.icon, hidden: !!c.hidden });
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={(o) => !o && (edit ? setEdit(null) : onClose())}>
|
||||
<DialogContent className="max-h-[85dvh] max-w-sm overflow-y-auto">
|
||||
<DialogHeader><DialogTitle>{edit ? (edit.id ? '编辑分类' : '新建分类') : '分类管理'}</DialogTitle></DialogHeader>
|
||||
{edit ? (
|
||||
<div className="space-y-3">
|
||||
{edit.parentId && <div className="text-xs text-muted-foreground">所属:{meta.category(edit.parentId)?.name}</div>}
|
||||
<Input value={edit.name} maxLength={20} placeholder="分类名称" onChange={(e) => setEdit({ ...edit, name: e.target.value })} />
|
||||
<div className="grid max-h-56 grid-cols-6 gap-2 overflow-y-auto rounded-xl bg-muted/50 p-2">
|
||||
{choices.map((icon) => (
|
||||
<button
|
||||
key={icon}
|
||||
onClick={() => setEdit({ ...edit, icon })}
|
||||
className={cn('flex aspect-square items-center justify-center rounded-xl', edit.icon === icon && 'bg-primary/20 ring-2 ring-primary')}
|
||||
>
|
||||
<img src={iconUrl(icon, style)} alt="" className="size-7" loading="lazy" />
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
{edit.id && (
|
||||
<label className="flex items-center justify-between text-sm">
|
||||
隐藏(记账时不显示,历史账单保留)
|
||||
<Switch checked={edit.hidden} onCheckedChange={(v) => setEdit({ ...edit, hidden: v })} />
|
||||
</label>
|
||||
)}
|
||||
<DialogFooter className="flex-row gap-2">
|
||||
<Button variant="outline" className="flex-1" onClick={() => setEdit(null)}>取消</Button>
|
||||
<Button className="flex-1" disabled={!edit.name.trim() || save.isPending} onClick={() => save.mutate()}>保存</Button>
|
||||
</DialogFooter>
|
||||
</div>
|
||||
) : (
|
||||
<div className="space-y-3">
|
||||
<div className="flex rounded-full bg-muted p-0.5 text-xs">
|
||||
{(['expense', 'income'] as const).map((t) => (
|
||||
<button key={t} onClick={() => setType(t)} className={cn('flex-1 rounded-full py-1', type === t && 'bg-card font-medium shadow-sm')}>
|
||||
{t === 'expense' ? '支出' : '收入'}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
{roots.map((r) => (
|
||||
<div key={r.id} className={cn('rounded-xl border p-2', r.hidden && 'opacity-50')}>
|
||||
<button className="flex w-full items-center gap-2 text-left text-sm font-medium" onClick={() => open_(r)}>
|
||||
<CategoryIcon category={r} className="size-8" />
|
||||
{r.name}
|
||||
</button>
|
||||
<div className="mt-2 flex flex-wrap gap-1.5">
|
||||
{all.filter((c) => c.parentId === r.id).map((c) => (
|
||||
<button key={c.id} onClick={() => open_(c)} className={cn('flex items-center gap-1 rounded-full bg-muted py-0.5 pr-2 pl-0.5 text-xs', c.hidden && 'line-through opacity-50')}>
|
||||
<CategoryIcon category={c} className="size-5 rounded-full bg-transparent" />
|
||||
{c.name}
|
||||
</button>
|
||||
))}
|
||||
<button onClick={() => setEdit({ parentId: r.id, name: '', icon: null, hidden: false })} className="flex items-center rounded-full border border-dashed px-2 py-0.5 text-xs text-muted-foreground">
|
||||
<Plus className="size-3" />子类
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
<Button variant="outline" className="w-full" onClick={() => setEdit({ parentId: null, name: '', icon: null, hidden: false })}>
|
||||
<Plus className="size-4" /> 新建一级分类
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
|
||||
function BooksDialog({ open, onClose }: { open: boolean; onClose: () => void }) {
|
||||
const meta = useMeta();
|
||||
const qc = useQueryClient();
|
||||
const [name, setName] = useState('');
|
||||
const add = useMutation({
|
||||
mutationFn: () => api.addBook(name.trim()),
|
||||
onSuccess: () => { qc.invalidateQueries({ queryKey: ['meta'] }); setName(''); },
|
||||
onError: (e) => toast.error((e as Error).message),
|
||||
});
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={(o) => !o && onClose()}>
|
||||
<DialogContent className="max-w-sm">
|
||||
<DialogHeader><DialogTitle>账本</DialogTitle></DialogHeader>
|
||||
<ul className="space-y-1">
|
||||
{meta.books.map((b) => (
|
||||
<li key={b.id}>
|
||||
<button
|
||||
onClick={() => { meta.setBookId(b.id); onClose(); }}
|
||||
className={cn('w-full rounded-lg px-3 py-2.5 text-left text-sm', b.id === meta.bookId && 'bg-muted font-medium')}
|
||||
>
|
||||
{b.name}
|
||||
</button>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
<div className="flex gap-2">
|
||||
<Input placeholder="新账本名称,如:旅行" value={name} maxLength={20} onChange={(e) => setName(e.target.value)} />
|
||||
<Button disabled={!name.trim() || add.isPending} onClick={() => add.mutate()}>添加</Button>
|
||||
</div>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
|
||||
function IconStylePicker() {
|
||||
const style = useIconStyle();
|
||||
const meta = useMeta();
|
||||
const sample = meta.roots('expense').slice(0, 1)[0];
|
||||
return (
|
||||
<div className="rounded-2xl bg-card px-4 py-3.5 shadow-sm">
|
||||
<div className="mb-3 flex items-center gap-3">
|
||||
<Palette className="size-5 text-pink-500" />
|
||||
<span className="text-sm">图标风格</span>
|
||||
</div>
|
||||
<div className="grid grid-cols-5 gap-2">
|
||||
{ICON_STYLES.map((s) => (
|
||||
<button
|
||||
key={s.id}
|
||||
onClick={() => setIconStyle(s.id)}
|
||||
className={cn('flex flex-col items-center gap-1 rounded-xl py-2', style === s.id && 'bg-primary/10 ring-2 ring-primary')}
|
||||
>
|
||||
{sample?.icon && <img src={iconUrl(sample.icon, s.id)} alt="" className="size-8" />}
|
||||
<span className="text-[11px]">{s.label}</span>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,172 @@
|
||||
import { useNavigate, useParams } from 'react-router';
|
||||
import { useQuery } from '@tanstack/react-query';
|
||||
import { Bar, BarChart, ResponsiveContainer, Tooltip, XAxis } from 'recharts';
|
||||
import { ChevronLeft } from 'lucide-react';
|
||||
import { api } from '@/lib/api';
|
||||
import { cst, money, percentChange } from '@/lib/format';
|
||||
import { useMeta } from '@/lib/meta';
|
||||
import { cn } from '@/lib/utils';
|
||||
import { CategoryIcon } from '@/components/category-icon';
|
||||
import { YearSwitcher } from '@/components/pickers';
|
||||
import { Skeleton } from '@/components/ui/skeleton';
|
||||
import { PALETTE } from './stats';
|
||||
|
||||
export default function ReportPage() {
|
||||
const meta = useMeta();
|
||||
const navigate = useNavigate();
|
||||
const year = Number(useParams().year) || new Date().getFullYear();
|
||||
const report = useQuery({ queryKey: ['report', year, meta.bookId], queryFn: () => api.report(year, meta.bookId) });
|
||||
const r = report.data;
|
||||
|
||||
const change = r ? percentChange(r.totals.expense, r.previous.expense) : null;
|
||||
const months = r?.monthly.length || 1;
|
||||
const topMonth = r?.monthly.reduce((a, b) => (b.expense > a.expense ? b : a), r.monthly[0]);
|
||||
const memberTotal = (r?.members ?? []).reduce((s, m) => s + m.own + m.shared, 0);
|
||||
const sharedTotal = (r?.members ?? []).reduce((s, m) => s + m.shared, 0);
|
||||
|
||||
return (
|
||||
<div>
|
||||
<header className="pt-safe sticky top-0 z-30 bg-background/95 backdrop-blur">
|
||||
<div className="flex h-12 items-center justify-between px-2">
|
||||
<button className="p-2" onClick={() => navigate(-1)} aria-label="返回"><ChevronLeft className="size-5" /></button>
|
||||
<YearSwitcher year={year} onChange={(y) => navigate(`/report/${y}`, { replace: true })} />
|
||||
<div className="w-9" />
|
||||
</div>
|
||||
</header>
|
||||
|
||||
{!r ? (
|
||||
<div className="space-y-3 px-4">{[0, 1, 2].map((i) => <Skeleton key={i} className="h-40 rounded-2xl" />)}</div>
|
||||
) : r.totals.count === 0 ? (
|
||||
<div className="py-20 text-center text-sm text-muted-foreground">{year} 年没有记账数据</div>
|
||||
) : (
|
||||
<div className="space-y-3 px-4">
|
||||
<section className="rounded-3xl bg-gradient-to-br from-orange-400 to-rose-400 p-5 text-white shadow-md">
|
||||
<div className="text-sm opacity-90">{year} 年,我们一共花了</div>
|
||||
<div className="tabular mt-1 text-4xl font-bold">¥{money(r.totals.expense)}</div>
|
||||
<div className="mt-2 text-sm opacity-90">
|
||||
{change === null ? '' : change >= 0 ? `比去年多 ${change}%` : `比去年少 ${-change}%`}
|
||||
{change === null ? '' : ' · '}月均 ¥{money(Math.round(r.totals.expense / months))}
|
||||
</div>
|
||||
<div className="mt-4 grid grid-cols-3 gap-2 text-center text-xs">
|
||||
<Stat label="收入" value={`¥${money(r.totals.income)}`} />
|
||||
<Stat label="结余" value={`¥${money(r.totals.income - r.totals.expense)}`} />
|
||||
<Stat label="记账" value={`${r.activeDays}天 · ${r.totals.count}笔`} />
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<Card title="每月支出">
|
||||
<div className="h-40">
|
||||
<ResponsiveContainer width="100%" height="100%">
|
||||
<BarChart data={r.monthly.map((m) => ({ ...m, label: `${Number(m.month.slice(5))}月`, v: m.expense / 100 }))} margin={{ left: 0, right: 0, top: 4, bottom: 0 }}>
|
||||
<XAxis dataKey="label" tickLine={false} axisLine={false} fontSize={10} interval={0} />
|
||||
<Tooltip cursor={{ fill: 'var(--muted)' }} formatter={(v) => [`¥${money(Number(v) * 100)}`, '支出']} contentStyle={{ borderRadius: 12, fontSize: 12 }} />
|
||||
<Bar dataKey="v" fill="#f97316" radius={[4, 4, 0, 0]} />
|
||||
</BarChart>
|
||||
</ResponsiveContainer>
|
||||
</div>
|
||||
{topMonth && (
|
||||
<p className="mt-2 text-xs text-muted-foreground">花得最多的是 {Number(topMonth.month.slice(5))} 月:¥{money(topMonth.expense)}</p>
|
||||
)}
|
||||
</Card>
|
||||
|
||||
<Card title="钱都花在哪了">
|
||||
<ul className="space-y-2">
|
||||
{r.categories.slice(0, 8).map((c, i) => {
|
||||
const pct = (c.amount / r.totals.expense) * 100;
|
||||
return (
|
||||
<li key={c.categoryId} className="flex items-center gap-3">
|
||||
<CategoryIcon category={meta.category(c.categoryId)} className="size-9" />
|
||||
<div className="flex-1">
|
||||
<div className="flex justify-between text-sm">
|
||||
<span>{meta.category(c.categoryId)?.name}</span>
|
||||
<span className="tabular">¥{money(c.amount)} <span className="text-xs text-muted-foreground">{pct.toFixed(0)}%</span></span>
|
||||
</div>
|
||||
<div className="mt-1 h-1.5 rounded-full bg-muted">
|
||||
<div className="h-full rounded-full" style={{ width: `${pct}%`, backgroundColor: PALETTE[i % PALETTE.length] }} />
|
||||
</div>
|
||||
</div>
|
||||
</li>
|
||||
);
|
||||
})}
|
||||
</ul>
|
||||
</Card>
|
||||
|
||||
<Card title="我们俩">
|
||||
<div className="flex h-3 overflow-hidden rounded-full">
|
||||
{r.members.map((m) => (
|
||||
<div key={m.memberId} style={{ width: `${((m.own + m.shared) / (memberTotal || 1)) * 100}%`, backgroundColor: meta.member(m.memberId)?.color }} />
|
||||
))}
|
||||
</div>
|
||||
<div className="mt-3 grid grid-cols-2 gap-3">
|
||||
{r.members.map((m) => {
|
||||
const mem = meta.member(m.memberId);
|
||||
return (
|
||||
<div key={m.memberId}>
|
||||
<div className="text-xs" style={{ color: mem?.color }}>{mem?.name}</div>
|
||||
<div className="tabular font-semibold">¥{money(m.own + m.shared)}</div>
|
||||
<div className="tabular text-[11px] text-muted-foreground">个人 {money(m.own)} · 共同 {money(m.shared)}</div>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
<p className="mt-3 text-xs text-muted-foreground">共同支出占 {memberTotal ? Math.round((sharedTotal / memberTotal) * 100) : 0}%</p>
|
||||
</Card>
|
||||
|
||||
<Card title="最常记的">
|
||||
<div className="grid grid-cols-5 gap-2">
|
||||
{r.habits.map((h) => (
|
||||
<div key={h.categoryId} className="flex flex-col items-center gap-1 text-center">
|
||||
<CategoryIcon category={meta.category(h.categoryId)} className="size-11" />
|
||||
<span className="line-clamp-1 text-[11px]">{meta.category(h.categoryId)?.name}</span>
|
||||
<span className="text-[10px] text-muted-foreground">{h.count}次</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
{r.busiestDay && (
|
||||
<p className="mt-3 text-xs text-muted-foreground">
|
||||
花钱最多的一天是 {r.busiestDay.day.slice(5).replace('-', '月')}日,记了 {r.busiestDay.count} 笔,共 ¥{money(r.busiestDay.amount)}
|
||||
</p>
|
||||
)}
|
||||
</Card>
|
||||
|
||||
<Card title="年度大额支出">
|
||||
<ul className="divide-y">
|
||||
{r.topBills.map((b, i) => {
|
||||
const d = cst(b.time);
|
||||
return (
|
||||
<li key={b.id} className="flex items-center gap-3 py-2">
|
||||
<span className={cn('w-4 text-center text-sm font-semibold', i < 3 ? 'text-primary' : 'text-muted-foreground')}>{i + 1}</span>
|
||||
<CategoryIcon category={meta.category(b.categoryId)} className="size-8" />
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="truncate text-sm">{meta.categoryLabel(b.categoryId)}</div>
|
||||
<div className="truncate text-xs text-muted-foreground">{d.month}月{d.day}日{b.note && ` · ${b.note}`}</div>
|
||||
</div>
|
||||
<span className="tabular text-sm font-medium">¥{money(b.amount)}</span>
|
||||
</li>
|
||||
);
|
||||
})}
|
||||
</ul>
|
||||
</Card>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function Stat({ label, value }: { label: string; value: string }) {
|
||||
return (
|
||||
<div className="rounded-xl bg-white/15 py-2">
|
||||
<div className="opacity-85">{label}</div>
|
||||
<div className="tabular mt-0.5 font-medium">{value}</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function Card({ title, children }: { title: string; children: React.ReactNode }) {
|
||||
return (
|
||||
<section className="rounded-2xl bg-card p-4 shadow-sm">
|
||||
<h2 className="mb-3 text-sm font-medium">{title}</h2>
|
||||
{children}
|
||||
</section>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,164 @@
|
||||
import { useState } from 'react';
|
||||
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
|
||||
import { toast } from 'sonner';
|
||||
import { ArrowRight, Trash2 } from 'lucide-react';
|
||||
import { api } from '@/lib/api';
|
||||
import { cst, money } from '@/lib/format';
|
||||
import { useMeta } from '@/lib/meta';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle } from '@/components/ui/dialog';
|
||||
import { Input } from '@/components/ui/input';
|
||||
|
||||
export default function SettlePage() {
|
||||
const meta = useMeta();
|
||||
const qc = useQueryClient();
|
||||
const settle = useQuery({ queryKey: ['settle'], queryFn: api.settle });
|
||||
const [form, setForm] = useState<{ fromId: number; toId: number; amount: string; note: string } | null>(null);
|
||||
|
||||
const add = useMutation({
|
||||
mutationFn: () =>
|
||||
api.addSettlement({ fromId: form!.fromId, toId: form!.toId, amount: Math.round(Number(form!.amount) * 100), note: form!.note }),
|
||||
onSuccess: () => {
|
||||
qc.invalidateQueries({ queryKey: ['settle'] });
|
||||
setForm(null);
|
||||
toast.success('已记录结算');
|
||||
},
|
||||
onError: (e) => toast.error((e as Error).message),
|
||||
});
|
||||
const remove = useMutation({
|
||||
mutationFn: (id: number) => api.deleteSettlement(id),
|
||||
onSuccess: () => qc.invalidateQueries({ queryKey: ['settle'] }),
|
||||
});
|
||||
|
||||
const data = settle.data;
|
||||
const t = data?.transfers[0];
|
||||
const [a, b] = meta.members;
|
||||
|
||||
return (
|
||||
<div>
|
||||
<header className="pt-safe sticky top-0 z-30 bg-background/95 backdrop-blur">
|
||||
<div className="flex h-12 items-center px-4 text-base font-semibold">共同支出结算</div>
|
||||
</header>
|
||||
|
||||
<div className="space-y-3 px-4">
|
||||
<section className="rounded-3xl bg-card p-5 text-center shadow-sm">
|
||||
{!data ? (
|
||||
<div className="py-6 text-muted-foreground">加载中…</div>
|
||||
) : t ? (
|
||||
<>
|
||||
<div className="flex items-center justify-center gap-3 text-sm">
|
||||
<Name id={t.from} />
|
||||
<ArrowRight className="size-4 text-muted-foreground" />
|
||||
<Name id={t.to} />
|
||||
</div>
|
||||
<div className="mt-2 text-xs text-muted-foreground">{meta.member(t.from)?.name} 需要给 {meta.member(t.to)?.name}</div>
|
||||
<div className="tabular mt-1 text-4xl font-bold text-primary">¥{money(t.amount, { decimals: true })}</div>
|
||||
<Button
|
||||
className="mt-4 h-10 w-full rounded-full"
|
||||
onClick={() => setForm({ fromId: t.from, toId: t.to, amount: String(t.amount / 100), note: '' })}
|
||||
>
|
||||
记录一笔转账
|
||||
</Button>
|
||||
</>
|
||||
) : (
|
||||
<div className="py-4">
|
||||
<div className="text-3xl">🎉</div>
|
||||
<div className="mt-2 font-medium">已经结清</div>
|
||||
<div className="mt-1 text-xs text-muted-foreground">共同支出互不相欠</div>
|
||||
</div>
|
||||
)}
|
||||
</section>
|
||||
|
||||
{data && (
|
||||
<section className="rounded-2xl bg-card p-4 shadow-sm">
|
||||
<h2 className="mb-3 text-sm font-medium">明细</h2>
|
||||
<div className="grid grid-cols-2 gap-3">
|
||||
{data.balances.map((x) => (
|
||||
<div key={x.memberId} className="rounded-xl bg-muted/60 p-3 text-sm">
|
||||
<Name id={x.memberId} />
|
||||
<div className="mt-2 flex justify-between text-xs text-muted-foreground"><span>付款</span><span className="tabular">¥{money(x.paid)}</span></div>
|
||||
<div className="flex justify-between text-xs text-muted-foreground"><span>应承担</span><span className="tabular">¥{money(x.consumed)}</span></div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
<p className="mt-3 text-xs leading-relaxed text-muted-foreground">
|
||||
每笔支出按「谁付的」和「谁花的」计算:共同支出默认两人平分,付款多的一方会被记为对方欠款。
|
||||
转账记录后余额会相应减少。
|
||||
</p>
|
||||
</section>
|
||||
)}
|
||||
|
||||
{data && data.history.length > 0 && (
|
||||
<section className="rounded-2xl bg-card p-4 shadow-sm">
|
||||
<h2 className="mb-2 text-sm font-medium">结算记录</h2>
|
||||
<ul className="divide-y">
|
||||
{data.history.map((h) => {
|
||||
const d = cst(h.time);
|
||||
return (
|
||||
<li key={h.id} className="flex items-center gap-2 py-2 text-sm">
|
||||
<span className="text-xs text-muted-foreground">{d.year}/{d.month}/{d.day}</span>
|
||||
<span className="flex-1 truncate">
|
||||
{meta.member(h.fromId)?.name} → {meta.member(h.toId)?.name}
|
||||
{h.note && <span className="text-muted-foreground"> · {h.note}</span>}
|
||||
</span>
|
||||
<span className="tabular">¥{money(h.amount)}</span>
|
||||
<button
|
||||
className="p-1 text-muted-foreground"
|
||||
onClick={() => confirm('删除这条结算记录?') && remove.mutate(h.id)}
|
||||
aria-label="删除"
|
||||
>
|
||||
<Trash2 className="size-4" />
|
||||
</button>
|
||||
</li>
|
||||
);
|
||||
})}
|
||||
</ul>
|
||||
</section>
|
||||
)}
|
||||
|
||||
{a && b && !t && (
|
||||
<Button variant="outline" className="w-full" onClick={() => setForm({ fromId: b.id, toId: a.id, amount: '', note: '' })}>
|
||||
手动记录转账
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<Dialog open={!!form} onOpenChange={(o) => !o && setForm(null)}>
|
||||
<DialogContent className="max-w-sm">
|
||||
<DialogHeader><DialogTitle>记录转账</DialogTitle></DialogHeader>
|
||||
{form && (
|
||||
<div className="space-y-3">
|
||||
<div className="flex items-center gap-2 text-sm">
|
||||
<select value={form.fromId} onChange={(e) => setForm({ ...form, fromId: Number(e.target.value) })} className="h-9 flex-1 rounded-lg bg-muted px-2">
|
||||
{meta.members.map((m) => <option key={m.id} value={m.id}>{m.name}</option>)}
|
||||
</select>
|
||||
<span className="text-muted-foreground">付给</span>
|
||||
<select value={form.toId} onChange={(e) => setForm({ ...form, toId: Number(e.target.value) })} className="h-9 flex-1 rounded-lg bg-muted px-2">
|
||||
{meta.members.map((m) => <option key={m.id} value={m.id}>{m.name}</option>)}
|
||||
</select>
|
||||
</div>
|
||||
<Input inputMode="decimal" placeholder="金额" value={form.amount} onChange={(e) => setForm({ ...form, amount: e.target.value })} />
|
||||
<Input placeholder="备注(可选)" value={form.note} onChange={(e) => setForm({ ...form, note: e.target.value })} />
|
||||
</div>
|
||||
)}
|
||||
<DialogFooter>
|
||||
<Button onClick={() => add.mutate()} disabled={add.isPending || !form || !(Number(form.amount) > 0)}>保存</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function Name({ id }: { id: number }) {
|
||||
const m = useMeta().member(id);
|
||||
if (!m) return null;
|
||||
return (
|
||||
<span className="inline-flex items-center gap-1.5 font-medium">
|
||||
<span className="flex size-6 items-center justify-center rounded-full text-[11px] text-white" style={{ backgroundColor: m.color }}>
|
||||
{m.name.slice(0, 1)}
|
||||
</span>
|
||||
{m.name}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,234 @@
|
||||
import { useMemo, useState } from 'react';
|
||||
import { Link } from 'react-router';
|
||||
import { useQuery } from '@tanstack/react-query';
|
||||
import { Bar, BarChart, Cell, Pie, PieChart, ResponsiveContainer, Tooltip, XAxis, YAxis } from 'recharts';
|
||||
import { ChevronLeft, ChevronRight, FileBarChart } from 'lucide-react';
|
||||
import { api, type BillType } from '@/lib/api';
|
||||
import { money, moneyShort, monthKey, monthLabel, monthStart, shiftMonth, yearRange } from '@/lib/format';
|
||||
import { useMeta } from '@/lib/meta';
|
||||
import { cn } from '@/lib/utils';
|
||||
import { CategoryIcon } from '@/components/category-icon';
|
||||
import { BookSwitcher, MemberFilter, MonthSwitcher, YearSwitcher } from '@/components/pickers';
|
||||
import { BillList } from '@/components/bill-list';
|
||||
|
||||
export const PALETTE = ['#f97316', '#3b82f6', '#22c55e', '#eab308', '#a855f7', '#ec4899', '#14b8a6', '#ef4444', '#6366f1', '#84cc16'];
|
||||
|
||||
export default function StatsPage() {
|
||||
const meta = useMeta();
|
||||
const [period, setPeriod] = useState<'month' | 'year'>('month');
|
||||
const [month, setMonth] = useState(monthKey());
|
||||
const [year, setYear] = useState(new Date().getFullYear());
|
||||
const [type, setType] = useState<BillType>('expense');
|
||||
const [memberId, setMemberId] = useState<number | null>(null);
|
||||
const [parentId, setParentId] = useState<number | null>(null);
|
||||
const [leafId, setLeafId] = useState<number | null>(null);
|
||||
|
||||
const range = period === 'month' ? { month } : yearRange(year);
|
||||
const rangeKey = period === 'month' ? month : String(year);
|
||||
|
||||
const cats = useQuery({
|
||||
queryKey: ['catstats', meta.bookId, rangeKey, type, memberId, parentId],
|
||||
queryFn: () =>
|
||||
api.categoryStats({ bookId: meta.bookId, ...range, type, memberId: memberId ?? undefined, parentId: parentId ?? undefined }),
|
||||
});
|
||||
|
||||
// Member comparison: 6 months ending at the chosen month, or the chosen year.
|
||||
const compareRange = period === 'month'
|
||||
? { from: monthStart(shiftMonth(month, -5)), to: monthStart(shiftMonth(month, 1)) }
|
||||
: yearRange(year);
|
||||
const members = useQuery({
|
||||
queryKey: ['memberstats', meta.bookId, rangeKey, period],
|
||||
queryFn: () => api.memberStats({ bookId: meta.bookId, ...compareRange }),
|
||||
});
|
||||
const current = useQuery({
|
||||
queryKey: ['memberstats-current', meta.bookId, rangeKey],
|
||||
queryFn: () => api.memberStats({ bookId: meta.bookId, ...range }),
|
||||
});
|
||||
const budgets = useQuery({
|
||||
queryKey: ['budgets', meta.bookId, month],
|
||||
queryFn: () => api.budgets(meta.bookId, month),
|
||||
enabled: period === 'month',
|
||||
});
|
||||
const leafBills = useQuery({
|
||||
queryKey: ['bills', meta.bookId, rangeKey, 'leaf', leafId, memberId],
|
||||
queryFn: () => api.bills({ bookId: meta.bookId, ...range, categoryId: leafId!, memberId: memberId ?? undefined }),
|
||||
enabled: leafId !== null,
|
||||
});
|
||||
|
||||
const total = cats.data?.reduce((s, c) => s + c.amount, 0) ?? 0;
|
||||
const pieData = (cats.data ?? []).map((c, i) => ({
|
||||
name: meta.category(c.categoryId)?.name ?? '?',
|
||||
value: c.amount,
|
||||
fill: PALETTE[i % PALETTE.length],
|
||||
}));
|
||||
|
||||
const chartData = useMemo(() => {
|
||||
const byMonth = new Map<string, Record<string, number | string>>();
|
||||
for (const r of members.data?.monthly ?? []) {
|
||||
if (!byMonth.has(r.month)) byMonth.set(r.month, { month: r.month });
|
||||
byMonth.get(r.month)![`m${r.memberId}`] = r.amount / 100;
|
||||
}
|
||||
return [...byMonth.values()].map((r) => ({ ...r, label: `${Number(String(r.month).slice(5))}月` }));
|
||||
}, [members.data]);
|
||||
|
||||
const parent = meta.category(parentId);
|
||||
|
||||
return (
|
||||
<div>
|
||||
<header className="pt-safe sticky top-0 z-30 bg-background/95 backdrop-blur">
|
||||
<div className="flex h-12 items-center justify-between px-4">
|
||||
<BookSwitcher />
|
||||
{period === 'month' ? <MonthSwitcher month={month} onChange={setMonth} /> : <YearSwitcher year={year} onChange={setYear} />}
|
||||
<div className="flex rounded-full bg-muted p-0.5 text-xs">
|
||||
{(['month', 'year'] as const).map((p) => (
|
||||
<button key={p} onClick={() => setPeriod(p)} className={cn('rounded-full px-2.5 py-1', period === p && 'bg-card font-medium shadow-sm')}>
|
||||
{p === 'month' ? '月' : '年'}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<div className="space-y-3 px-4">
|
||||
<Link
|
||||
to={`/report/${period === 'year' ? year : Number(month.slice(0, 4))}`}
|
||||
className="flex items-center gap-3 rounded-2xl bg-card p-3 shadow-sm"
|
||||
>
|
||||
<span className="flex size-9 items-center justify-center rounded-xl bg-primary/15 text-primary"><FileBarChart className="size-5" /></span>
|
||||
<span className="flex-1 text-sm font-medium">{period === 'year' ? year : month.slice(0, 4)} 年度报表</span>
|
||||
<ChevronRight className="size-4 text-muted-foreground" />
|
||||
</Link>
|
||||
|
||||
{/* Two-person comparison */}
|
||||
<section className="rounded-2xl bg-card p-4 shadow-sm">
|
||||
<h2 className="mb-3 text-sm font-medium">两人支出对比</h2>
|
||||
<div className="grid grid-cols-2 gap-3">
|
||||
{meta.members.map((m) => {
|
||||
const b = current.data?.breakdown.find((x) => x.memberId === m.id);
|
||||
const sum = (b?.own ?? 0) + (b?.shared ?? 0);
|
||||
return (
|
||||
<div key={m.id} className="rounded-xl bg-muted/60 p-3">
|
||||
<div className="text-xs" style={{ color: m.color }}>{m.name}</div>
|
||||
<div className="tabular text-lg font-semibold">¥{money(sum)}</div>
|
||||
<div className="tabular mt-0.5 text-[11px] text-muted-foreground">个人 {money(b?.own ?? 0)} · 共同分摊 {money(b?.shared ?? 0)}</div>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
<div className="mt-3 h-44">
|
||||
<ResponsiveContainer width="100%" height="100%">
|
||||
<BarChart data={chartData} margin={{ left: -16, right: 0, top: 4, bottom: 0 }}>
|
||||
<XAxis dataKey="label" tickLine={false} axisLine={false} fontSize={11} />
|
||||
<YAxis tickLine={false} axisLine={false} fontSize={10} tickFormatter={(v) => moneyShort(v * 100)} />
|
||||
<Tooltip
|
||||
cursor={{ fill: 'var(--muted)' }}
|
||||
formatter={(v, name) => [`¥${money(Number(v) * 100)}`, meta.member(Number(String(name).slice(1)))?.name]}
|
||||
labelFormatter={(_, p) => (p?.[0] ? monthLabel(String(p[0].payload.month)) : '')}
|
||||
contentStyle={{ borderRadius: 12, fontSize: 12 }}
|
||||
/>
|
||||
{meta.members.map((m) => (
|
||||
<Bar key={m.id} dataKey={`m${m.id}`} fill={m.color} radius={[4, 4, 0, 0]} maxBarSize={18} />
|
||||
))}
|
||||
</BarChart>
|
||||
</ResponsiveContainer>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
{/* Category breakdown */}
|
||||
<section className="rounded-2xl bg-card p-4 shadow-sm">
|
||||
<div className="mb-3 flex items-center justify-between">
|
||||
{parent ? (
|
||||
<button className="flex items-center gap-1 text-sm font-medium" onClick={() => { setParentId(null); setLeafId(null); }}>
|
||||
<ChevronLeft className="size-4" />
|
||||
{parent.name}
|
||||
</button>
|
||||
) : (
|
||||
<div className="flex rounded-full bg-muted p-0.5 text-xs">
|
||||
{(['expense', 'income'] as const).map((t) => (
|
||||
<button key={t} onClick={() => setType(t)} className={cn('rounded-full px-3 py-1', type === t && 'bg-card font-medium shadow-sm')}>
|
||||
{t === 'expense' ? '支出' : '收入'}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
<MemberFilter value={memberId} onChange={setMemberId} />
|
||||
</div>
|
||||
|
||||
<div className="relative mx-auto h-44 w-44">
|
||||
<ResponsiveContainer width="100%" height="100%">
|
||||
<PieChart>
|
||||
<Pie data={pieData} dataKey="value" innerRadius="68%" outerRadius="100%" paddingAngle={1} stroke="none" isAnimationActive={false}>
|
||||
{pieData.map((d) => <Cell key={d.name} fill={d.fill} />)}
|
||||
</Pie>
|
||||
</PieChart>
|
||||
</ResponsiveContainer>
|
||||
<div className="pointer-events-none absolute inset-0 flex flex-col items-center justify-center">
|
||||
<span className="text-xs text-muted-foreground">{type === 'expense' ? '总支出' : '总收入'}</span>
|
||||
<span className="tabular text-lg font-semibold">¥{money(total)}</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<ul className="mt-3 space-y-1">
|
||||
{(cats.data ?? []).map((c, i) => {
|
||||
const cat = meta.category(c.categoryId);
|
||||
const pct = total ? (c.amount / total) * 100 : 0;
|
||||
const drillable = !parentId && cat && meta.childrenOf(cat.id).length > 0;
|
||||
return (
|
||||
<li key={c.categoryId}>
|
||||
<button
|
||||
className="flex w-full items-center gap-3 rounded-xl py-1.5 text-left active:bg-muted"
|
||||
onClick={() => (drillable ? setParentId(c.categoryId) : setLeafId(leafId === c.categoryId ? null : c.categoryId))}
|
||||
>
|
||||
<CategoryIcon category={cat} className="size-9" />
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="flex justify-between text-sm">
|
||||
<span>{cat?.name}<span className="ml-1.5 text-xs text-muted-foreground">{pct.toFixed(1)}% · {c.count}笔</span></span>
|
||||
<span className="tabular">¥{money(c.amount)}</span>
|
||||
</div>
|
||||
<div className="mt-1 h-1.5 overflow-hidden rounded-full bg-muted">
|
||||
<div className="h-full rounded-full" style={{ width: `${pct}%`, backgroundColor: PALETTE[i % PALETTE.length] }} />
|
||||
</div>
|
||||
</div>
|
||||
</button>
|
||||
{leafId === c.categoryId && leafBills.data && (
|
||||
<div className="mt-2 -mx-4"><BillList bills={leafBills.data} memberId={memberId} /></div>
|
||||
)}
|
||||
</li>
|
||||
);
|
||||
})}
|
||||
{cats.data?.length === 0 && <li className="py-6 text-center text-sm text-muted-foreground">暂无数据</li>}
|
||||
</ul>
|
||||
</section>
|
||||
|
||||
{/* Budgets */}
|
||||
{period === 'month' && budgets.data && budgets.data.length > 0 && (
|
||||
<section className="rounded-2xl bg-card p-4 shadow-sm">
|
||||
<h2 className="mb-3 text-sm font-medium">本月预算</h2>
|
||||
<ul className="space-y-3">
|
||||
{budgets.data.map((b) => {
|
||||
const cat = meta.category(b.categoryId);
|
||||
const over = b.percent >= 100;
|
||||
return (
|
||||
<li key={b.id}>
|
||||
<div className="flex justify-between text-sm">
|
||||
<span>{cat ? cat.name : '总预算'}</span>
|
||||
<span className={cn('tabular text-xs', over ? 'text-destructive' : 'text-muted-foreground')}>
|
||||
¥{money(b.spent)} / ¥{money(b.amount)}
|
||||
</span>
|
||||
</div>
|
||||
<div className="mt-1 h-2 overflow-hidden rounded-full bg-muted">
|
||||
<div
|
||||
className={cn('h-full rounded-full', over ? 'bg-destructive' : b.percent >= 80 ? 'bg-amber-500' : 'bg-emerald-500')}
|
||||
style={{ width: `${Math.min(100, b.percent)}%` }}
|
||||
/>
|
||||
</div>
|
||||
</li>
|
||||
);
|
||||
})}
|
||||
</ul>
|
||||
</section>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
/// <reference lib="webworker" />
|
||||
import { cleanupOutdatedCaches, createHandlerBoundToURL, precacheAndRoute } from 'workbox-precaching';
|
||||
import { NavigationRoute, registerRoute } from 'workbox-routing';
|
||||
|
||||
declare const self: ServiceWorkerGlobalScope;
|
||||
|
||||
// App shell is cached for instant start; API calls always go to the network.
|
||||
precacheAndRoute(self.__WB_MANIFEST);
|
||||
cleanupOutdatedCaches();
|
||||
registerRoute(new NavigationRoute(createHandlerBoundToURL('/index.html'), { denylist: [/^\/api\//] }));
|
||||
|
||||
self.addEventListener('install', () => self.skipWaiting());
|
||||
self.addEventListener('activate', (e) => e.waitUntil(self.clients.claim()));
|
||||
|
||||
self.addEventListener('push', (event) => {
|
||||
const data = (() => {
|
||||
try { return event.data?.json() ?? {}; } catch { return { title: '记账', body: event.data?.text() }; }
|
||||
})() as { title?: string; body?: string; url?: string };
|
||||
event.waitUntil(
|
||||
self.registration.showNotification(data.title ?? '记账', {
|
||||
body: data.body,
|
||||
icon: '/app-icon-192.png',
|
||||
badge: '/app-icon-192.png',
|
||||
data: { url: data.url ?? '/' },
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
self.addEventListener('notificationclick', (event) => {
|
||||
event.notification.close();
|
||||
const url = (event.notification.data as { url?: string })?.url ?? '/';
|
||||
event.waitUntil(
|
||||
self.clients.matchAll({ type: 'window', includeUncontrolled: true }).then((list) => {
|
||||
for (const c of list) {
|
||||
if ('focus' in c) {
|
||||
(c as WindowClient).navigate(url);
|
||||
return (c as WindowClient).focus();
|
||||
}
|
||||
}
|
||||
return self.clients.openWindow(url);
|
||||
}),
|
||||
);
|
||||
});
|
||||
Vendored
+1
@@ -0,0 +1 @@
|
||||
/// <reference types="vite-plugin-pwa/client" />
|
||||
Reference in New Issue
Block a user