Files
Flog/src/Page.tsx
T
2026-10-17 11:27:41 +02:00

426 lines
13 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import { useCallback, useEffect, useMemo, useState } from "react";
import type { ChangeEvent } from "react";
import { Data, DataKeys, migrateSuggestions, Suggestions, SuggestionEntry, WebsiteStorage } from "./Storage";
import { Table } from "./Table";
import { AmountTone, formatSigned, getMonth } from "./utils";
import { CategoryGraphs } from "./Charts";
import { SuggestionsManager } from "./Suggestions";
import styled from "styled-components";
import { theme } from "./theme";
const Div = styled.div`
min-height: 100%;
display: flex;
flex-direction: column;
`;
const Header = styled.header`
position: sticky;
top: 0;
z-index: 20;
display: flex;
align-items: center;
justify-content: space-between;
flex-wrap: wrap;
gap: ${theme.spacing.md}px;
padding: ${theme.spacing.md}px ${theme.spacing.xl}px;
background: ${theme.colors.bg};
border-bottom: 1px solid ${theme.colors.border};
@media (max-width: ${theme.breakpoints.mobile}) {
padding: ${theme.spacing.sm}px ${theme.spacing.md}px;
flex-direction: column;
align-items: stretch;
gap: ${theme.spacing.sm}px;
}
`;
const Brand = styled.div`
display: flex;
align-items: baseline;
gap: ${theme.spacing.md}px;
`;
const Title = styled.h1`
margin: 0;
font-size: ${theme.font.sizes.lg};
font-weight: 700;
letter-spacing: 0.02em;
`;
const MonthBadge = styled.span`
font-variant-numeric: tabular-nums;
color: ${theme.colors.textMuted};
font-size: ${theme.font.sizes.sm};
`;
const Controls = styled.div`
display: flex;
align-items: center;
gap: ${theme.spacing.sm}px;
flex-wrap: wrap;
justify-content: flex-end;
@media (max-width: ${theme.breakpoints.mobile}) {
width: 100%;
justify-content: space-between;
gap: ${theme.spacing.xs}px;
}
`;
const MonthInput = styled.input.attrs({ type: "month" })`
min-width: 150px;
max-width: 200px;
@media (max-width: ${theme.breakpoints.mobile}) {
max-width: none;
min-height: 44px;
min-width: 130px;
flex: 1;
}
`;
const MonthNav = styled.div`
display: flex;
align-items: center;
gap: ${theme.spacing.xs}px;
button {
min-width: 40px;
padding-left: 10px;
padding-right: 10px;
font-size: 1.25rem;
line-height: 1;
}
@media (max-width: ${theme.breakpoints.mobile}) {
flex: 1 1 100%;
order: -1;
button {
min-width: 48px;
min-height: 44px;
font-size: 1.4rem;
}
input {
flex: 1;
min-width: 0;
}
}
`;
const Main = styled.main`
width: 100%;
max-width: 1200px;
margin: 0 auto;
padding: ${theme.spacing.xl}px;
display: flex;
flex-direction: column;
gap: ${theme.spacing.xl}px;
flex: 1;
@media (max-width: ${theme.breakpoints.mobile}) {
padding: ${theme.spacing.lg}px;
gap: ${theme.spacing.lg}px;
}
`;
const SummaryGrid = styled.section`
display: grid;
grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
gap: ${theme.spacing.md}px;
@media (max-width: ${theme.breakpoints.mobileSmall}) {
grid-template-columns: repeat(2, 1fr);
> *:first-child {
grid-column: 1 / -1;
}
}
`;
const StatCard = styled.div<{ hero?: boolean }>`
background: ${p => (p.hero ? theme.colors.surfaceAlt : theme.colors.surface)};
border: 1px solid ${p => (p.hero ? theme.colors.borderStrong : theme.colors.border)};
border-radius: ${theme.radius.md}px;
padding: ${theme.spacing.lg}px;
display: flex;
flex-direction: column;
gap: ${theme.spacing.xs}px;
min-width: 0;
@media (max-width: ${theme.breakpoints.mobileSmall}) {
padding: ${theme.spacing.md}px;
}
`;
const StatLabel = styled.span`
font-size: ${theme.font.sizes.xs};
font-weight: 700;
text-transform: uppercase;
letter-spacing: 0.08em;
color: ${theme.colors.textMuted};
`;
const StatValue = styled.span<{ tone?: AmountTone }>`
font-size: ${theme.font.sizes.xl};
font-weight: 700;
font-variant-numeric: tabular-nums;
text-align: right;
color: ${p =>
p.tone === "income" ? theme.colors.income
: p.tone === "expense" ? theme.colors.expense
: theme.colors.text};
`;
const EmptyHint = styled.div`
background: ${theme.colors.surface};
border: 1px dashed ${theme.colors.borderStrong};
border-radius: ${theme.radius.md}px;
padding: ${theme.spacing.xl}px;
text-align: center;
color: ${theme.colors.textMuted};
`;
const Message = styled.div`
flex: 1;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
gap: ${theme.spacing.md}px;
padding: ${theme.spacing.xl}px;
text-align: center;
color: ${theme.colors.textMuted};
`;
const ErrorTitle = styled.h2`
color: ${theme.colors.expense};
margin: 0;
`;
const fmtMoney = (n: number) =>
Math.abs(n).toLocaleString("en-US", { minimumFractionDigits: 2, maximumFractionDigits: 2 });
function shiftMonth(month: string, delta: number): string {
const fallback = getMonth();
const match = /^(\d{4})-(\d{2})$/.exec(month || fallback);
if (!match) return fallback;
const d = new Date(Number(match[1]), Number(match[2]) - 1 + delta, 1);
return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, "0")}`;
}
export function Page(props: { storage: WebsiteStorage, logout: () => void }) {
const [month, setMonth] = useState("");
const [data, setData] = useState<Data<Date>[]>([]);
const [past, setPast] = useState<Data<Date>[][]>([]);
const [future, setFuture] = useState<Data<Date>[][]>([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState("");
const [suggestions, setAutoSuggestions] = useState<Suggestions>({});
const [suggestionsOpen, setSuggestionsOpen] = useState(false);
const setDate = async (month: string) => {
setLoading(true);
setPast([]);
setFuture([]);
try {
const data = await props.storage.load(month);
setMonth(month);
setData(data ?? []);
} catch (error) {
console.error(error);
setError((error as any).message)
setMonth(month);
setData([]);
}
setLoading(false);
}
const fetchAutoSuggestions = async () => {
const autoSuggestions = await props.storage.getAutoSuggestions();
setAutoSuggestions(autoSuggestions);
}
const setSuggestions = (next: Suggestions) => {
const migrated = migrateSuggestions(next);
setAutoSuggestions(migrated);
props.storage.setAutoSuggestions(migrated);
}
const modifySuggestions = async (key: DataKeys, value: string[]) => {
const clone = migrateSuggestions({ ...suggestions });
const items: Record<string, SuggestionEntry> = {};
value.forEach(entry => {
if (entry.trim()) {
const normalized = entry.trim();
const existing = clone[key]?.items[normalized];
items[normalized] = existing
? { ...existing, count: existing.count }
: { count: 1, lastUsed: Date.now() };
}
});
clone[key] = { items };
setSuggestions(clone);
}
const addSuggestions = async (values: {key: DataKeys, value: string}[]) => {
const clone = migrateSuggestions({ ...suggestions });
const now = Date.now();
for (const { key, value } of values) {
const actualValue = value.trim();
if (!actualValue) continue;
clone[key] = clone[key] ?? { items: {} };
const group = clone[key]!;
const found = Object.keys(group.items).find(e => e.toLowerCase() === actualValue.toLowerCase());
if (found) {
const prev = group.items[found];
const prevCount = prev.count + 1;
delete group.items[found];
group.items[actualValue] = { count: prevCount, lastUsed: now };
} else {
group.items[actualValue] = {
count: (group.items[actualValue]?.count ?? 0) + 1,
lastUsed: now
};
}
}
setSuggestions(clone);
}
useEffect(() => {
setDate(getMonth());
fetchAutoSuggestions();
}, []);
const commitData = (next: Data<Date>[]) => {
props.storage.save(next, month);
setPast(p => [...p, data]);
setFuture([]);
setData(next);
};
const undo = useCallback(() => {
if (past.length === 0) return;
const previous = past[past.length - 1];
setPast(p => p.slice(0, -1));
setFuture(f => [...f, data]);
props.storage.save(previous, month);
setData(previous);
}, [past, data, month, props.storage]);
const redo = useCallback(() => {
if (future.length === 0) return;
const next = future[future.length - 1];
setFuture(f => f.slice(0, -1));
setPast(p => [...p, data]);
props.storage.save(next, month);
setData(next);
}, [future, data, month, props.storage]);
useEffect(() => {
const onKey = (e: KeyboardEvent) => {
if (!(e.ctrlKey || e.metaKey)) return;
const target = e.target as HTMLElement | null;
const tag = target?.tagName;
if (tag === "INPUT" || tag === "TEXTAREA" || tag === "SELECT" || target?.isContentEditable) return;
const key = e.key.toLowerCase();
if (key === "z" && e.shiftKey) { e.preventDefault(); redo(); }
else if (key === "z") { e.preventDefault(); undo(); }
else if (key === "y") { e.preventDefault(); redo(); }
};
window.addEventListener("keydown", onKey);
return () => window.removeEventListener("keydown", onKey);
}, [undo, redo]);
const summary = useMemo(() => {
let income = 0;
let expense = 0;
for (const entry of data) {
if (entry.amount > 0) income += entry.amount;
else expense += entry.amount;
}
return { income, expense: Math.abs(expense), net: income + expense };
}, [data]);
if (error) {
return <Div>
<Message role="alert">
<ErrorTitle>Something went wrong</ErrorTitle>
<p>{error}</p>
<button onClick={() => setDate(month || getMonth())}>Try again</button>
</Message>
</Div>
}
if (loading) {
return <Div>
<Message role="status">Loading…</Message>
</Div>
}
return <Div>
<Header>
<Brand>
<Title>Flog</Title>
<MonthBadge>{month}</MonthBadge>
</Brand>
<Controls>
<MonthNav>
<button onClick={() => setDate(shiftMonth(month, -1))} aria-label="Previous month" title="Previous month">‹</button>
<MonthInput aria-label="Select month" value={month} onChange={(d: ChangeEvent<HTMLInputElement>) => setDate(d.target.value)} />
<button onClick={() => setDate(shiftMonth(month, 1))} aria-label="Next month" title="Next month">›</button>
</MonthNav>
<button onClick={undo} disabled={past.length === 0} aria-label="Undo" title="Undo (Ctrl+Z)">Undo</button>
<button onClick={redo} disabled={future.length === 0} aria-label="Redo" title="Redo (Ctrl+Y)">Redo</button>
<button onClick={() => setSuggestionsOpen(true)}>Suggestions</button>
<button onClick={() => props.logout()}>Logout</button>
</Controls>
</Header>
<Main>
<SummaryGrid>
<StatCard hero>
<StatLabel>Balance</StatLabel>
<StatValue tone={summary.net > 0 ? "income" : summary.net < 0 ? "expense" : "neutral"}>
{formatSigned(summary.net)}
</StatValue>
</StatCard>
<StatCard>
<StatLabel>Income</StatLabel>
<StatValue tone="income">+{fmtMoney(summary.income)}</StatValue>
</StatCard>
<StatCard>
<StatLabel>Expenses</StatLabel>
<StatValue tone="expense">-{fmtMoney(summary.expense)}</StatValue>
</StatCard>
</SummaryGrid>
{data.length === 0 && (
<EmptyHint>
No entries for this month yet. Add your first transaction below.
</EmptyHint>
)}
<Table
data={data}
month={month}
autosuggestions={suggestions}
updateAutoSuggestions={addSuggestions}
modifySuggestions={modifySuggestions}
onChange={commitData}/>
<CategoryGraphs data={data} />
</Main>
{suggestionsOpen && (
<SuggestionsManager
suggestions={suggestions}
onSave={setSuggestions}
onClose={() => setSuggestionsOpen(false)} />
)}
</Div>;
}