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:
@@ -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;
|
||||
}
|
||||
Reference in New Issue
Block a user