358 lines
18 KiB
JavaScript
358 lines
18 KiB
JavaScript
/* Finance UI: theme, nav drawer, inline edits, live numbers, charts. No framework needed. */
|
||
"use strict";
|
||
|
||
// ------------------------------------------------------------------ helpers
|
||
const $ = (sel, root = document) => root.querySelector(sel);
|
||
const $$ = (sel, root = document) => Array.from(root.querySelectorAll(sel));
|
||
const css = (name) => getComputedStyle(document.documentElement).getPropertyValue(name).trim();
|
||
const nf = (d) => new Intl.NumberFormat("nl-NL", { minimumFractionDigits: d, maximumFractionDigits: d });
|
||
const eur = (v, d = 0) => (v < 0 ? "-" : "") + "€ " + nf(d).format(Math.abs(v));
|
||
const eurCompact = (v) => {
|
||
const a = Math.abs(v);
|
||
if (a >= 1e6) return (v < 0 ? "-" : "") + "€ " + nf(1).format(a / 1e6) + "M";
|
||
if (a >= 1e4) return (v < 0 ? "-" : "") + "€ " + nf(a >= 1e5 ? 0 : 1).format(a / 1e3) + "k";
|
||
return eur(v);
|
||
};
|
||
const MONTHS = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
|
||
const monthLabel = (ym, withYear) => { const [y, m] = ym.split("-"); return MONTHS[+m - 1] + (withYear ? " " + y : ""); };
|
||
const dateLabel = (iso) => { const d = new Date(iso); return d.getDate() + " " + MONTHS[d.getMonth()] + " " + d.getFullYear(); };
|
||
|
||
// ------------------------------------------------------------------ theme
|
||
function currentTheme() { try { return localStorage.getItem("theme") || "auto"; } catch (e) { return "auto"; } }
|
||
function markTheme() { $$("[data-theme-set]").forEach((b) => b.classList.toggle("on", b.dataset.themeSet === currentTheme())); }
|
||
document.addEventListener("click", (e) => {
|
||
const b = e.target.closest("[data-theme-set]");
|
||
if (!b) return;
|
||
const t = b.dataset.themeSet;
|
||
try { t === "auto" ? localStorage.removeItem("theme") : localStorage.setItem("theme", t); } catch (err) {}
|
||
if (t === "auto") delete document.documentElement.dataset.theme; else document.documentElement.dataset.theme = t;
|
||
markTheme();
|
||
redrawCharts(); // pick up the new colours without a reload
|
||
});
|
||
|
||
// ------------------------------------------------------------------ mobile nav drawer
|
||
document.addEventListener("click", (e) => {
|
||
if (e.target.closest("[data-nav-toggle]")) document.body.classList.toggle("nav-open");
|
||
else if (e.target.closest("[data-nav-close]")) document.body.classList.remove("nav-open");
|
||
});
|
||
document.addEventListener("keydown", (e) => e.key === "Escape" && document.body.classList.remove("nav-open"));
|
||
|
||
// ------------------------------------------------------------------ inline edits & small UX
|
||
document.addEventListener("change", async (e) => {
|
||
const el = e.target;
|
||
if (el.matches("select[data-tx]")) {
|
||
const body = new FormData();
|
||
body.append("category_id", el.value);
|
||
const r = await fetch(`/transactions/${el.dataset.tx}/category`, { method: "POST", body });
|
||
el.style.boxShadow = `0 0 0 3px ${r.ok ? css("--good") : css("--bad")}55`;
|
||
const dot = el.closest("td")?.querySelector(".dot");
|
||
if (dot && el.selectedOptions[0]) dot.style.background = el.selectedOptions[0].dataset.color || "transparent";
|
||
setTimeout(() => (el.style.boxShadow = ""), 900);
|
||
setTimeout(pollLive, 300);
|
||
}
|
||
if (el.matches("input[data-notes]")) {
|
||
const body = new FormData();
|
||
body.append("notes", el.value);
|
||
await fetch(`/transactions/${el.dataset.notes}/notes`, { method: "POST", body });
|
||
}
|
||
if (el.matches("[data-autosubmit]")) el.form.submit();
|
||
});
|
||
document.addEventListener("submit", (e) => {
|
||
const msg = e.target.dataset.confirm;
|
||
if (msg && !confirm(msg)) e.preventDefault();
|
||
});
|
||
|
||
// ------------------------------------------------------------------ live numbers
|
||
// Elements with data-live="key" refresh from /api/live. data-fmt: eur | eur0 | eurs | eur0s | pct ; data-color = good/bad by sign.
|
||
const LIVE_INTERVAL = 30000;
|
||
function fmt(v, kind) {
|
||
if (v === null || v === undefined || Number.isNaN(v)) return "–";
|
||
if (kind === "pct") return (v < 0 ? "-" : "+") + nf(1).format(Math.abs(v)) + "%";
|
||
const sign = v < 0 ? "-" : kind.endsWith("s") && v > 0 ? "+" : "";
|
||
return `${sign}€ ${nf(kind.startsWith("eur0") ? 0 : 2).format(Math.abs(v))}`;
|
||
}
|
||
function animate(el, from, to, kind) {
|
||
const t0 = performance.now(), dur = 700;
|
||
const step = (now) => {
|
||
const p = Math.min(1, (now - t0) / dur), k = 1 - Math.pow(1 - p, 3);
|
||
el.textContent = fmt(from + (to - from) * k, kind);
|
||
if (p < 1) requestAnimationFrame(step);
|
||
};
|
||
requestAnimationFrame(step);
|
||
}
|
||
function applyLive(values) {
|
||
$$("[data-live]").forEach((el) => {
|
||
const key = el.dataset.live;
|
||
if (!(key in values)) return;
|
||
const to = values[key], kind = el.dataset.fmt || "eur";
|
||
const from = el.dataset.v !== undefined && el.dataset.v !== "" ? parseFloat(el.dataset.v) : null;
|
||
el.dataset.v = to ?? "";
|
||
if (el.hasAttribute("data-color") && to !== null) { el.classList.toggle("good", to >= 0); el.classList.toggle("bad", to < 0); }
|
||
if (from === null) { el.textContent = fmt(to, kind); return; }
|
||
if (to === null || Math.abs(to - from) < 0.005) return;
|
||
animate(el, from, to, kind);
|
||
el.classList.remove("flash-up", "flash-down");
|
||
void el.offsetWidth;
|
||
el.classList.add(to > from ? "flash-up" : "flash-down");
|
||
});
|
||
}
|
||
let liveVersion = null;
|
||
async function pollLive() {
|
||
if (!$("[data-live]") || document.hidden) return;
|
||
const qs = new URLSearchParams(location.search), params = new URLSearchParams();
|
||
["account", "month"].forEach((k) => qs.get(k) && params.set(k, qs.get(k)));
|
||
try {
|
||
const r = await fetch("/api/live?" + params, { headers: { Accept: "application/json" } });
|
||
if (!r.ok) return;
|
||
const data = await r.json();
|
||
applyLive(data.values);
|
||
const changed = liveVersion && data.version.split(":")[0] !== liveVersion.split(":")[0];
|
||
$$(".live-status").forEach((s) => (s.innerHTML = changed ? 'New data · <a href="">reload</a>' : "Live · " + data.at));
|
||
liveVersion = data.version;
|
||
} catch (e) { /* offline / session expired: keep last numbers */ }
|
||
}
|
||
|
||
// Refresh prices in place
|
||
document.addEventListener("submit", async (e) => {
|
||
const form = e.target;
|
||
if (!form.matches("[data-ajax-refresh]")) return;
|
||
e.preventDefault();
|
||
const btn = $("button", form), label = btn.innerHTML;
|
||
btn.disabled = true;
|
||
btn.lastChild.textContent = " Refreshing…";
|
||
try {
|
||
const r = await (await fetch("/api/prices/refresh", { method: "POST" })).json();
|
||
await pollLive();
|
||
btn.lastChild.textContent = r.ok ? " Updated" : " Some failed";
|
||
if (!r.ok) btn.title = r.errors.join("\n");
|
||
} catch (err) { btn.lastChild.textContent = " Failed"; }
|
||
setTimeout(() => { btn.disabled = false; btn.innerHTML = label; }, 2200);
|
||
});
|
||
|
||
// ------------------------------------------------------------------ charts
|
||
const PALETTE = ["#6366f1", "#22c55e", "#f59e0b", "#ec4899", "#06b6d4", "#8b5cf6", "#ef4444", "#84cc16", "#14b8a6", "#f97316"];
|
||
const charts = [];
|
||
|
||
const solid = (ds, i) => {
|
||
const c = Array.isArray(ds.backgroundColor) ? ds.backgroundColor[i] : ds.borderColor || ds.backgroundColor;
|
||
return typeof c === "string" ? c : ds.borderColor;
|
||
};
|
||
function baseOptions() {
|
||
return {
|
||
responsive: true, maintainAspectRatio: false, animation: { duration: 500 },
|
||
interaction: { mode: "index", intersect: false },
|
||
plugins: {
|
||
legend: { display: false },
|
||
tooltip: {
|
||
backgroundColor: css("--panel"), titleColor: css("--text"), bodyColor: css("--text"), footerColor: css("--muted"),
|
||
borderColor: css("--line"), borderWidth: 1, padding: 12, cornerRadius: 10, boxPadding: 5, usePointStyle: true,
|
||
titleFont: { weight: "600" }, footerFont: { weight: "500" },
|
||
callbacks: {},
|
||
},
|
||
},
|
||
scales: {
|
||
x: { grid: { display: false }, border: { display: false }, ticks: { color: css("--muted"), maxRotation: 0, autoSkipPadding: 14 } },
|
||
y: { grid: { color: css("--line"), drawTicks: false }, border: { display: false },
|
||
ticks: { color: css("--muted"), padding: 8, maxTicksLimit: 6, callback: (v) => eurCompact(v) } },
|
||
},
|
||
};
|
||
}
|
||
|
||
// Text in the middle of a doughnut; follows the hovered slice.
|
||
const centerText = {
|
||
id: "centerText",
|
||
afterDraw(chart, _args, opts) {
|
||
if (!opts || !opts.label) return;
|
||
const { ctx, chartArea: a } = chart;
|
||
const active = chart.getActiveElements()[0];
|
||
const ds = chart.data.datasets[0];
|
||
const total = ds.data.reduce((s, v, i) => s + (chart.getDataVisibility(i) ? v : 0), 0);
|
||
let top = opts.label, big = eur(total), small = "";
|
||
if (active) {
|
||
const v = ds.data[active.index];
|
||
top = chart.data.labels[active.index];
|
||
big = eur(v);
|
||
small = total ? nf(1).format((v / total) * 100) + "%" : "";
|
||
}
|
||
const x = (a.left + a.right) / 2, y = (a.top + a.bottom) / 2;
|
||
ctx.save();
|
||
ctx.textAlign = "center"; ctx.textBaseline = "middle";
|
||
ctx.fillStyle = css("--muted"); ctx.font = `500 12px ${getComputedStyle(document.body).fontFamily}`;
|
||
ctx.fillText(top.length > 18 ? top.slice(0, 17) + "…" : top, x, y - 18);
|
||
ctx.fillStyle = css("--text"); ctx.font = `700 19px ${getComputedStyle(document.body).fontFamily}`;
|
||
ctx.fillText(big, x, y + 3);
|
||
if (small) { ctx.fillStyle = css("--muted"); ctx.font = `600 12px ${getComputedStyle(document.body).fontFamily}`; ctx.fillText(small, x, y + 23); }
|
||
ctx.restore();
|
||
},
|
||
};
|
||
|
||
// Vertical hover line for line charts
|
||
const crosshair = {
|
||
id: "crosshair",
|
||
afterDatasetsDraw(chart) {
|
||
const act = chart.tooltip && chart.tooltip.getActiveElements();
|
||
if (!act || !act.length || chart.config.type !== "line") return;
|
||
const x = act[0].element.x, { top, bottom } = chart.chartArea, ctx = chart.ctx;
|
||
ctx.save(); ctx.strokeStyle = css("--muted"); ctx.globalAlpha = 0.35; ctx.setLineDash([4, 4]);
|
||
ctx.beginPath(); ctx.moveTo(x, top); ctx.lineTo(x, bottom); ctx.stroke(); ctx.restore();
|
||
},
|
||
};
|
||
|
||
function gradient(chart, color) {
|
||
const { ctx, chartArea } = chart;
|
||
if (!chartArea) return color + "33";
|
||
const g = ctx.createLinearGradient(0, chartArea.top, 0, chartArea.bottom);
|
||
g.addColorStop(0, color + "55"); g.addColorStop(1, color + "00");
|
||
return g;
|
||
}
|
||
|
||
const builders = {
|
||
// Income/expense bars + net line; click a month to drill in.
|
||
months(canvas, d) {
|
||
const good = css("--good"), bad = css("--bad"), accent = css("--accent");
|
||
const net = d.income.map((v, i) => v - d.expense[i]);
|
||
const o = baseOptions();
|
||
o.scales.x.ticks.callback = function (v) { const l = this.getLabelForValue(v); return monthLabel(l, l.endsWith("-01")); };
|
||
o.plugins.tooltip.callbacks = {
|
||
labelColor: (c) => ({ borderColor: solid(c.dataset, c.dataIndex), backgroundColor: solid(c.dataset, c.dataIndex), borderRadius: 3 }),
|
||
title: (items) => monthLabel(items[0].label, true),
|
||
label: (c) => ` ${c.dataset.label}: ${eur(c.parsed.y)}`,
|
||
footer: (items) => { const i = items[0].dataIndex, r = d.income[i] ? (net[i] / d.income[i]) * 100 : null;
|
||
return r === null ? "" : `Savings rate ${nf(0).format(r)}%`; },
|
||
};
|
||
o.plugins.legend = { display: true, position: "bottom", labels: { usePointStyle: true, pointStyle: "rectRounded", boxWidth: 10, boxHeight: 10, color: css("--muted"), padding: 16 } };
|
||
o.onClick = (_e, els) => { if (els.length && canvas.dataset.link) location.href = canvas.dataset.link.replace("{label}", d.labels[els[0].index]); };
|
||
o.onHover = (e, els) => (e.native.target.style.cursor = els.length ? "pointer" : "default");
|
||
const dim = (c) => d.labels.map((l) => (l === d.current ? c : c + "99"));
|
||
return {
|
||
type: "bar",
|
||
data: { labels: d.labels, datasets: [
|
||
{ label: "Income", data: d.income, backgroundColor: dim(good), borderRadius: 6, maxBarThickness: 22, order: 2 },
|
||
{ label: "Expenses", data: d.expense, backgroundColor: dim(bad), borderRadius: 6, maxBarThickness: 22, order: 2 },
|
||
{ label: "Net", data: net, type: "line", borderColor: accent, backgroundColor: accent, borderWidth: 2, tension: 0.35,
|
||
pointRadius: 3, pointHoverRadius: 5, pointBackgroundColor: css("--panel"), order: 1 },
|
||
] },
|
||
options: o,
|
||
};
|
||
},
|
||
|
||
// Doughnut with centre total, custom clickable legend, click-through links.
|
||
donut(canvas, d) {
|
||
const o = baseOptions();
|
||
delete o.scales; o.interaction = { mode: "nearest", intersect: true };
|
||
o.cutout = "72%"; o.layout = { padding: 6 };
|
||
o.plugins.centerText = { label: canvas.dataset.center === "spent" ? "Total spent" : "Total" };
|
||
o.plugins.tooltip.enabled = false; // the centre shows the hovered slice
|
||
o.onClick = (_e, els) => { if (els.length && d.links && d.links[els[0].index]) location.href = d.links[els[0].index]; };
|
||
o.onHover = (e, els) => (e.native.target.style.cursor = els.length && d.links ? "pointer" : "default");
|
||
const colors = d.colors || d.labels.map((_, i) => PALETTE[i % PALETTE.length]);
|
||
return {
|
||
type: "doughnut",
|
||
data: { labels: d.labels, datasets: [{ data: d.data, backgroundColor: colors, borderColor: css("--panel"), borderWidth: 3, hoverOffset: 8, borderRadius: 4 }] },
|
||
options: o, plugins: [centerText],
|
||
};
|
||
},
|
||
|
||
// Value vs paid over time; gradient fill, range filter, P/L in tooltip.
|
||
history(canvas, d) {
|
||
const accent = css("--accent"), muted = css("--muted");
|
||
const o = baseOptions();
|
||
o.scales.x.ticks.maxTicksLimit = 7;
|
||
o.scales.x.ticks.callback = function (v) { const l = this.getLabelForValue(v); const dt = new Date(l); return dt.getDate() + " " + MONTHS[dt.getMonth()]; };
|
||
o.plugins.tooltip.callbacks = {
|
||
labelColor: (c) => ({ borderColor: c.dataset.borderColor, backgroundColor: c.dataset.borderColor, borderRadius: 3 }),
|
||
title: (items) => dateLabel(items[0].label),
|
||
label: (c) => ` ${c.dataset.label}: ${eur(c.parsed.y)}`,
|
||
footer: (items) => {
|
||
const v = items.find((i) => i.datasetIndex === 0), c = items.find((i) => i.datasetIndex === 1);
|
||
if (!v || !c) return "";
|
||
const pl = v.parsed.y - c.parsed.y, pct = c.parsed.y ? (pl / c.parsed.y) * 100 : 0;
|
||
return `P/L ${pl >= 0 ? "+" : ""}${eur(pl)} (${pct >= 0 ? "+" : ""}${nf(1).format(pct)}%)`;
|
||
},
|
||
};
|
||
o.plugins.legend = { display: true, position: "bottom", labels: { usePointStyle: true, pointStyle: "line", color: muted, padding: 16 } };
|
||
canvas._full = d;
|
||
return {
|
||
type: "line",
|
||
data: { labels: d.labels, datasets: [
|
||
{ label: "Value", data: d.value, borderColor: accent, borderWidth: 2.5, tension: 0.3, pointRadius: 0, pointHoverRadius: 5,
|
||
pointHoverBackgroundColor: accent, pointHoverBorderColor: css("--panel"), pointHoverBorderWidth: 2,
|
||
fill: true, backgroundColor: (ctx) => gradient(ctx.chart, accent) },
|
||
{ label: "Paid", data: d.cost, borderColor: muted, borderWidth: 1.5, borderDash: [5, 5], pointRadius: 0, pointHoverRadius: 0, stepped: true, fill: false },
|
||
] },
|
||
options: o, plugins: [crosshair],
|
||
};
|
||
},
|
||
};
|
||
|
||
function buildLegend(chart, id) {
|
||
const box = document.getElementById(id);
|
||
if (!box) return;
|
||
box.innerHTML = "";
|
||
const ds = chart.data.datasets[0];
|
||
const total = ds.data.reduce((a, b) => a + b, 0);
|
||
chart.data.labels.forEach((label, i) => {
|
||
const b = document.createElement("button");
|
||
b.type = "button";
|
||
b.innerHTML = `<span class="dot" style="background:${ds.backgroundColor[i]}"></span><span>${label}</span><span class="v">${eur(ds.data[i])} · ${nf(0).format((ds.data[i] / total) * 100)}%</span>`;
|
||
b.title = "Click to hide/show";
|
||
b.onclick = () => { chart.toggleDataVisibility(i); b.classList.toggle("off", !chart.getDataVisibility(i)); chart.update(); };
|
||
b.onmouseenter = () => { chart.setActiveElements([{ datasetIndex: 0, index: i }]); chart.update("none"); };
|
||
b.onmouseleave = () => { chart.setActiveElements([]); chart.update("none"); };
|
||
box.appendChild(b);
|
||
});
|
||
}
|
||
|
||
function applyRange(canvas, days) {
|
||
const chart = Chart.getChart(canvas), d = canvas._full;
|
||
if (!chart || !d) return;
|
||
let from = 0;
|
||
if (days > 0 && d.labels.length) {
|
||
const cutoff = new Date(d.labels[d.labels.length - 1]);
|
||
cutoff.setDate(cutoff.getDate() - days);
|
||
from = d.labels.findIndex((l) => new Date(l) >= cutoff);
|
||
if (from < 0) from = 0;
|
||
}
|
||
chart.data.labels = d.labels.slice(from);
|
||
chart.data.datasets[0].data = d.value.slice(from);
|
||
chart.data.datasets[1].data = d.cost.slice(from);
|
||
chart.update();
|
||
}
|
||
document.addEventListener("click", (e) => {
|
||
const b = e.target.closest("[data-range-for] button");
|
||
if (!b) return;
|
||
const seg = b.parentElement;
|
||
$$("button", seg).forEach((x) => x.classList.toggle("on", x === b));
|
||
const canvas = document.getElementById(seg.dataset.rangeFor);
|
||
if (canvas) { canvas._days = +b.dataset.days; applyRange(canvas, canvas._days); }
|
||
});
|
||
|
||
function drawCharts() {
|
||
if (!window.Chart) return;
|
||
Chart.defaults.font.family = getComputedStyle(document.body).fontFamily;
|
||
Chart.defaults.color = css("--muted");
|
||
$$("canvas[data-chart]").forEach((canvas) => {
|
||
const build = builders[canvas.dataset.chart];
|
||
if (!build) return;
|
||
const chart = new Chart(canvas, build(canvas, JSON.parse(canvas.dataset.json)));
|
||
charts.push(chart);
|
||
if (canvas.dataset.legend) buildLegend(chart, canvas.dataset.legend);
|
||
if (canvas.dataset.chart === "history") {
|
||
const seg = $(`[data-range-for="${canvas.id}"] .on`);
|
||
applyRange(canvas, canvas._days ?? (seg ? +seg.dataset.days : 0));
|
||
}
|
||
});
|
||
}
|
||
function redrawCharts() { while (charts.length) charts.pop().destroy(); drawCharts(); }
|
||
|
||
// ------------------------------------------------------------------ boot
|
||
window.addEventListener("DOMContentLoaded", () => {
|
||
markTheme();
|
||
drawCharts();
|
||
pollLive();
|
||
setInterval(pollLive, LIVE_INTERVAL);
|
||
document.addEventListener("visibilitychange", () => !document.hidden && pollLive());
|
||
// follow OS theme changes live when on "auto"
|
||
window.matchMedia("(prefers-color-scheme: dark)").addEventListener("change", () => currentTheme() === "auto" && redrawCharts());
|
||
});
|