Skip to content

armgit / sure

Public Imported from GitHub
0

The personal finance app for everyone (by everyone)

Ruby

Fit goal projection chart y-axis to recent saved values (#5421)

joaocbatista177b9a021bbf
diff --git a/app/javascript/controllers/goal_projection_chart_controller.js b/app/javascript/controllers/goal_projection_chart_controller.js
index b32ff9e841..83f193d425 100644
--- a/app/javascript/controllers/goal_projection_chart_controller.js
+++ b/app/javascript/controllers/goal_projection_chart_controller.js
@@ -27,6 +27,19 @@ import {
// shows in full.
const SAVED_HEADROOM_FACTOR = 2;
+// Axis floor and tick step for the y-axis. The floor sits 10% of the visible
+// range below the recent minimum, rounded down to a multiple of the tick step,
+// so the bottom edge is always a labeled tick and the labels stay evenly
+// spaced. Returns floor 0 when there is no useful floor (a new goal, or a
+// floor within one step of zero); the axis then stays anchored at zero as before.
+function axisFloor(recentMin, yMax) {
+ if (!(recentMin > 0) || !(yMax > recentMin)) return { floor: 0, step: 0 };
+ const padded = recentMin - 0.1 * (yMax - recentMin);
+ const step = d3.tickStep(padded, yMax, 3);
+ const floor = Math.floor(padded / step) * step;
+ return floor > 0 ? { floor, step } : { floor: 0, step: 0 };
+}
+
export default class extends Controller {
static values = {
data: Object,
@@ -143,9 +156,12 @@ export default class extends Controller {
const savedSeries = [];
// Only seed a (start, 0) point when start_date predates the first
// contribution. Otherwise the line draws a vertical jump up at the
- // chart's left edge.
+ // chart's left edge. Kept in a variable so it can be dropped below when
+ // the axis does not start at zero.
+ let seedPoint = null;
if (!firstContribDate || firstContribDate.getTime() > start.getTime()) {
- savedSeries.push({ date: start, value: 0 });
+ seedPoint = { date: start, value: 0 };
+ savedSeries.push(seedPoint);
}
savedSeries.push(...rawSavedSeries);
// Always close the saved line at (today, currentAmount) — the projection
@@ -195,8 +211,29 @@ export default class extends Controller {
const savedMax = d3.max(savedSeries, (d) => d.value) || 0;
const yMax = Math.min(Math.max(goalBand, savedMax * 1.05), goalBand * SAVED_HEADROOM_FACTOR);
+ // Fit the floor to the last 90 days of the saved line (and today's balance),
+ // so recent progress is visible instead of flattened against zero. The
+ // zero seed point is dropped when the axis no longer starts at zero; the
+ // area and line are clipped to the plot either way.
+ // Subtract calendar days, not 90 x 24h, so DST shifts can't move the
+ // boundary off local midnight and drop a value dated on that day.
+ const windowStart = new Date(today);
+ windowStart.setDate(windowStart.getDate() - 90);
+ // The target counts toward the lowest value, so a floor never pushes the
+ // target line off the plot. Narrow layouts hide the y-axis, so they keep a
+ // zero floor instead of showing a baseline with no label.
+ const recentMin = Math.min(
+ currentAmount,
+ ...(targetAmount > 0 ? [targetAmount] : []),
+ ...rawSavedSeries.filter((p) => p.date >= windowStart).map((p) => p.value)
+ );
+ const { floor: yMin, step: yStep } = yAxisVisible
+ ? axisFloor(recentMin, yMax)
+ : { floor: 0, step: 0 };
+ if (yMin > 0 && seedPoint) savedSeries.splice(savedSeries.indexOf(seedPoint), 1);
+
const x = d3.scaleTime().domain([start, endDate]).range([margin.left, margin.left + innerWidth]);
- const y = d3.scaleLinear().domain([0, yMax]).range([margin.top + innerHeight, margin.top]);
+ const y = d3.scaleLinear().domain([yMin, yMax]).range([margin.top + innerHeight, margin.top]);
const svg = d3
.select(root)
@@ -241,7 +278,13 @@ export default class extends Controller {
const COLLISION_PX = 18;
const targetY = targetAmount > 0 ? y(targetAmount) : null;
- const yTicks = yAxisVisible ? y.ticks(3) : [];
+ // With a floor, label from the floor up in even steps so the bottom edge
+ // carries a label; otherwise keep d3's default ticks.
+ const yTicks = yAxisVisible
+ ? (yMin > 0
+ ? d3.range(yMin, yMax + yStep / 2, yStep).filter((v) => v <= yMax)
+ : y.ticks(3))
+ : [];
const targetCollidesWithTick =
targetY !== null && yTicks.some((tv) => Math.abs(y(tv) - targetY) < COLLISION_PX);
@@ -265,7 +308,7 @@ export default class extends Controller {
.attr("text-anchor", "end")
.attr("font-size", 12)
.attr("fill", textSecondary)
- .text(this._fmtMoneyShort(tickValue, data.currency));
+ .text(this._fmtMoneyShort(tickValue, data.currency, yStep));
});
}
@@ -640,7 +683,10 @@ export default class extends Controller {
}
}
- _fmtMoneyShort(amount, _currency) {
+ // `step` is the tick spacing when known. Millions need two decimals when the
+ // ticks are closer than 100K, or neighbouring labels round to the same value
+ // (1.02M and 1.04M would both read "1M").
+ _fmtMoneyShort(amount, _currency, step = null) {
// The server ships `currency_symbol` via projection_payload (resolved
// through Money.new(0, code).currency.symbol so EUR/GBP/JPY/etc. render
// with the family-locale-correct glyph). Fall back to "$" if a stale
@@ -648,10 +694,12 @@ export default class extends Controller {
const symbol = this.dataValue?.currency_symbol || "$";
const abs = Math.abs(amount);
if (abs >= 1_000_000) {
- return `${symbol}${(amount / 1_000_000).toFixed(1).replace(/\.0$/, "")}M`;
+ const decimals = step && step < 100_000 ? 2 : 1;
+ return `${symbol}${Number((amount / 1_000_000).toFixed(decimals))}M`;
}
if (abs >= 1_000) {
- return `${symbol}${(amount / 1_000).toFixed(1).replace(/\.0$/, "")}K`;
+ const decimals = step && step < 1_000 ? 2 : 1;
+ return `${symbol}${Number((amount / 1_000).toFixed(decimals))}K`;
}
return `${symbol}${Math.round(amount).toLocaleString()}`;
}