The personal finance app for everyone (by everyone)
Ruby
Fix the goal projection chart's labels and dark-mode halos (#5312)
jaysbeekayed78520ef958
diff --git a/app/javascript/controllers/goal_projection_chart_controller.js b/app/javascript/controllers/goal_projection_chart_controller.jsindex 83f193d425..32e1e3d2ba 100644--- a/app/javascript/controllers/goal_projection_chart_controller.js+++ b/app/javascript/controllers/goal_projection_chart_controller.js@@ -52,6 +52,7 @@ export default class extends Controller {};connect() {+ this._connected = true;this._resize = this._draw.bind(this);window.addEventListener("resize", this._resize);// Container may have 0 width on initial connect (Turbo restoration,@@ -85,18 +86,32 @@ export default class extends Controller {};document.addEventListener("turbo:render", this._onTurboRender);document.addEventListener("turbo:frame-load", this._onTurboRender);++ // Date labels are measured to thin the axis and place the labels; measure+ // again whenever a font finishes loading, including one the chart's own+ // text starts loading after the first draw.+ this._onFontsLoaded = () => {+ if (this._connected) this._draw();+ };+ document.fonts?.addEventListener("loadingdone", this._onFontsLoaded);}disconnect() {+ this._connected = false;window.removeEventListener("resize", this._resize);this._observer?.disconnect();this._themeObserver?.disconnect();+ document.fonts?.removeEventListener("loadingdone", this._onFontsLoaded);if (this._onTurboRender) {document.removeEventListener("turbo:render", this._onTurboRender);document.removeEventListener("turbo:frame-load", this._onTurboRender);}}+ _boxesOverlap(a, b) {+ return a.x < b.x + b.width && b.x < a.x + a.width && a.y < b.y + b.height && b.y < a.y + a.height;+ }+_draw() {const root = this.element;root.innerHTML = "";@@ -110,7 +125,9 @@ export default class extends Controller {const textPrimary = isDark ? "#ffffff" : "#171717";const textSecondary = isDark ? "#cfcfcf" : "#737373";const borderSubdued = isDark ? "rgba(255,255,255,0.15)" : "rgba(0,0,0,0.10)";- const containerBg = isDark ? "#0a0a0a" : "#ffffff";+ // Halos, dot rings and hollow dots blend into the card the chart sits in+ // (DS::Card, bg-container), so they take that token in either theme.+ const containerBg = "var(--color-container)";// Reserve gutter for y-axis labels when there's room. Mobile (< 320)// keeps the tighter left margin and skips the y-axis entirely.@@ -276,7 +293,11 @@ export default class extends Controller {.attr("height", innerHeight);const plotClip = `url(#${clipId})`;+ // A gridline this close to the target line loses its tick label.const COLLISION_PX = 18;+ // A point label sits this far above its dot, or this far below it.+ const LABEL_ABOVE_PX = 8;+ const LABEL_BELOW_PX = 16;const targetY = targetAmount > 0 ? y(targetAmount) : null;// With a floor, label from the floor up in even steps so the bottom edge// carries a label; otherwise keep d3's default ticks.@@ -285,8 +306,6 @@ export default class extends Controller {? 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);if (yAxisVisible) {yTicks.forEach((tickValue) => {@@ -298,8 +317,8 @@ export default class extends Controller {.attr("y2", y(tickValue)).attr("stroke", borderSubdued).attr("stroke-width", 1);- // Skip the y-axis label when its row is close to the target line.- // The target's own label will take over that y-slot below.+ // Skip the y-axis label when its row is close to the target line,+ // which carries its own amount, so the row is not labelled twice.if (targetY !== null && Math.abs(y(tickValue) - targetY) < COLLISION_PX) return;svg.append("text")@@ -312,6 +331,12 @@ export default class extends Controller {});}+ let targetLabel = null;+ let projectionDot = null;+ // The projection-end or shortfall label, and how to clear a label it+ // collides with: drop an on-track one, move a shortfall below its dot.+ let pointLabel = null;+ let clearPointLabel = null;if (targetAmount > 0) {svg.append("line")@@ -323,29 +348,22 @@ export default class extends Controller {.attr("stroke-width", 1).attr("stroke-dasharray", "3 3");- if (targetCollidesWithTick) {- // Merge target label into the y-axis column at the target's y-row.- // The collided y-axis tick was suppressed above so this label takes- // over that slot cleanly.- svg- .append("text")- .attr("x", margin.left - 6)- .attr("y", targetY + 3)- .attr("text-anchor", "end")- .attr("font-size", 12)- .attr("fill", textPrimary)- .text(`Target · ${data.target_amount_short_label}`);- } else {- // Plenty of room: keep the right-side full-format label.- svg- .append("text")- .attr("x", margin.left + innerWidth - 4)- .attr("y", targetY - 6)- .attr("text-anchor", "end")- .attr("font-size", 12)- .attr("fill", textPrimary)- .text(`Target · ${data.target_amount_label}`);- }+ // Always on the right, in full, above the line. The y-axis gutter is+ // sized for short tick labels and cannot hold it. The halo keeps the+ // projection line from running through the text; it is raised above the+ // plot lines once they are drawn.+ targetLabel = svg+ .append("text")+ .attr("x", margin.left + innerWidth - 4)+ .attr("y", targetY - 6)+ .attr("text-anchor", "end")+ .attr("font-size", 12)+ .attr("fill", textPrimary)+ .attr("paint-order", "stroke")+ .attr("stroke", containerBg)+ .attr("stroke-width", 4)+ .attr("stroke-linejoin", "round")+ .text(`Target · ${data.target_amount_label}`);}const area = d3@@ -409,7 +427,7 @@ export default class extends Controller {.attr("stroke-dasharray", "4 4").attr("d", line);- svg+ projectionDot = svg.append("circle").attr("cx", x(target)).attr("cy", y(projectionEnd))@@ -418,14 +436,9 @@ export default class extends Controller {.attr("stroke", containerBg).attr("stroke-width", 2);- // Suppress the projection-end label when it would visually collide- // with the target label above. In a barely-on-track case the dot- // already conveys "you'll hit the target". duplicating "$2.4K"- // beside "Target · $2,400" adds noise.const projDotY = y(projectionEnd);- const collidesWithTargetLabel = targetAmount > 0 && Math.abs(projDotY - y(targetAmount)) < 18;- if (innerWidth >= 320 && !(willHit && collidesWithTargetLabel)) {+ if (innerWidth >= 320) {// Server-rendered labels: projection_end_label is the full-format// currency for the on-track endpoint, projection_shortfall_label// is the "$X short" string when we fall short.@@ -433,10 +446,10 @@ export default class extends Controller {? data.projection_end_label: (data.projection_shortfall_label ? `${data.projection_shortfall_label} short` : "");if (labelText) {- svg+ pointLabel = svg.append("text").attr("x", x(target) - 8)- .attr("y", y(projectionEnd) - 8)+ .attr("y", projDotY - LABEL_ABOVE_PX).attr("text-anchor", "end").attr("font-size", 12).attr("fill", textSecondary)@@ -445,6 +458,22 @@ export default class extends Controller {.attr("stroke-width", 4).attr("stroke-linejoin", "round").text(labelText);+ // Both labels end at the right edge, so a dot near the target line+ // puts this one on top of the target label: measured, not guessed+ // from the gap between the two lines. An on-track end label is+ // dropped (the dot already says the target is hit, and "$2.4K"+ // beside "Target · $2,400" is noise); a shortfall goes below its dot.+ clearPointLabel = () => {+ if (willHit) {+ pointLabel.remove();+ pointLabel = null;+ } else {+ pointLabel.attr("y", projDotY + LABEL_BELOW_PX);+ }+ };+ if (targetLabel && this._boxesOverlap(pointLabel.node().getBBox(), targetLabel.node().getBBox())) {+ clearPointLabel();+ }}}}@@ -459,7 +488,7 @@ export default class extends Controller {.attr("stroke-width", 1).attr("stroke-dasharray", "2 4");- svg+ const todayDot = svg.append("circle").attr("cx", x(today)).attr("cy", y(currentAmount))@@ -468,8 +497,9 @@ export default class extends Controller {.attr("stroke", containerBg).attr("stroke-width", 2);+ let todayLabel = null;if (innerWidth >= 320) {- svg+ todayLabel = svg.append("text").attr("x", x(today)).attr("y", margin.top - 4)@@ -479,13 +509,37 @@ export default class extends Controller {.text(this.todayLabelValue);}+ // A target date close to today puts Today at the right edge too, above a+ // point label near the top of the scale.+ if (pointLabel && todayLabel && this._boxesOverlap(pointLabel.node().getBBox(), todayLabel.node().getBBox())) {+ clearPointLabel();+ }++ if (targetLabel) {+ // On an overdue goal Today sits on the right edge too; a target near the+ // top of the scale would put the two labels on top of each other, so the+ // target label ends just left of Today instead. It stays above its line:+ // below it is where a near-miss shortfall label goes.+ if (todayLabel) {+ const todayBox = todayLabel.node().getBBox();+ if (this._boxesOverlap(targetLabel.node().getBBox(), todayBox)) {+ targetLabel.attr("x", todayBox.x - 6);+ }+ }+ // Painted after the plot lines so its halo masks the ones crossing it,+ // and under the dots, which its halo would otherwise cut into.+ targetLabel.raise();+ projectionDot?.raise();+ todayDot.raise();+ }+// Full 4-digit year so the terminal "Jan 2027" reads as the year, not// as "Jan 27" (which scans as January 27th). Slightly wider per tick;// the de-dupe logic below keeps the count sane.const tickFmt = d3.timeFormat("%b %Y");const tickCount = Math.min(5, Math.max(2, Math.round(innerWidth / 80)));const ticks = x.ticks(tickCount);- const tickGroup = svg.append("g");+ const tickGroup = svg.append("g").attr("data-axis", "x");tickGroup.selectAll("text").data(ticks)@@ -497,14 +551,34 @@ export default class extends Controller {.attr("font-size", 12).attr("fill", textSecondary).text((d) => tickFmt(d));- // De-dupe adjacent equal tick labels (e.g. multiple "May '26" on a- // short window where d3.ticks oversamples).+ // De-dupe adjacent equal tick labels first (daily ticks on a short window+ // all read "Jan 2027"), so the thinning below can't drop the only tick of+ // a month in favour of repeats of another.const tickNodes = tickGroup.selectAll("text").nodes();for (let i = tickNodes.length - 1; i > 0; i--) {if (tickNodes[i].textContent === tickNodes[i - 1].textContent) {tickNodes[i].remove();}}+ // d3 treats the tick count as a hint and can return nearly twice as many+ // (nine quarterly ticks for a two-year goal when asked for five). When the+ // widest label plus a gap is wider than the closest pair of labels, keep+ // every k-th label, so they thin to a regular interval. Counted back from+ // the last label, which is always kept: it is the goal's end date, and it+ // also keeps the axis from going blank.+ const LABEL_GAP_PX = 12;+ const labelNodes = tickGroup.selectAll("text").nodes();+ const widest = d3.max(labelNodes, (n) => n.getComputedTextLength());+ if (labelNodes.length >= 2 && Number.isFinite(widest) && widest > 0) {+ const positions = labelNodes.map((n) => Number(n.getAttribute("x")));+ const minSpacing = d3.min(d3.pairs(positions), ([a, b]) => b - a);+ const stride = minSpacing > 0 ? Math.ceil((widest + LABEL_GAP_PX) / minSpacing) : labelNodes.length;+ if (stride > 1) {+ labelNodes.forEach((n, i) => {+ if ((labelNodes.length - 1 - i) % stride !== 0) n.remove();+ });+ }+ }// Hover interactivity: crosshair + dots + tooltip on pointermove.// Transparent rect catches pointer events across the plot area.diff --git a/test/system/goal_projection_chart_test.rb b/test/system/goal_projection_chart_test.rbnew file mode 100644index 0000000000..c2baa2d6a4--- /dev/null+++ b/test/system/goal_projection_chart_test.rb@@ -0,0 +1,347 @@+require "application_system_test_case"++# What only a browser can say about the goal projection chart: where its text+# lands once laid out. Goal#projection_payload is covered by the model tests;+# these read the SVG the controller draws.+#+# The goal is the one the defects were reported against: $10,000 by+# 22 Oct 2028, created 22 Oct 2026, with $3,000 saved in one cash account.+class GoalProjectionChartTest < ApplicationSystemTestCase+ TODAY = Date.new(2026, 10, 22)+ TARGET_DATE = Date.new(2028, 10, 22)+ COLLISION_PX = 18++ setup do+ @user = users(:family_admin)+ # Goals sit behind the preview gate.+ @user.update!(+ preferences: (@user.preferences || {}).merge("preview_features_enabled" => true),+ show_ai_sidebar: false+ )+ travel_to(TODAY) { sign_in @user }+ end++ test "a target on a gridline keeps its full label inside the chart" do+ travel_to TODAY do+ visit_goal(target: 10_000)++ assert target_collides_with_gridline?, "premise: the $10,000 target must sit on a y-axis gridline"++ label = target_label+ assert_operator label["x"], :>=, 0, "the target label starts left of the chart: #{label.inspect}"+ assert_operator label["x"] + label["width"], :<=, svg_width, "the target label runs past the chart's right edge"+ assert_equal "Target · $10,000", label["text"], "the target label must use the full-format amount"+ # The gridline's own tick label is suppressed, so the row is labelled once.+ assert_not_includes chart_texts.map { |t| t["text"] }, "$10K"+ end+ end++ test "the target label is painted above the plot lines and under the dots" do+ travel_to TODAY do+ visit_goal(target: 10_000, saved: 3_000, pace: 330)++ order = page.evaluate_script(<<~JS)+ (() => {+ const kids = Array.from(document.querySelector("[data-controller='goal-projection-chart'] svg").children);+ const label = kids.findIndex((n) => n.tagName === "text" && n.textContent.startsWith("Target"));+ const lastPath = kids.map((n) => n.tagName).lastIndexOf("path");+ const circles = kids+ .map((n, i) => (n.tagName === "circle" && n.style.display !== "none" ? i : -1))+ .filter((i) => i >= 0);+ return { label, lastPath, circles };+ })()+ JS+ assert_operator order["lastPath"], :>=, 0, "premise: plot paths drawn"+ assert_operator order["label"], :>, order["lastPath"], "a line drawn after the label paints over its halo"+ assert_equal 2, order["circles"].size, "premise: the Today and projection-end dots are drawn"+ order["circles"].each do |circle|+ assert_operator circle, :>, order["label"], "the label's halo is painted over a dot"+ end+ end+ end++ test "on an overdue goal just short of its target the target label clears Today and the shortfall label" do+ travel_to TODAY do+ visit_goal(target: 10_000, saved: 9_900, target_date: TODAY, history_from: TODAY - 90.days)++ today_label = chart_texts.find { |t| t["text"] == "Today" }+ assert today_label, "premise: the Today label is drawn"+ assert_operator today_label["x"] + today_label["width"], :>, svg_width - 60, "premise: Today sits at the right edge"+ label = target_label+ assert_not boxes_overlap?(label, today_label), "Target and Today overlap: #{label.inspect} #{today_label.inspect}"+ assert_not boxes_overlap?(label, shortfall_label), "Target and shortfall overlap: #{label.inspect} #{shortfall_label.inspect}"+ end+ end++ # A target date a week away puts Today at the right edge, beside an end+ # label that sits near the top of the scale.+ test "a projection ending a week out keeps its labels clear of the Today label" do+ travel_to TODAY do+ visit_goal(target: 10_000, saved: 9_000, pace: 20_000, target_date: TODAY + 7.days, history_from: TODAY - 90.days)++ today_label = chart_texts.find { |t| t["text"] == "Today" }+ assert today_label, "premise: the Today label is drawn"+ chart_texts.reject { |t| t["text"] == "Today" }.each do |text|+ assert_not boxes_overlap?(text, today_label), "#{text["text"].inspect} overlaps Today: #{text.inspect} #{today_label.inspect}"+ end+ end+ end++ test "a window of daily ticks keeps the label of every month it covers" do+ travel_to Date.new(2027, 1, 25) do+ # The setup session is three months old by now.+ sign_in @user+ visit_goal(target: 10_000, target_date: Date.new(2027, 2, 1))+ resize_chart(428)++ labels = x_labels.map { |l| l["text"] }+ assert_equal [ "Jan 2027", "Feb 2027" ], labels+ end+ end++ test "an on-track projection ending at the target still drops its own end label" do+ travel_to TODAY do+ # $7,000 to go over ~24 months: the projection ends within a few dollars+ # of the target, so its end dot sits on the target line.+ goal = visit_goal(target: 10_000, saved: 3_000, pace: 291.67)+ end_label = Money.new(goal.projection_end_amount, "USD").format(precision: 0)++ end_dot_y = page.evaluate_script(<<~JS)+ Number(Array.from(document.querySelectorAll("[data-controller='goal-projection-chart'] svg circle"))+ .find((c) => c.getAttribute("fill") === "var(--color-green-600)").getAttribute("cy"))+ JS+ assert_operator (end_dot_y - target_line_y).abs, :<, COLLISION_PX, "premise: the projection ends on the target line"++ assert_equal "Target · $10,000", target_label["text"]+ assert_not_includes chart_texts.map { |t| t["text"] }, end_label, "the projection-end label must stay suppressed"+ end+ end++ # $3,000 saved at $280 a month ends about $280 short, so the end dot sits a+ # few pixels under the target line and both right-aligned labels share the+ # chart's right edge.+ test "a projection ending just short of the target keeps its shortfall label clear of the target label" do+ travel_to TODAY do+ visit_goal(target: 10_000, saved: 3_000, pace: 280)++ assert_operator (shortfall_dot_y - target_line_y).abs, :<, COLLISION_PX, "premise: the projection ends beside the target line"+ target = target_label+ shortfall = shortfall_label+ assert_not boxes_overlap?(target, shortfall), "the shortfall label overlaps the target label: #{[ target, shortfall ].inspect}"+ assert_operator shortfall["y"], :>, shortfall_dot_y, "the shortfall label moves below its dot"+ end+ end++ test "a projection ending well short of the target keeps its shortfall label above the dot" do+ travel_to TODAY do+ visit_goal(target: 10_000, saved: 3_000, pace: 200)++ assert_operator (shortfall_dot_y - target_line_y).abs, :>=, COLLISION_PX, "premise: the projection ends clear of the target line"+ assert_operator shortfall_label["y"] + shortfall_label["height"], :<=, shortfall_dot_y, "the shortfall label stays above its dot"+ end+ end++ # $3,000 saved at $200 a month: the projection falls short, so the chart+ # draws a halo'd shortfall label beside the halo'd target label.+ test "in the dark theme every halo and ring matches the card" do+ @user.update!(theme: "dark")+ travel_to TODAY do+ visit_goal(target: 10_000, saved: 3_000, pace: 200)+ assert_selector "html[data-theme='dark']"++ assert_backdrop_paint+ end+ end++ # The reported axis opens on Oct 2026, before the goal was created, so its+ # domain starts with the saved history: the 90 days the balance series+ # covers. Asked for "about 5" ticks, d3 then returns nine quarterly ones,+ # Oct 2026 to Oct 2028, about 52 px apart at this width.+ # Eight quarterly ticks, Oct 2026 to Jul 2028, thinned to every other one:+ # counted from the first label, the last (the goal's end) would be dropped.+ test "thinning the x-axis keeps the goal's end date" do+ travel_to TODAY do+ visit_goal(target: 10_000, target_date: Date.new(2028, 7, 22), history_from: TODAY - 90.days)+ resize_chart(560)++ labels = x_labels.map { |l| l["text"] }+ assert_operator labels.size, :<, 8, "premise: some labels are dropped to fit: #{labels}"+ assert_equal "Jul 2028", labels.last, "the goal's end date must keep its label: #{labels}"+ end+ end++ test "x-axis labels on a two-year goal do not overlap and keep the target date" do+ travel_to TODAY do+ visit_goal(target: 10_000, history_from: TODAY - 90.days)++ labels = x_labels+ assert_x_labels_clear(labels)+ assert_operator labels.size, :>=, 2, "thinning must not empty the axis"+ assert_equal "Oct 2028", labels.last["text"], "the goal's end date must keep its label: #{labels.map { |l| l["text"] }}"+ months = labels.map { |l| d = Date.strptime(l["text"], "%b %Y"); d.year * 12 + d.month }+ assert_equal 1, months.each_cons(2).map { |a, b| b - a }.uniq.size, "kept labels must advance by a regular interval: #{labels.map { |l| l["text"] }}"+ end+ end++ private++ # The saved history is pinned: empty by default, so the x-domain starts on+ # the day the goal was created; or one point at `history_from`, which is+ # where the domain then starts.+ # pace_measurable? is stubbed true: the test account has no transaction or+ # balance history, so the chart would otherwise draw no projection at all.+ def visit_goal(target:, saved: 3_000, pace: 0, target_date: TARGET_DATE, history_from: nil)+ Goal.any_instance.stubs(:pace).returns(pace)+ Goal.any_instance.stubs(:pace_measurable?).returns(true)+ history = history_from ? [ OpenStruct.new(date: history_from, value: Money.new(saved, "USD")) ] : []+ Goal.any_instance.stubs(:balance_series_values).returns(history)++ account = @user.family.accounts.create!(name: "Holiday savings", accountable: Depository.new, currency: "USD", balance: saved)+ goal = @user.family.goals.create!(+ name: "Japan holiday", target_amount: target, currency: "USD", target_date: target_date,+ goal_accounts: [ GoalAccount.new(account: account) ]+ )++ visit goal_path(goal)+ assert_selector "[data-controller='goal-projection-chart'] svg text", minimum: 1+ wait_for_settled_chart+ goal+ end++ # The first paint can land before the layout settles; the ResizeObserver+ # then redraws at the real width, and a font that finishes loading redraws+ # again, after `document.fonts.status` already reads "loaded". So wait for+ # the drawn width to match, the fonts to be loaded, and the same <svg> to+ # be found on two checks in a row: a redraw replaces it.+ def wait_for_settled_chart+ page.document.synchronize do+ settled = page.evaluate_script(<<~JS)+ (() => {+ const root = document.querySelector("[data-controller='goal-projection-chart']");+ const svg = root.querySelector("svg");+ const unchanged = !!svg && window.__settledChartSvg === svg;+ window.__settledChartSvg = svg;+ return unchanged && svg.viewBox.baseVal.width === root.clientWidth && document.fonts.status === "loaded";+ })()+ JS+ raise Capybara::ExpectationNotMet, "the chart has not redrawn at its settled width" unless settled+ end+ end++ # The colour each halo, ring and hollow dot resolves to, beside the colour+ # actually behind the chart: the nearest ancestor that paints a background.+ def backdrop_paint+ page.evaluate_script(<<~JS)+ (() => {+ const root = document.querySelector("[data-controller='goal-projection-chart']");+ let el = root;+ let backdrop = null;+ while (el && !backdrop) {+ const bg = getComputedStyle(el).backgroundColor;+ if (bg && bg !== "rgba(0, 0, 0, 0)" && bg !== "transparent") backdrop = bg;+ el = el.parentElement;+ }+ const svg = root.querySelector("svg");+ const halos = Array.from(svg.querySelectorAll("text[paint-order='stroke']"))+ .map((t) => ({ text: t.textContent, colour: getComputedStyle(t).stroke }));+ const rings = Array.from(svg.querySelectorAll("circle"))+ .map((c) => ({ fill: c.getAttribute("fill"), colour: getComputedStyle(c).stroke }));+ return { backdrop, halos, rings };+ })()+ JS+ end++ def assert_backdrop_paint+ paint = backdrop_paint+ # The target and shortfall labels; the projection end, Today and the two+ # hover dots.+ assert_operator paint["halos"].size, :>=, 2, "premise: halo'd labels drawn: #{paint["halos"].inspect}"+ assert_operator paint["rings"].size, :>=, 4, "premise: ringed dots drawn: #{paint["rings"].inspect}"++ backdrop = paint["backdrop"]+ (paint["halos"] + paint["rings"]).each do |item|+ assert_equal backdrop, item["colour"], "does not match the card behind the chart: #{item.inspect}"+ end+ end++ def x_labels+ page.evaluate_script(<<~JS)+ Array.from(document.querySelectorAll("[data-controller='goal-projection-chart'] g[data-axis='x'] text")).map((t) => {+ const b = t.getBBox();+ return { text: t.textContent, left: b.x, right: b.x + b.width };+ })+ JS+ end++ def assert_x_labels_clear(labels)+ labels.each_cons(2) do |a, b|+ assert_operator a["right"] + 4, :<=, b["left"], "#{a["text"]} runs into #{b["text"]}: #{labels.inspect}"+ end+ end++ def svg_width+ page.evaluate_script("document.querySelector(\"[data-controller='goal-projection-chart'] svg\").viewBox.baseVal.width")+ end++ # Every <text> in the chart with its laid-out box, in SVG user units.+ def chart_texts+ page.evaluate_script(<<~JS)+ Array.from(document.querySelectorAll("[data-controller='goal-projection-chart'] svg text")).map((t) => {+ const b = t.getBBox();+ return { text: t.textContent, x: b.x, y: b.y, width: b.width, height: b.height };+ })+ JS+ end++ def target_label+ labels = chart_texts.select { |t| t["text"].start_with?("Target") }+ assert_equal 1, labels.size, "expected one target label, got #{labels.inspect}"+ labels.first+ end++ def shortfall_label+ labels = chart_texts.select { |t| t["text"].end_with?(" short") }+ assert_equal 1, labels.size, "expected one shortfall label, got #{labels.inspect}"+ labels.first+ end++ # The end dot of a projection that falls short.+ def shortfall_dot_y+ page.evaluate_script(<<~JS)+ Number(Array.from(document.querySelectorAll("[data-controller='goal-projection-chart'] svg circle"))+ .find((c) => c.getAttribute("fill") === "var(--color-yellow-600)").getAttribute("cy"))+ JS+ end++ def boxes_overlap?(a, b)+ a["x"] < b["x"] + b["width"] && b["x"] < a["x"] + a["width"] &&+ a["y"] < b["y"] + b["height"] && b["y"] < a["y"] + a["height"]+ end++ # Solid horizontal lines across the plot: the y-axis gridlines.+ def gridline_ys+ page.evaluate_script(<<~JS)+ Array.from(document.querySelectorAll("[data-controller='goal-projection-chart'] svg line"))+ .filter((l) => l.getAttribute("y1") === l.getAttribute("y2") && !l.getAttribute("stroke-dasharray"))+ .map((l) => Number(l.getAttribute("y1")))+ JS+ end++ def target_line_y+ page.evaluate_script(<<~JS)+ Number(Array.from(document.querySelectorAll("[data-controller='goal-projection-chart'] svg line"))+ .find((l) => l.getAttribute("y1") === l.getAttribute("y2") && l.getAttribute("stroke-dasharray") === "3 3")+ .getAttribute("y1"))+ JS+ end++ def resize_chart(width)+ page.execute_script("document.querySelector(\"[data-controller='goal-projection-chart']\").style.width = '#{width}px'")+ wait_for_settled_chart+ end++ def target_collides_with_gridline?+ ty = target_line_y+ gridline_ys.any? { |gy| (gy - ty).abs < COLLISION_PX }+ end+end