Skip to content

armgit / sure

Public Imported from GitHub
0

The personal finance app for everyone (by everyone)

Ruby

fix(charts): restyle hover tooltips with soft shadow + larger radius (#2029)

Guillem Arias Fauste6d27285c0357
diff --git a/app/assets/tailwind/sure-design-system/components.css b/app/assets/tailwind/sure-design-system/components.css
index f529486fc6..7e96c36459 100644
--- a/app/assets/tailwind/sure-design-system/components.css
+++ b/app/assets/tailwind/sure-design-system/components.css
@@ -219,4 +219,32 @@
background-size: 32px 100%, 32px 100%, 12px 100%, 12px 100%;
background-attachment: local, local, scroll, scroll;
}
+
+ /*
+ Chart hover tooltip surface (see utils/chart_tooltip.js for the JS-side
+ contract). Matches the design reference exactly: hairline border ring
+ composed with a soft 8/24 drop shadow (Tailwind shadow utilities don't
+ compose, hence the component class), 10px radius, 10x12 padding. Dark
+ mode swaps the ring to alpha-white; the drop shadow is near-invisible
+ there, which is fine — the ring carries the edge.
+
+ No position transition here on purpose: cursor-following tooltips
+ (sankey, time-series) update left/top every mousemove and a transition
+ makes them trail the pointer. Snap-positioned tooltips (goal projection,
+ which jumps between dates) opt into the 80ms glide via inline style.
+ */
+ .chart-tooltip {
+ background: var(--color-container);
+ border-radius: 10px;
+ padding: 10px 12px;
+ box-shadow:
+ 0 0 0 1px var(--color-alpha-black-50),
+ 0 8px 24px rgba(11, 11, 11, 0.12);
+
+ @variant theme-dark {
+ box-shadow:
+ 0 0 0 1px var(--color-alpha-white-50),
+ 0 8px 24px rgba(11, 11, 11, 0.12);
+ }
+ }
}
diff --git a/app/javascript/controllers/goal_projection_chart_controller.js b/app/javascript/controllers/goal_projection_chart_controller.js
index cefddedeb5..43e3c5481e 100644
--- a/app/javascript/controllers/goal_projection_chart_controller.js
+++ b/app/javascript/controllers/goal_projection_chart_controller.js
@@ -1,5 +1,10 @@
import { Controller } from "@hotwired/stimulus";
import * as d3 from "d3";
+import {
+ createChartTooltip,
+ CHART_TOOLTIP_CONTEXT_CLASSES,
+ CHART_TOOLTIP_VALUE_CLASSES,
+} from "utils/chart_tooltip";
// Projection chart for a goal. Renders:
// - Saved area + line from goal creation → today (solid)
@@ -18,6 +23,7 @@ export default class extends Controller {
todayLabel: { type: String, default: "Today" },
projectedTemplate: { type: String, default: "Projected: {amount}" },
savedTemplate: { type: String, default: "Saved: {amount}" },
+ targetRelationTemplate: { type: String, default: "{percent}% of {target} target" },
};
connect() {
@@ -439,10 +445,38 @@ export default class extends Controller {
// clobber a stylesheet `position: fixed/sticky/absolute` with our
// own `relative`. Read the computed style instead.
if (getComputedStyle(root).position === "static") root.style.position = "relative";
- const tooltip = document.createElement("div");
- tooltip.className = "bg-container text-primary text-sm font-sans absolute p-2 border border-secondary rounded-lg pointer-events-none z-50 privacy-sensitive";
- tooltip.style.display = "none";
- root.appendChild(tooltip);
+ // Shared visual contract (utils/chart_tooltip) — this used to be a
+ // hand-copied class string that drifted from the other charts the moment
+ // the contract changed.
+ const tooltip = createChartTooltip(root);
+ // This tooltip snaps between discrete dates (not raw cursor positions),
+ // so the glide reads as easing, not lag. Cursor-following tooltips must
+ // not do this — see the .chart-tooltip comment in components.css.
+ tooltip.style.transition = "left 80ms ease-out, top 80ms ease-out";
+ const tooltipDate = document.createElement("div");
+ tooltipDate.className = CHART_TOOLTIP_CONTEXT_CLASSES;
+ const tooltipValue = document.createElement("div");
+ tooltipValue.className = CHART_TOOLTIP_VALUE_CLASSES;
+ // Relation line: where this value sits against the goal target. Tertiary
+ // so the hierarchy stays date < value > relation; hidden when the goal
+ // has no positive target to compare against.
+ const tooltipRelation = document.createElement("div");
+ tooltipRelation.className = "text-xs text-subdued mt-0.5";
+ tooltip.replaceChildren(tooltipDate, tooltipValue, tooltipRelation);
+
+ const setRelation = (amount) => {
+ // `targetAmount` is _draw()'s outer const (data.target_amount) — no
+ // local copy, which previously shadowed the `target` date const.
+ if (targetAmount <= 0 || !data.target_amount_short_label) {
+ tooltipRelation.style.display = "none";
+ return;
+ }
+ const percent = Math.round((amount / targetAmount) * 100);
+ tooltipRelation.textContent = this.targetRelationTemplateValue
+ .replace("{percent}", percent)
+ .replace("{target}", data.target_amount_short_label);
+ tooltipRelation.style.display = "";
+ };
const overlay = svg
.append("rect")
@@ -485,7 +519,7 @@ export default class extends Controller {
const hoverX = x(hoverDate);
crosshair.attr("x1", hoverX).attr("x2", hoverX).style("display", null);
- const lines = [dateFmt(hoverDate)];
+ tooltipDate.textContent = dateFmt(hoverDate);
if (future) {
// Projection segment: interpolate along the dashed line; saved dot
@@ -494,7 +528,8 @@ export default class extends Controller {
const projValue = currentAmount + tFrac * (projectionEnd - currentAmount);
hoverProjDot.attr("cx", hoverX).attr("cy", y(projValue)).style("display", null);
hoverSavedDot.style("display", "none");
- lines.push(this.projectedTemplateValue.replace("{amount}", this._fmtMoney(projValue, data.currency)));
+ tooltipValue.textContent = this.projectedTemplateValue.replace("{amount}", this._fmtMoney(projValue, data.currency));
+ setRelation(projValue);
} else {
// Saved segment: hoverDate is already snapped to nearest savedSeries
// entry above, so reuse that entry directly instead of running
@@ -502,11 +537,10 @@ export default class extends Controller {
const savedPoint = savedSeries.find((p) => p.date.getTime() === hoverDate.getTime()) || savedSeries[savedSeries.length - 1];
hoverSavedDot.attr("cx", x(savedPoint.date)).attr("cy", y(savedPoint.value)).style("display", null);
hoverProjDot.style("display", "none");
- lines.push(this.savedTemplateValue.replace("{amount}", this._fmtMoney(savedPoint.value, data.currency)));
+ tooltipValue.textContent = this.savedTemplateValue.replace("{amount}", this._fmtMoney(savedPoint.value, data.currency));
+ setRelation(savedPoint.value);
}
- tooltip.textContent = lines.join("\n");
- tooltip.style.whiteSpace = "pre";
tooltip.style.display = "block";
const tipRect = tooltip.getBoundingClientRect();
const left = Math.min(width - tipRect.width - 4, Math.max(4, xPos + 12));
diff --git a/app/javascript/controllers/sankey_chart_controller.js b/app/javascript/controllers/sankey_chart_controller.js
index b7d12c0364..eba61846b1 100644
--- a/app/javascript/controllers/sankey_chart_controller.js
+++ b/app/javascript/controllers/sankey_chart_controller.js
@@ -445,7 +445,16 @@ export default class extends Controller {
linkPaths
.on("mouseenter", (event, d) => {
applyHover([d]);
- this.#showTooltip(event, d.value, d.percentage);
+ // A link is a flow between two named nodes — without the names the
+ // value floats context-free (the old tooltip showed only "$X (Y%)").
+ this.#showTooltip(
+ event,
+ d.value,
+ d.percentage,
+ this.#tooltipContext(
+ `${this.#esc(d.source.name)} → ${this.#esc(d.target.name)}`,
+ ),
+ );
})
.on("mousemove", (event) => this.#updateTooltipPosition(event))
.on("mouseleave", () => {
@@ -466,7 +475,12 @@ export default class extends Controller {
(l) => l.source === d || l.target === d,
);
applyHover(connectedLinks);
- this.#showTooltip(event, d.value, d.percentage, d.name);
+ this.#showTooltip(
+ event,
+ d.value,
+ d.percentage,
+ this.#tooltipContext(this.#esc(d.name)),
+ );
})
.on("mousemove", (event) => this.#updateTooltipPosition(event))
.on("click", (event, d) => {
@@ -490,7 +504,12 @@ export default class extends Controller {
(l) => l.source === d || l.target === d,
);
applyHover(connectedLinks);
- this.#showTooltip(event, d.value, d.percentage, d.name);
+ this.#showTooltip(
+ event,
+ d.value,
+ d.percentage,
+ this.#tooltipContext(this.#esc(d.name)),
+ );
})
.on("mousemove", (event) => this.#updateTooltipPosition(event))
.on("click", (event, d) => {
@@ -517,12 +536,32 @@ export default class extends Controller {
.style("pointer-events", "none");
}
- #showTooltip(event, value, percentage, title = null) {
+ // Node names are user-named categories; escape anything interpolated into
+ // .html() (the previous code injected them raw).
+ #esc(s) {
+ return String(s).replace(
+ /[&<>"']/g,
+ (c) =>
+ ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" })[c],
+ );
+ }
+
+ // Context line shared by node and link tooltips: the (escaped) name(s) of
+ // what's hovered. No color swatch — the hover highlight on the diagram
+ // itself already says which ribbon the card belongs to.
+ #tooltipContext(label) {
+ // max-w-64 gives truncate a constraint to fire against — an absolute
+ // tooltip otherwise grows to fit and never ellipsizes deep flows.
+ return `<div class="max-w-64 text-xs text-secondary mb-1 truncate">${label}</div>`;
+ }
+
+ #showTooltip(event, value, percentage, contextHtml = null) {
if (!this.tooltip) this.#createTooltip();
- const content = title
- ? `${title}<br/>${this.#formatCurrency(value)} (${percentage || 0}%)`
- : `${this.#formatCurrency(value)} (${percentage || 0}%)`;
+ const valueLine = `<span class="font-medium tabular-nums">${this.#formatCurrency(value)}</span> <span class="text-secondary">(${percentage || 0}%)</span>`;
+ const content = contextHtml
+ ? `${contextHtml}<div>${valueLine}</div>`
+ : valueLine;
const isInDialog = !!this.element.closest("dialog");
const x = isInDialog ? event.clientX : event.pageX;
diff --git a/app/javascript/controllers/time_series_chart_controller.js b/app/javascript/controllers/time_series_chart_controller.js
index 1b8d672545..3c358dd964 100644
--- a/app/javascript/controllers/time_series_chart_controller.js
+++ b/app/javascript/controllers/time_series_chart_controller.js
@@ -396,11 +396,11 @@ export default class extends Controller {
_tooltipTemplate(datum) {
return `
- <div style="margin-bottom: 4px; color: var(--color-gray-500);">
+ <div class="text-xs text-secondary mb-1">
${datum.date_formatted}
</div>
<div class="flex items-center gap-4">
- <div class="flex items-center gap-2 text-primary">
+ <div class="flex items-center gap-2 text-primary font-medium tabular-nums">
<div class="flex items-center justify-center h-4 w-4">
${this._getTrendIcon(datum)}
</div>
@@ -411,7 +411,7 @@ export default class extends Controller {
datum.trend.value === 0
? `<span class="w-20"></span>`
: `
- <span style="color: ${datum.trend.color};">
+ <span class="tabular-nums" style="color: ${datum.trend.color};">
${this._extractFormattedValue(datum.trend.value)} (${datum.trend.percent_formatted})
</span>
`
diff --git a/app/javascript/utils/chart_tooltip.js b/app/javascript/utils/chart_tooltip.js
index 3b3b6f1453..228095602c 100644
--- a/app/javascript/utils/chart_tooltip.js
+++ b/app/javascript/utils/chart_tooltip.js
@@ -11,8 +11,22 @@
// Not to be confused with DS::Tooltip — that is the info-icon hint primitive
// (bg-inverse, aria-describedby, anchored to a static trigger). This is a
// data-card surface created and updated inside D3 handler code.
+// The surface itself lives in the design system as `.chart-tooltip`
+// (sure-design-system/components.css): container bg, 10px radius, 12x14
+// padding, hairline ring composed with a soft 8/24 drop shadow, 80ms
+// left/top glide. It's a component class because Tailwind shadow utilities
+// can't compose a ring with a custom drop shadow. This constant adds the
+// behavioural classes shared by every chart tooltip.
export const CHART_TOOLTIP_CLASSES =
- "bg-container text-primary text-sm font-sans absolute p-2 border border-secondary rounded-lg pointer-events-none z-50 privacy-sensitive";
+ "chart-tooltip text-primary text-sm font-sans absolute pointer-events-none z-50 privacy-sensitive";
+
+// Content conventions (kept here so the controllers stay aligned):
+// - context line (date / node title): `text-xs text-secondary mb-1`
+// - money / numeric figures: tabular-nums so digits don't jitter while the
+// scrubber moves (sans, not mono — the app's money convention everywhere
+// else); secondary parentheticals in `text-secondary`
+export const CHART_TOOLTIP_CONTEXT_CLASSES = "text-xs text-secondary mb-1";
+export const CHART_TOOLTIP_VALUE_CLASSES = "font-medium tabular-nums";
// Convenience factory for the raw-DOM idiom (no d3.select). Creates a hidden
// tooltip div carrying the shared contract and appends it to `parent`.
diff --git a/app/views/goals/show.html.erb b/app/views/goals/show.html.erb
index 6409f4d87f..bffcfdf84f 100644
--- a/app/views/goals/show.html.erb
+++ b/app/views/goals/show.html.erb
@@ -231,7 +231,8 @@
data-goal-projection-chart-aria-description-value="<%= strip_tags(@goal.projection_summary) %>"
data-goal-projection-chart-today-label-value="<%= t("goals.show.projection.today_marker") %>"
data-goal-projection-chart-projected-template-value="<%= t("goals.show.projection.tooltip_projected", amount: "{amount}") %>"
- data-goal-projection-chart-saved-template-value="<%= t("goals.show.projection.tooltip_saved", amount: "{amount}") %>"></div>
+ data-goal-projection-chart-saved-template-value="<%= t("goals.show.projection.tooltip_saved", amount: "{amount}") %>"
+ data-goal-projection-chart-target-relation-template-value="<%= t("goals.show.projection.tooltip_target_relation", percent: "{percent}", target: "{target}") %>"></div>
<% if @goal.target_date.nil? %>
<div class="mt-3 flex items-center gap-2 text-xs text-secondary">
<span class="text-subdued"><%= icon("calendar-plus", size: "sm") %></span>
diff --git a/config/locales/views/goals/en.yml b/config/locales/views/goals/en.yml
index cf2a5a57a7..c8b04b9d2a 100644
--- a/config/locales/views/goals/en.yml
+++ b/config/locales/views/goals/en.yml
@@ -153,6 +153,7 @@ en:
today_marker: Today
tooltip_projected: "Projected: %{amount}"
tooltip_saved: "Saved: %{amount}"
+ tooltip_target_relation: "%{percent}% of %{target} target"
catch_up:
title: "Save %{amount}/mo more to catch up"
body: "Current pace %{avg}/mo · required %{required}/mo to hit your target."