The personal finance app for everyone (by everyone)
Ruby
Redraw a resized chart once, when its size settles (#4930)
Yong Cong Sin69696c666d3f
diff --git a/app/javascript/controllers/bar_chart_controller.js b/app/javascript/controllers/bar_chart_controller.jsindex cbe96848b1..f3e8fb1ae6 100644--- a/app/javascript/controllers/bar_chart_controller.js+++ b/app/javascript/controllers/bar_chart_controller.js@@ -1,6 +1,7 @@import { Controller } from "@hotwired/stimulus";import * as d3 from "d3";import { CHART_TOOLTIP_CLASSES } from "utils/chart_tooltip";+import SettledResize from "utils/settled_resize";// Grouped bar chart used by the dashboard "money flow" widget — each month// shows an expense bar (red) and an income bar (green) side by side.@@ -10,6 +11,8 @@ import { CHART_TOOLTIP_CLASSES } from "utils/chart_tooltip";// Breathing room between neighbouring month labels before they read as touching.const LABEL_GAP_PX = 8;+const MARGIN = { top: 16, right: 4, bottom: 24, left: 4 };+const BAND_PADDING = 0.3;export default class extends Controller {static values = {@@ -19,24 +22,32 @@ export default class extends Controller {expenseLabel: { type: String, default: "Expenses" },};- _resizeObserver = null;+ _settledResize = null;connect() {this._install();document.addEventListener("turbo:load", this._reinstall);- this._resizeObserver = new ResizeObserver(() => this._reinstall());- this._resizeObserver.observe(this.element);+ // The month labels step down (full, short, every other) as the chart+ // narrows: a resize across one of those steps redraws then, rather than+ // stretch labels that no longer fit, or stay cut back, until the end.+ this._settledResize = new SettledResize(this.element, this._reinstall, {+ layoutChanges: (from, to) =>+ this._labelFit(from.width) !== this._labelFit(to.width),+ margins: { left: MARGIN.left, right: MARGIN.right },+ });+ this._settledResize.start();}disconnect() {this._teardown();document.removeEventListener("turbo:load", this._reinstall);- this._resizeObserver?.disconnect();+ this._settledResize?.stop();}_reinstall = () => {this._teardown();this._install();+ this._settledResize?.drew();};_teardown() {@@ -50,7 +61,7 @@ export default class extends Controller {if (width < 50 || height < 50 || data.length === 0) return;- const margin = { top: 16, right: 4, bottom: 24, left: 4 };+ const margin = MARGIN;const innerWidth = width - margin.left - margin.right;const innerHeight = height - margin.top - margin.bottom;@@ -72,7 +83,7 @@ export default class extends Controller {.scaleBand().domain(data.map((d) => d.label)).range([0, innerWidth])- .padding(0.3);+ .padding(BAND_PADDING);const x1 = d3.scaleBand().domain(series).range([0, x0.bandwidth()]).padding(0.15);@@ -143,15 +154,21 @@ export default class extends Controller {// then the abbreviated month, then every other tick. Measuring beats guessing// at a character width, which varies by locale, font and zoom._fitAxisLabels(labels, data, step) {+ this._labelWidths = null;if (labels.empty()) return;+ // Both widths, so _labelFit can tell the step at any other chart width.const widest = () => d3.max(labels.nodes(), (node) => node.getComputedTextLength()) || 0;- const fits = () => widest() <= step - LABEL_GAP_PX;-- if (fits()) return;-+ const full = widest();labels.text((_d, i) => data[i].short_label ?? data[i].label);- if (fits()) return;+ this._labelWidths = { full, short: widest(), count: data.length };++ const fit = this._labelFit(this.element.clientWidth, step);+ if (fit === "full") {+ labels.text((_d, i) => data[i].label);+ return;+ }+ if (fit === "short") return;// Still too wide (a very narrow column): thin out rather than overlap.// The parity is taken from the highlighted month rather than fixed at even,@@ -164,6 +181,26 @@ export default class extends Controller {labels.style("display", (_d, i) => (i % 2 === keepParity ? null : "none"));}+ // Which labels fit a chart this wide: "full", "short" or "alternate" (every+ // other short label). Null before the labels were measured.+ _labelFit(width, step = null) {+ const widths = this._labelWidths;+ if (!widths) return null;++ const bandStep =+ step ??+ d3+ .scaleBand()+ .domain(d3.range(widths.count))+ .range([0, width - MARGIN.left - MARGIN.right])+ .padding(BAND_PADDING)+ .step();+ const room = bandStep - LABEL_GAP_PX;+ if (widths.full <= room) return "full";+ if (widths.short <= room) return "short";+ return "alternate";+ }+_tooltipTemplate(month, key) {const label = key === "income" ? this.incomeLabelValue : this.expenseLabelValue;// Match the bar/legend palette — expenses render gray, not destructive red.diff --git a/app/javascript/controllers/sankey_chart_controller.js b/app/javascript/controllers/sankey_chart_controller.jsindex 41220216de..b2be3d6255 100644--- a/app/javascript/controllers/sankey_chart_controller.js+++ b/app/javascript/controllers/sankey_chart_controller.js@@ -10,6 +10,7 @@ import {buildCategoryTransactionsUrl,isNavigableCategoryNode,} from "utils/transactions_filter_url";+import SettledResize from "utils/settled_resize";// Connects to data-controller="sankey-chart"export default class extends Controller {@@ -47,12 +48,28 @@ export default class extends Controller {connect() {this.connected = true;this.zoomRootId = null;- this.resizeObserver = new ResizeObserver(() => this.#draw());- this.resizeObserver.observe(this.#chartElement());+ // Crossing the subcategory threshold changes the columns, which a+ // stretched drawing can't show: redraw then, not only at the end.+ const minWidth = this.constructor.SUBCATEGORY_MIN_WIDTH;+ this.settledResize = new SettledResize(+ this.#chartElement(),+ () => this.#draw(),+ {+ layoutChanges: (from, to) =>+ from.width < minWidth !== to.width < minWidth,+ // The extent's margin keeps its width, so the outer bars and their+ // labels stay put at the edges.+ margins: {+ left: this.constructor.EXTENT_MARGIN,+ right: this.constructor.EXTENT_MARGIN,+ },+ },+ );this.tooltip = null;this.#createTooltip();this.#syncZoomControls();this.#draw();+ this.settledResize.start();// A Turbo morph refresh (the sync toast's auto-refresh) keeps this// element and its controller but puts the server markup back around@@ -81,7 +98,7 @@ export default class extends Controller {disconnect() {this.connected = false;document.removeEventListener("turbo:morph", this.onMorph);- this.resizeObserver?.disconnect();+ this.settledResize?.stop();clearTimeout(this.drawTimeout);this.tooltip?.remove();this.tooltip = null;@@ -136,6 +153,7 @@ export default class extends Controller {chart.selectAll("svg").remove();this.#render(nodes, links, width, false);}+ this.settledResize?.drew();}#render(nodes, links, width, animate) {@@ -325,6 +343,8 @@ export default class extends Controller {.data(links).join("path").attr("class", "sankey-link")+ // Stays joined to its bars while a resize stretches the drawing.+ .attr("data-settled-resize-joins", "").attr("d", (d) =>d3.linkHorizontal()({source: [d.source.x1, d.y0],@@ -347,6 +367,8 @@ export default class extends Controller {nodeGroups.append("path").attr("d", (d) => this.#nodePath(d))+ // Keeps its width while a resize stretches the drawing (SettledResize).+ .attr("data-settled-resize-keep-width", "").attr("fill", (d) => d.color || this.constructor.DEFAULT_COLOR).attr("stroke", (d) => (d.color ? "none" : "var(--color-gray-500)"));diff --git a/app/javascript/controllers/spending_chart_controller.js b/app/javascript/controllers/spending_chart_controller.jsindex 6f1d761ca9..63931789ba 100644--- a/app/javascript/controllers/spending_chart_controller.js+++ b/app/javascript/controllers/spending_chart_controller.js@@ -1,6 +1,7 @@import { Controller } from "@hotwired/stimulus";import * as d3 from "d3";import { CHART_TOOLTIP_CLASSES } from "utils/chart_tooltip";+import SettledResize from "utils/settled_resize";// Cumulative spending chart for the dashboard "spending" widget: the selected// month's running total (green, ending today while the month is in progress)@@ -11,6 +12,9 @@ import { CHART_TOOLTIP_CLASSES } from "utils/chart_tooltip";const CURRENT_COLOR = "var(--color-success)";const PREVIOUS_COLOR = "var(--color-gray-400)";+// The axis column on the right is part of the margin.+const MARGIN = { top: 8, right: 48, bottom: 20, left: 4 };+export default class extends Controller {static values = {data: Object,@@ -19,24 +23,32 @@ export default class extends Controller {previousLabel: { type: String, default: "Previous" },};- _resizeObserver = null;+ _settledResize = null;connect() {this._install();document.addEventListener("turbo:load", this._reinstall);- this._resizeObserver = new ResizeObserver(() => this._reinstall());- this._resizeObserver.observe(this.element);+ // The axis column on the right keeps its width while a resize stretches+ // the drawing.+ this._settledResize = new SettledResize(this.element, this._reinstall, {+ margins: { left: MARGIN.left, right: MARGIN.right },+ // The day axis spans the whole month on wide screens and the days so+ // far on narrow ones: a resize across that width redraws at once.+ layoutChanges: () => this._wideAxis !== this._isWide(),+ });+ this._settledResize.start();}disconnect() {this._teardown();document.removeEventListener("turbo:load", this._reinstall);- this._resizeObserver?.disconnect();+ this._settledResize?.stop();}_reinstall = () => {this._teardown();this._install();+ this._settledResize?.drew();};_teardown() {@@ -59,7 +71,7 @@ export default class extends Controller {// Room on the right for the axis labels ($0, $1.5K, …), like the// reference design; the curves run to the axis, not the card edge.- const margin = { top: 8, right: 48, bottom: 20, left: 4 };+ const margin = MARGIN;const innerWidth = width - margin.left - margin.right;const innerHeight = height - margin.top - margin.bottom;@@ -167,13 +179,19 @@ export default class extends Controller {).call((g) => g.select(".domain").remove()).selectAll("text")+ .attr("data-settled-resize-edge", "right").attr("class", "text-secondary fill-current").style("font-size", "12px").style("font-weight", "500");}+ _isWide() {+ return window.matchMedia("(min-width: 640px)").matches;+ }+_drawXAxis(group, x, days, innerHeight, axisLabels, currentDays = days) {- const mobile = !window.matchMedia("(min-width: 640px)").matches;+ this._wideAxis = this._isWide();+ const mobile = !this._wideAxis;const span = mobile ? Math.min(days, currentDays) : days;const tickDays = [...new Set([1, Math.round((1 + span) / 2), span])];diff --git a/app/javascript/controllers/time_series_chart_controller.js b/app/javascript/controllers/time_series_chart_controller.jsindex 12a6534b1e..917a9186dd 100644--- a/app/javascript/controllers/time_series_chart_controller.js+++ b/app/javascript/controllers/time_series_chart_controller.js@@ -1,6 +1,7 @@import { Controller } from "@hotwired/stimulus";import * as d3 from "d3";import { CHART_TOOLTIP_CLASSES } from "utils/chart_tooltip";+import SettledResize from "utils/settled_resize";const parseLocalDate = d3.timeParse("%Y-%m-%d");@@ -19,7 +20,7 @@ export default class extends Controller {_d3InitialContainerWidth = 0;_d3InitialContainerHeight = 0;_normalDataPoints = [];- _resizeObserver = null;+ _settledResize = null;_d3DragSelectBrush = null;_d3DragSelectGroup = null;// d3 only nulls a truly zero-width selection, so 1-3px of jitter on a click@@ -37,13 +38,14 @@ export default class extends Controller {connect() {this._install();document.addEventListener("turbo:load", this._reinstall);- this._setupResizeObserver();+ this._settledResize = new SettledResize(this.element, this._reinstall);+ this._settledResize.start();}disconnect() {this._teardown();document.removeEventListener("turbo:load", this._reinstall);- this._resizeObserver?.disconnect();+ this._settledResize?.stop();}_reinstall = () => {@@ -66,6 +68,8 @@ export default class extends Controller {this._normalizeDataPoints();this._rememberInitialContainerSize();this._draw();+ this._settledResize?.drew();+ this.element.dispatchEvent(new CustomEvent("time-series-chart:drawn", { bubbles: true }));}_normalizeDataPoints() {@@ -256,7 +260,10 @@ export default class extends Controller {// We know we only have 2 valuesreturn i === 0 ? "5em" : "-5em";})- .attr("dy", "0em");+ .attr("dy", "0em")+ // While the chart is stretched (utils/settled_resize), each date keeps its+ // distance from its own edge.+ .attr("data-settled-resize-edge", (_d, i) => (i === 0 ? "left" : "right"));}_drawGradientBelowTrendline() {@@ -729,11 +736,4 @@ export default class extends Controller {.rangeRound([this._d3ContainerHeight, 0]).domain([yMin, yMax]);}-- _setupResizeObserver() {- this._resizeObserver = new ResizeObserver(() => {- this._reinstall();- });- this._resizeObserver.observe(this.element);- }}diff --git a/app/javascript/utils/settled_resize.js b/app/javascript/utils/settled_resize.jsnew file mode 100644index 0000000000..47f6988d78--- /dev/null+++ b/app/javascript/utils/settled_resize.js@@ -0,0 +1,315 @@+// Redraws a chart once its container has settled on a new size, stretching+// the drawing it already has in the meantime.+//+// A container resized by an animation (a sidebar opening or closing) or by a+// drag changes size on every frame, and a full d3 redraw on each of them makes+// the animation stutter. Instead the existing SVG is stretched to the new size+// at once, and `redraw` runs when a width transition around the chart ends or+// the size has not changed for `settleMs`. A size that did not change (the+// observer's first callback right after the chart drew) redraws nothing.+//+// Only a width is stretched. A height change (a dashboard height preset, a+// dialog sized to the window) redraws at once: charts have fixed vertical+// margins and data-sized strokes (a Sankey's flows) that a vertical stretch+// would distort, and the animations this is for only change widths.+//+// A chart whose layout changes with its size (the Sankey drops a column below+// a width) passes `layoutChanges(from, to)`: a resize across such a change+// redraws at once rather than stretch a drawing with the wrong columns, so a+// column appears or goes as the width passes the threshold, not at the end.+//+// A shape marked `data-settled-resize-keep-width` (a Sankey's bars) keeps its+// width the same way; a label beside one stays beside it, and a shape marked+// `data-settled-resize-joins` (a Sankey's links) stays joined to the kept+// shapes at its ends. Circles (dots) stay round and lines keep their stroke+// width.+//+// A chart with fixed margins (a Sankey's 16px extent, an axis column) passes+// `margins: { left, right }`: only the part between them is stretched, so+// what sits at the edges stays at its distance from them rather than drift+// with the stretch and jump back at the end.+//+// Text is not stretched with the drawing: each label is scaled back to its+// normal shape around its anchor, and a label marked+// `data-settled-resize-edge="left"` or `"right"` also keeps its distance from+// that edge, so the redraw at the end finds it where it already is.+// Transitions that change an element's width: a sidebar animates its width+// when it opens or closes, and its max-width when resized from the keyboard+// or reset to its default.+const LAYOUT_PROPERTIES = new Set(["width", "max-width", "min-width", "flex-basis"]);++// How far from a kept-width shape a label still counts as beside it.+const BESIDE = 12;++export default class SettledResize {+ constructor(+ element,+ redraw,+ {+ settleMs = 150,+ layoutChanges = () => false,+ margins = { left: 0, right: 0 },+ } = {},+ ) {+ this.element = element;+ this.redraw = redraw;+ this.settleMs = settleMs;+ this.layoutChanges = layoutChanges;+ this.margins = margins;+ this.timer = null;+ this.drawnSize = null;+ // Width transitions running around the chart (a sidebar animating): while+ // any is, only its end settles the chart, not a pause in resizes.+ this.transitions = new Set();+ }++ start() {+ this.drawnSize = this.#size();+ this.observer = new ResizeObserver(() => this.#onResize());+ this.observer.observe(this.element);+ document.addEventListener("transitionrun", this.#onTransitionRun);+ document.addEventListener("transitionend", this.#onTransitionEnd);+ document.addEventListener("transitioncancel", this.#onTransitionEnd);+ }++ stop() {+ this.observer?.disconnect();+ document.removeEventListener("transitionrun", this.#onTransitionRun);+ document.removeEventListener("transitionend", this.#onTransitionEnd);+ document.removeEventListener("transitioncancel", this.#onTransitionEnd);+ clearTimeout(this.timer);+ this.timer = null;+ this.transitions.clear();+ }++ // The chart drew (for any reason): this is now the size it is drawn at.+ drew() {+ this.drawnSize = this.#size();+ this.textGeometry = null;+ // A pending settle would only draw the same size again.+ clearTimeout(this.timer);+ this.timer = null;+ }++ #size() {+ return { width: this.element.clientWidth, height: this.element.clientHeight };+ }++ #onResize() {+ const size = this.#size();+ const drawn = this.drawnSize;+ if (drawn && size.width === drawn.width && size.height === drawn.height) {+ // Back at the drawn size before settling (a quick drag back and forth):+ // the drawing may still be stretched to the last size, so undo that.+ const stretched = this.element.querySelector("svg");+ if (this.timer && stretched) {+ // Resets the labels' counter-scaling; the drawing is at its own+ // size again, so it isn't stretched either.+ this.#stretch(stretched, size);+ stretched.removeAttribute("preserveAspectRatio");+ }+ clearTimeout(this.timer);+ this.timer = null;+ return;+ }++ const svg = this.element.querySelector("svg");+ // Nothing to stretch (a chart that was hidden or too small to draw), a+ // new height, or a size the chart lays out differently: draw now.+ if (+ !svg ||+ !drawn ||+ drawn.width <= 0 ||+ drawn.height <= 0 ||+ size.height !== drawn.height ||+ this.layoutChanges(drawn, size)+ ) {+ this.#settle();+ return;+ }++ this.#stretch(svg, size);+ clearTimeout(this.timer);+ // During a width transition, wait for its end (with a long fallback in case+ // it never comes); otherwise for a pause in resizes (a drag, a window).+ // A transition whose element left the page (a Turbo morph replaced a+ // sidebar mid-animation) never reports its end here: it no longer counts.+ for (const target of this.transitions) {+ if (!target.isConnected) this.transitions.delete(target);+ }+ const wait = this.transitions.size > 0 ? 1000 : this.settleMs;+ this.timer = setTimeout(() => this.#settle(), wait);+ }++ #stretch(svg, size) {+ // Measure the labels once, as drawn, before anything is stretched; again+ // if the SVG was replaced since (a chart's delayed, animated draw).+ if (!this.textGeometry || this.textGeometrySvg !== svg) {+ this.keptGeometry = this.#measureShapes(svg, "[data-settled-resize-keep-width]").map((shape) => ({+ ...shape,+ share: this.#keptWidthShare(shape),+ }));+ this.joinGeometry = this.#measureShapes(svg, "[data-settled-resize-joins]");+ this.textGeometry = this.#measureTexts(svg);+ this.textGeometrySvg = svg;+ }+ const drawn = this.drawnSize;+ const { sx, offset } = this.#horizontalMap(size);+ // x maps to sx * x + offset: the margins keep their width, the part+ // between them stretches by sx.+ svg.setAttribute("viewBox", `${-offset / sx} 0 ${size.width / sx} ${drawn.height}`);+ svg.setAttribute("width", size.width);+ svg.setAttribute("preserveAspectRatio", "none");+ this.textGeometry.forEach((geometry) => this.#keepTextShape(geometry, sx, size));+ // Shapes whose width is part of the design (a Sankey's bars) keep it too,+ // dots stay round, and lines keep their stroke width, so nothing thickens,+ // thins or turns oval with the stretch and snaps back at the end.+ this.keptGeometry.forEach(({ element, share }) => {+ element.style.transformBox = "fill-box";+ element.style.transformOrigin = `${share * 100}% 50%`;+ element.style.transform = `scale(${1 / sx}, 1)`;+ });+ this.joinGeometry.forEach((join) => this.#keepJoined(join, sx, offset));+ svg.querySelectorAll("circle").forEach((dot) => {+ dot.style.transformBox = "fill-box";+ dot.style.transformOrigin = "50% 50%";+ dot.style.transform = `scale(${1 / sx}, 1)`;+ });+ svg.querySelectorAll("path, line, polyline").forEach((line) => {+ line.style.vectorEffect = "non-scaling-stroke";+ });+ }++ // The horizontal stretch: a factor for the part between the margins, and the+ // shift that keeps the left margin's width (sx * x + offset).+ // Where across its width a kept-width shape is held: its share of the way+ // from the left margin to the right one (0 at the left margin, 1 at the+ // right). A bar at the edge keeps its distance from it, and every bar sits+ // where a drawing at this width would put it (a Sankey spaces its columns+ // evenly between the margins). Measured once per drawing.+ #keptWidthShare({ x, width }) {+ const left = Math.min(this.margins.left || 0, this.drawnSize.width / 4);+ const right = Math.min(this.margins.right || 0, this.drawnSize.width / 4);+ const room = this.drawnSize.width - left - right - width;+ return room > 0 ? Math.min(Math.max((x - left) / room, 0), 1) : 0.5;+ }++ // Where a kept-width shape's left edge is shown, in pixels from the chart's+ // left: its anchor point stretches, and the shape keeps its width around it.+ #keptLeft({ x, width, share }, sx, offset) {+ return offset + sx * x + (sx - 1) * share * width;+ }++ // Shapes' boxes in the chart's own coordinates (their groups' offsets+ // included), and the offset of their own coordinates.+ #measureShapes(svg, selector) {+ const toSvg = svg.getScreenCTM()?.inverse();+ return Array.from(svg.querySelectorAll(selector)).flatMap((element) => {+ const ctm = element.getScreenCTM();+ if (!toSvg || !ctm) return [];+ const local = toSvg.multiply(ctm);+ const box = element.getBBox();+ return [{ element, originX: local.e, x: local.e + box.x, width: box.width, y: local.f + box.y, height: box.height }];+ });+ }++ // A shape joining two kept-width shapes (a link from a bar's right edge to+ // another's left edge) is mapped so its ends stay on theirs; an end that+ // joins none just stretches.+ #keepJoined({ element, originX, x, width }, sx, offset) {+ if (width <= 0) return;+ const near = (a, b) => Math.abs(a - b) < 0.5;+ const from = this.keptGeometry.find((kept) => near(kept.x + kept.width, x));+ const to = this.keptGeometry.find((kept) => near(kept.x, x + width));+ const start = from ? this.#keptLeft(from, sx, offset) + from.width : offset + sx * x;+ const end = to ? this.#keptLeft(to, sx, offset) : offset + sx * (x + width);+ // In the chart's coordinates, before the stretch maps them to pixels.+ const startX = (start - offset) / sx;+ const scale = ((end - offset) / sx - startX) / width;+ const shift = startX - scale * x - originX * (1 - scale);+ element.style.transformBox = "view-box";+ element.style.transformOrigin = "0 0";+ element.style.transform = `matrix(${scale}, 0, 0, 1, ${shift}, 0)`;+ }++ #horizontalMap(size) {+ const drawn = this.drawnSize;+ const left = Math.min(this.margins.left || 0, drawn.width / 4);+ const right = Math.min(this.margins.right || 0, drawn.width / 4);+ const inner = drawn.width - left - right;+ const sx = inner > 0 ? Math.max(size.width - left - right, 1) / inner : size.width / drawn.width;+ return { sx, offset: inner > 0 ? left * (1 - sx) : 0 };+ }++ // Where each label's anchor sits, in the chart's own coordinates (its+ // groups' offsets included), and which share of its box that anchor is at.+ #measureTexts(svg) {+ const toSvg = svg.getScreenCTM()?.inverse();+ return Array.from(svg.querySelectorAll("text")).flatMap((text) => {+ const box = text.getBBox();+ const ctm = text.getScreenCTM();+ if (!toSvg || !ctm || box.width === 0) return [];+ const anchor = getComputedStyle(text).textAnchor;+ const share = anchor === "start" ? 0 : anchor === "end" ? 1 : 0.5;+ const local = toSvg.multiply(ctm);+ const x = local.e + box.x + box.width * share;+ // A label just beside a kept-width shape (a Sankey bar's name and value)+ // stays beside it. Any shape in that column will do: they all move+ // alike.+ const beside = this.keptGeometry.find(+ (kept) => x >= kept.x - BESIDE && x <= kept.x + kept.width + BESIDE,+ );+ return [{ text, share, x, edge: text.dataset.settledResizeEdge, beside }];+ });+ }++ // Scales a label back by the stretch, around the point its text-anchor puts+ // it at, so its glyphs keep their shape; an edge label is moved to keep its+ // distance from that edge.+ #keepTextShape({ text, share, x, edge, beside }, sx, size) {+ const { offset } = this.#horizontalMap(size);+ const at = sx * x + offset;+ let dx = 0;+ if (edge === "left") dx = (x - at) / sx;+ if (edge === "right") dx = (size.width - (this.drawnSize.width - x) - at) / sx;+ if (beside) dx = (this.#keptLeft(beside, sx, offset) + (x - beside.x) - at) / sx;+ text.style.transformBox = "fill-box";+ text.style.transformOrigin = `${share * 100}% 50%`;+ text.style.transform = `translate(${dx}px, 0) scale(${1 / sx}, 1)`;+ }++ #settle() {+ clearTimeout(this.timer);+ this.timer = null;+ this.redraw();+ this.drawnSize = this.#size();+ this.textGeometry = null;+ }++ // A width transition that can resize the chart: on one of its ancestors, or+ // on an element in the layout beside one (a sidebar next to the chart's+ // column). One elsewhere on the page (another card's progress bar) or out of+ // the layout (a fixed toast, an absolutely placed popover) can't, and must+ // not hold back or hurry the chart's redraw.+ #isLayoutTransition(event) {+ const target = event.target;+ if (!LAYOUT_PROPERTIES.has(event.propertyName) || !(target instanceof Element)) return false;+ if (this.element.contains(target)) return false;+ if (target.contains(this.element)) return true;+ if (!target.parentElement?.contains(this.element)) return false;+ const position = getComputedStyle(target).position;+ return position !== "fixed" && position !== "absolute";+ }++ #onTransitionRun = (event) => {+ if (this.#isLayoutTransition(event)) this.transitions.add(event.target);+ };++ // A layout transition (a sidebar's width) has ended: redraw at once rather+ // than wait out the settle delay, once no other one is still running.+ #onTransitionEnd = (event) => {+ if (!this.#isLayoutTransition(event)) return;+ this.transitions.delete(event.target);+ if (this.timer && this.transitions.size === 0) this.#settle();+ };+}diff --git a/test/system/chart_sidebar_resize_test.rb b/test/system/chart_sidebar_resize_test.rbnew file mode 100644index 0000000000..c4fdab819c--- /dev/null+++ b/test/system/chart_sidebar_resize_test.rb@@ -0,0 +1,584 @@+require "application_system_test_case"++# Opening or closing a sidebar animates its width, which resizes the charts+# beside it on every frame. Charts that redrew on each of those frames made the+# animation stutter; they now stretch their drawing during the animation and+# draw once, at the size the animation ends on (utils/settled_resize).+class ChartSidebarResizeTest < ApplicationSystemTestCase+ include EntriesTestHelper+ NET_WORTH = "#main [data-controller~='time-series-chart']".freeze++ setup do+ sign_in users(:family_admin)+ page.driver.browser.manage.window.resize_to(1100, 900)+ visit root_path+ assert_selector "#{NET_WORTH} svg"+ wait_until_settled+ end++ teardown do+ page.execute_script("localStorage.clear()") rescue nil+ end++ test "a sidebar animation redraws each dashboard chart at most once, at its final size" do+ assert_selector "#main [data-controller~='sankey-chart'] svg"+ page.execute_script(<<~JS)+ // The charts that redraw through SettledResize (the donut sizes itself).+ window.__charts = Array.from(document.querySelectorAll("#main [data-controller]"))+ .filter((el) => el.dataset.controller.split(" ").some((name) => ["time-series-chart", "sankey-chart", "bar-chart", "spending-chart"].includes(name)));+ window.__draws = window.__charts.map(() => 0);+ window.__widths = window.__charts.map((chart) => chart.querySelector("svg")?.parentElement.clientWidth);+ new MutationObserver((mutations) => mutations.forEach((m) => m.addedNodes.forEach((node) => {+ if (node.nodeName !== "svg") return;+ const i = window.__charts.findIndex((chart) => chart.contains(node));+ if (i >= 0) window.__draws[i]++;+ }))).observe(document.getElementById("main"), { childList: true, subtree: true });+ JS+ before = net_worth_width+ toggle_left_sidebar+ wait_until_settled(changed_from: before)++ charts = nil+ page.document.synchronize(10) do+ charts = page.evaluate_script(<<~JS)+ window.__charts.map((chart, i) => {+ const svg = chart.querySelector("svg");+ const width = svg?.parentElement.clientWidth;+ return { name: `${i}:${chart.dataset.controller}`, draws: window.__draws[i], resized: width !== window.__widths[i],+ // Drawn at its container's width, in its drawing coordinates too,+ // and not stretched (a stretched drawing carries preserveAspectRatio).+ fits: !!svg && Number(svg.getAttribute("width")) === width &&+ (!svg.hasAttribute("viewBox") || Number(svg.getAttribute("viewBox").split(/[ ,]+/)[2]) === width) &&+ !svg.hasAttribute("preserveAspectRatio") };+ })+ JS+ # Only charts whose width changed.+ raise Capybara::ExpectationNotMet, "a resized chart is still stretched: #{charts.inspect}" unless charts.all? { |chart| !chart["resized"] || chart["fits"] }+ end+ assert_operator charts.size, :>=, 4, "expected the dashboard's time-series, Sankey, bar and spending charts: #{charts.inspect}"+ draws = charts.to_h { |chart| [ chart["name"], chart["draws"] ] }+ puts "chart sidebar resize draws: #{draws.inspect}"+ charts.select { |chart| chart["resized"] }.each do |chart|+ assert_operator chart["draws"], :>=, 1, "#{chart["name"]} changed width but was never redrawn"+ end+ # One draw as the animation ends; a loaded machine can stall long enough+ # mid-animation to settle once early, so allow a second. Redrawing on every+ # frame was 6-7 draws per chart.+ draws.each do |chart, count|+ assert_operator count, :<=, 2, "#{chart} was drawn #{count} times during one sidebar animation"+ end+ end++ test "the chart's dates keep their shape and their place at the edges while a sidebar animates" do+ assert_selector "#{NET_WORTH} svg .tick text", count: 2+ page.execute_script(<<~JS)+ window.__labels = []; window.__sampling = true;+ // Measured after each frame is painted (resize observers run before the+ // paint, after requestAnimationFrame callbacks), so it sees what was shown.+ const afterPaint = (fn) => requestAnimationFrame(() => setTimeout(fn, 0));+ const sample = () => {+ const element = document.querySelector("#{NET_WORTH}");+ const container = element.getBoundingClientRect();+ const svg = element.querySelector("svg");+ const [first, last] = Array.from(element.querySelectorAll("svg .tick text")).map((t) => t.getBoundingClientRect());+ // On a slow machine this can run after the next animation step has+ // begun, measuring a layout the chart has not followed yet and that was+ // never painted: only count frames where the drawing fills its container.+ const painted = svg && Math.round(Number(svg.getAttribute("width"))) === Math.round(container.width);+ if (first && last && painted) window.__labels.push([Math.round(container.width), first.left - container.left, container.right - last.right, first.width, last.width]);+ if (window.__sampling) afterPaint(sample);+ };+ // The settled baseline, before the toggle; then after each paint.+ sample();+ JS+ before = net_worth_width+ toggle_left_sidebar+ wait_until_settled(changed_from: before)+ # The chart can settle between two samples: stop only once one at the+ # final width is in.+ final = net_worth_width+ page.document.synchronize(10) do+ last = page.evaluate_script("window.__labels.at(-1)?.[0]")+ raise Capybara::ExpectationNotMet, "no sample at the final width yet (last: #{last.inspect})" unless last == final+ end+ page.execute_script("window.__sampling = false")++ samples = page.evaluate_script("window.__labels")+ widths = samples.map(&:first)+ assert_equal before, widths.first, "sampling began after the animation had started"+ assert_equal net_worth_width, widths.last, "sampling ended before the animation finished"+ assert widths.any? { |width| width != widths.first && width != widths.last }, "no sample fell inside the animation: #{widths.uniq.inspect}"++ spread = samples.transpose.drop(1).map { |values| (values.max - values.min).round(1) }+ puts "date labels (left gap, right gap, widths) spread: #{spread.inspect}"+ assert spread.all? { |value| value <= 2 }, "the dates moved or changed shape during the animation: #{spread.inspect}"+ end++ # A quick drag back and forth can bring a chart back to the size it was drawn+ # at before it settles; its drawing must not stay stretched to the last size.+ test "a chart resized and back before it settles fits its container again" do+ result = page.evaluate_async_script(<<~JS)+ const done = arguments[0];+ const element = document.querySelector("#{NET_WORTH}");+ const original = element.clientWidth;+ element.style.width = Math.round(original * 0.6) + "px";+ requestAnimationFrame(() => requestAnimationFrame(() => {+ element.style.width = "";+ requestAnimationFrame(() => requestAnimationFrame(() => {+ const svg = element.querySelector("svg");+ done({ container: element.clientWidth, svg: Number(svg.getAttribute("width")), original, stretched: svg.hasAttribute("preserveAspectRatio") });+ }));+ }));+ JS++ assert_equal result["original"], result["container"]+ assert_equal result["container"], result["svg"], "the chart's drawing stayed stretched to the intermediate size: #{result.inspect}"+ assert_not result["stretched"], "the chart is back at its drawn size but still marked as stretched (preserveAspectRatio)"+ end++ # Only a width transition that can resize the chart (a sidebar beside it)+ # holds its redraw back until it ends; one elsewhere on the page, or out of+ # the layout, must not.+ test "a width transition elsewhere on the page does not hold back a resized chart's redraw" do+ {+ "in a box of its own" => "const box = document.createElement('div'); box.append(bar); document.body.append(box);",+ "fixed, directly in the body" => "bar.style.position = 'fixed'; bar.style.top = '0'; document.body.append(bar);"+ }.each do |where, place|+ visit root_path+ assert_selector "#{NET_WORTH} svg"+ wait_until_settled++ elapsed = page.evaluate_async_script(<<~JS)+ const done = arguments[0];+ const bar = document.createElement("div");+ bar.style.cssText = "width: 0; height: 1px; transition: width 3s linear";+ #{place}+ requestAnimationFrame(() => requestAnimationFrame(() => {+ bar.style.width = "200px";+ requestAnimationFrame(() => {+ const element = document.querySelector("#{NET_WORTH}");+ const started = performance.now();+ element.style.width = Math.round(element.clientWidth * 0.6) + "px";+ const check = () => {+ const svg = element.querySelector("svg");+ if (svg && Number(svg.getAttribute("width")) === element.clientWidth && !svg.hasAttribute("preserveAspectRatio")) done(performance.now() - started);+ else if (performance.now() - started > 3000) done(null);+ else requestAnimationFrame(check);+ };+ requestAnimationFrame(check);+ });+ }));+ JS++ assert elapsed, "the resized chart was never redrawn (transition #{where})"+ assert_operator elapsed, :<, 700, "the resized chart waited for an unrelated transition #{where} (#{elapsed.round} ms)"+ end+ end++ # The bar chart's month labels step down (full, short, every other) as it+ # narrows. A stretched drawing would keep the starting labels across such a+ # step, overlapping or needlessly cut back until the end: it redraws then.+ test "the bar chart shows the labels that fit its width on every frame of a sidebar animation" do+ page.driver.browser.manage.window.resize_to(1400, 900)+ visit root_path+ bar = "#main [data-controller~='bar-chart']"+ assert_selector "#{bar} svg"+ page.execute_script(%(document.querySelector("#{bar}").scrollIntoView({ block: "center" })))+ wait_until_settled++ # Twelve months, so the step from full labels ("Jan 2026") to short ones+ # ("Jan") falls inside the range the sidebar toggle moves this chart+ # through. Set as the chart's data attribute; a size change draws it.+ page.execute_script(<<~JS)+ const months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];+ window.__months = months;+ const element = document.querySelector("#{bar}");+ element.setAttribute("data-bar-chart-data-value", JSON.stringify(months.map((m, i) => ({ label: `${m} 2026`, short_label: m, income: 1000 + i * 50, expense: 800 + i * 40, highlighted: i === 11 }))));+ element.style.width = `${element.clientWidth - 1}px`;+ // Held long enough to settle (and draw) before going back.+ setTimeout(() => { element.style.width = ""; }, 400);+ JS+ page.document.synchronize(10) do+ count = page.evaluate_script(%(Array.from(document.querySelectorAll("#{bar} svg g text")).filter((t) => window.__months.some((m) => t.textContent.startsWith(m))).length))+ raise Capybara::ExpectationNotMet, "the twelve months are not drawn yet (#{count})" unless count == 12+ end++ # What a drawing shows, read from the page: every other label hidden,+ # short labels, or full ones; and whether two shown labels overlap.+ page.execute_script(<<~JS)+ window.__shown = (element) => {+ const labels = Array.from(element.querySelectorAll("svg g text")).filter((t) => window.__months.some((m) => t.textContent.startsWith(m)));+ const visible = labels.filter((t) => t.style.display !== "none" && t.getAttribute("display") !== "none");+ const boxes = visible.map((t) => t.getBoundingClientRect()).sort((a, b) => a.left - b.left);+ const overlap = boxes.some((box, i) => i > 0 && box.left < boxes[i - 1].right);+ const mode = visible.length < labels.length ? "alternate" : labels.every((t, i) => t.textContent === window.__months[i]) ? "short" : "full";+ return { mode, overlap };+ };+ JS++ page.execute_script(<<~JS)+ window.__frames = []; window.__sampling = true;+ const element = document.querySelector("#{bar}");+ const afterPaint = (fn) => requestAnimationFrame(() => setTimeout(fn, 0));+ const sample = () => {+ const svg = element.querySelector("svg");+ const width = element.clientWidth;+ if (svg && Math.round(Number(svg.getAttribute("width"))) === width) {+ const { mode, overlap } = window.__shown(element);+ window.__frames.push([width, mode, overlap]);+ }+ if (window.__sampling) afterPaint(sample);+ };+ sample();+ JS+ before = net_worth_width+ toggle_left_sidebar+ wait_until_settled(changed_from: before)+ sleep 0.3+ page.execute_script("window.__sampling = false")+ frames = page.evaluate_script("window.__frames")++ # What the chart shows when drawn at rest at each of those widths.+ widths = frames.map(&:first).uniq+ settled = page.evaluate_async_script(<<~JS, widths)+ const [widths, done] = arguments;+ const element = document.querySelector("#{bar}");+ const result = {};+ const next = (i) => {+ if (i === widths.length) { element.style.width = ""; return done(result); }+ element.style.width = `${widths[i]}px`;+ const wait = (tries) => {+ const svg = element.querySelector("svg");+ const drawn = svg && Number(svg.getAttribute("width")) === widths[i] && !svg.hasAttribute("preserveAspectRatio");+ if (drawn || tries > 40) { result[widths[i]] = window.__shown(element).mode; next(i + 1); }+ else setTimeout(() => wait(tries + 1), 50);+ };+ setTimeout(() => wait(0), 50);+ };+ next(0);+ JS++ assert_operator settled.values.uniq.size, :>, 1, "the toggle never crossed a label step (widths #{widths.inspect}, at rest #{settled.inspect})"+ overlapping = frames.select(&:last).map(&:first)+ assert_empty overlapping, "labels overlapped on frames at widths #{overlapping.inspect}"+ wrong = frames.reject { |width, mode, _| mode == settled[width.to_s] }.map { |width, mode, _| [ width, mode, settled[width.to_s] ] }+ assert_empty wrong, "frames showing other labels than the chart draws at rest at their width (width, shown, at rest): #{wrong.uniq.inspect}"+ ensure+ page.execute_script("localStorage.clear()") rescue nil+ end++ # A Turbo morph can replace a sidebar while it animates; its transition then+ # never reports an end, and must not hold back every later redraw.+ test "a sidebar removed mid-animation does not hold back a resized chart's redraw" do+ page.execute_script(%(if (!document.querySelector("[name='csrf-token']")) { const m = document.createElement("meta"); m.name = "csrf-token"; m.content = "test"; document.head.append(m) }))+ elapsed = page.evaluate_async_script(<<~JS)+ const done = arguments[0];+ document.querySelector("[data-action='app-layout#toggleLeftSidebar']").click();+ setTimeout(() => {+ document.querySelector("[data-app-layout-target='leftSidebar']").remove();+ setTimeout(() => {+ const element = document.querySelector("#{NET_WORTH}");+ const started = performance.now();+ element.style.width = Math.round(element.clientWidth * 0.6) + "px";+ const check = () => {+ const svg = element.querySelector("svg");+ if (svg && Number(svg.getAttribute("width")) === element.clientWidth && !svg.hasAttribute("preserveAspectRatio")) done(performance.now() - started);+ else if (performance.now() - started > 3000) done(null);+ else requestAnimationFrame(check);+ };+ requestAnimationFrame(check);+ }, 500);+ }, 80);+ JS++ assert elapsed, "the resized chart was never redrawn"+ assert_operator elapsed, :<, 700, "the resized chart waited for the removed sidebar's transition (#{elapsed.round} ms)"+ ensure+ page.execute_script("localStorage.clear()") rescue nil+ end++ # A Sankey's bars have a set width; stretched with the drawing they thickened+ # or thinned during the animation and snapped back at the end.+ test "a Sankey's bars keep their width while a sidebar animates" do+ sankey = "#main [data-controller~='sankey-chart']"+ assert_selector "#{sankey} svg path[data-settled-resize-keep-width]"+ page.execute_script(<<~JS)+ window.__bars = []; window.__sampling = true;+ const afterPaint = (fn) => requestAnimationFrame(() => setTimeout(fn, 0));+ const sample = () => {+ const bar = document.querySelector("#{sankey} svg path[data-settled-resize-keep-width]");+ if (bar) window.__bars.push(Math.round(bar.getBoundingClientRect().width * 10) / 10);+ if (window.__sampling) afterPaint(sample);+ };+ sample();+ JS+ before = net_worth_width+ toggle_left_sidebar+ wait_until_settled(changed_from: before)+ page.execute_script("window.__sampling = false")++ widths = page.evaluate_script("window.__bars")+ assert_operator widths.size, :>, 3, "too few frames sampled"+ assert_operator widths.max - widths.min, :<=, 1, "a Sankey bar changed width during the animation: #{widths.uniq.inspect}"+ ensure+ page.execute_script("localStorage.clear()") rescue nil+ end++ test "the spending chart's dots stay round while a sidebar animates" do+ spending = "#main [data-controller~='spending-chart']"+ assert_selector "#{spending} svg circle"+ page.execute_script(<<~JS)+ window.__dots = []; window.__sampling = true;+ const afterPaint = (fn) => requestAnimationFrame(() => setTimeout(fn, 0));+ const sample = () => {+ const dot = document.querySelector("#{spending} svg circle");+ if (dot) { const r = dot.getBoundingClientRect(); window.__dots.push(Math.round((r.width - r.height) * 10) / 10); }+ if (window.__sampling) afterPaint(sample);+ };+ sample();+ JS+ before = net_worth_width+ toggle_left_sidebar+ wait_until_settled(changed_from: before)+ page.execute_script("window.__sampling = false")++ skews = page.evaluate_script("window.__dots")+ assert_operator skews.size, :>, 3, "too few frames sampled"+ assert skews.all? { |skew| skew.abs <= 1 }, "a dot turned oval during the animation (width - height): #{skews.uniq.inspect}"+ ensure+ page.execute_script("localStorage.clear()") rescue nil+ end++ # Margins are fixed in pixels (a Sankey's 16px extent, the spending chart's+ # axis column): stretched with the drawing, what sits at the edges drifted+ # away from or towards them and jumped back at the end.+ test "bars, dots and labels keep their distance from the chart's edges, and links stay on their bars, while a sidebar animates" do+ sankey = "#main [data-controller~='sankey-chart']"+ spending = "#main [data-controller~='spending-chart']"+ assert_selector "#{sankey} svg path[data-settled-resize-keep-width]"+ assert_selector "#{spending} svg circle"+ page.execute_script(<<~JS)+ window.__gaps = []; window.__sampling = true;+ const afterPaint = (fn) => requestAnimationFrame(() => setTimeout(fn, 0));+ const sample = () => {+ // The chart's drawing, not an icon's svg beside it.+ const sankeySvg = document.querySelector("#{sankey} svg path[data-settled-resize-keep-width]").ownerSVGElement;+ const bars = Array.from(sankeySvg.querySelectorAll("path[data-settled-resize-keep-width]")).map((b) => b.getBoundingClientRect());+ const box = sankeySvg.getBoundingClientRect();+ const spendingSvg = document.querySelector("#{spending} svg circle").ownerSVGElement;+ const sbox = spendingSvg.getBoundingClientRect();+ const label = spendingSvg.querySelector("text[data-settled-resize-edge='right']")?.getBoundingClientRect();+ const dot = spendingSvg.querySelector("circle")?.getBoundingClientRect();+ // The links leaving the leftmost bars start on their right edge, and+ // the label beside those bars keeps its distance from it. Picked as+ // drawn, then followed.+ const leftmost = Math.min(...bars.map((b) => b.left));+ const firstColumn = bars.filter((b) => Math.abs(b.left - leftmost) < 1);+ const columnRight = Math.max(...firstColumn.map((b) => b.right));+ if (!window.__followed || !window.__followed.svg.isConnected || window.__followed.svg !== sankeySvg) {+ window.__followed = {+ svg: sankeySvg,+ links: Array.from(sankeySvg.querySelectorAll("path.sankey-link")).filter((l) => Math.abs(l.getBoundingClientRect().left - columnRight) < 2),+ label: Array.from(sankeySvg.querySelectorAll("text")).find((t) => { const r = t.getBoundingClientRect(); return r.left > columnRight && r.left - columnRight < 20; }),+ };+ }+ const joined = window.__followed.links.map((l) => l.getBoundingClientRect());+ const beside = window.__followed.label?.getBoundingClientRect();+ window.__gaps.push([+ leftmost - box.left,+ box.right - Math.max(...bars.map((b) => b.right)),+ label ? sbox.right - label.right : null,+ // A dot inside the plot moves with it: its place along the plot (the+ // chart's 4px and 48px margins aside), in thousandths, holds instead.+ dot ? (dot.left + dot.width / 2 - sbox.left - 4) / (sbox.width - 52) * 1000 : null,+ joined.length ? Math.max(...joined.map((l) => Math.abs(l.left - columnRight))) : null,+ beside ? beside.left - columnRight : null,+ ].map((v) => v === null ? null : Math.round(v)));+ if (window.__sampling) afterPaint(sample);+ };+ sample();+ JS+ before = net_worth_width+ toggle_left_sidebar+ wait_until_settled(changed_from: before)+ page.execute_script("window.__sampling = false")++ gaps = page.evaluate_script("window.__gaps")+ assert_operator gaps.size, :>, 3, "too few frames sampled"+ names = [ "Sankey left bar", "Sankey right bar", "spending axis label", "spending dot (place along the plot)", "Sankey links' start (from their bar)", "Sankey label (from its bar)" ]+ assert gaps.all? { |frame| frame[4] && frame[5] }, "no link or label beside the Sankey's first column: #{gaps.first.inspect}"+ moved = gaps.transpose.each_with_index.filter_map do |values, i|+ values = values.compact+ "#{names[i]}: #{values.inspect}" if values.any? && values.max - values.min > (i == 3 ? 3 : 1)+ end+ assert_empty moved, "moved against the chart's edges during the animation"+ ensure+ page.execute_script("localStorage.clear()") rescue nil+ end++ # The Sankey drops its subcategory column below 640px. Stretching a drawing+ # across that width would show the wrong columns until the animation ends+ # (a squeezed column, or one that pops in at the end): it redraws as the+ # width passes the threshold instead.+ test "a Sankey animated across the subcategory width shows the columns for its width on every frame" do+ family = users(:family_admin).family+ parent = family.categories.create!(name: "Sankey Shopping", color: "#123456")+ child = family.categories.create!(name: "Sankey Groceries", parent: parent)+ account = family.accounts.create!(name: "Sankey checking", currency: "USD", balance: 0, accountable: Depository.new)+ create_transaction(account: account, category: parent, amount: 100, date: Date.current - 2)+ create_transaction(account: account, category: child, amount: 50, date: Date.current - 2)+ page.driver.browser.manage.window.resize_to(1400, 900)+ visit root_path+ sankey = "#main [data-controller~='sankey-chart']"+ assert_selector "#{sankey} svg"+ page.execute_script(%(document.querySelector("#{sankey}").scrollIntoView({ block: "center" })))+ wait_until_settled++ page.execute_script(<<~JS)+ window.__frames = []; window.__sampling = true;+ const afterPaint = (fn) => requestAnimationFrame(() => setTimeout(fn, 0));+ const chart = document.querySelector("#{sankey} [data-sankey-chart-target='chart']") || document.querySelector("#{sankey}");+ const sample = () => {+ const svg = chart.querySelector("svg");+ const width = chart.clientWidth;+ const painted = svg && Math.round(Number(svg.getAttribute("width"))) === Math.round(width);+ // By datum: the subcategory's bar, whether or not its label fits.+ const sub = !!svg && Array.from(svg.querySelectorAll("g > path:not(.sankey-link)")).some((bar) => bar.__data__?.name === "Sankey Groceries");+ if (painted) window.__frames.push([width, sub]);+ if (window.__sampling) afterPaint(sample);+ };+ sample();+ JS+ before = net_worth_width+ toggle_left_sidebar+ wait_until_settled(changed_from: before)+ sleep 0.3+ page.execute_script("window.__sampling = false")++ frames = page.evaluate_script("window.__frames")+ widths = frames.map(&:first)+ assert_operator widths.min, :<, 640, "the chart never went below the threshold: #{widths.uniq.inspect}"+ assert_operator widths.max, :>=, 640, "the chart never reached the threshold: #{widths.uniq.inspect}"+ # Frames from inside the animation, on both sides of the threshold: the+ # first and last frames alone would pass with a chart that only redrew+ # at the end.+ inside = widths.reject { |width| width == widths.min || width == widths.max }+ assert inside.any? { |width| width < 640 }, "no painted frame inside the animation below 640px: #{widths.uniq.inspect}"+ assert inside.any? { |width| width >= 640 }, "no painted frame inside the animation at 640px or more: #{widths.uniq.inspect}"+ wrong = frames.reject { |width, sub| (width >= 640) == sub }+ assert_empty wrong, "frames showing the wrong columns for their width (width, subcategory shown): #{wrong.uniq.inspect}"+ ensure+ page.execute_script("localStorage.clear()") rescue nil+ end++ # The spending chart's day axis spans the whole month on wide screens and+ # the days so far on narrow ones. A stretched drawing kept the other span+ # until the resize settled.+ test "the spending chart redraws at once when a resize crosses its narrow-screen width" do+ spending = "#main [data-controller~='spending-chart']"+ page.driver.browser.manage.window.resize_to(700, 900)+ assert_selector "#{spending} svg circle"+ page.document.synchronize(10) do+ settled = page.evaluate_script(%((() => { const e = document.querySelector(#{spending.to_json}); const svg = e.querySelector("svg"); return !!svg && Number(svg.getAttribute("width")) === e.clientWidth && !svg.hasAttribute("preserveAspectRatio") })()))+ raise Capybara::ExpectationNotMet, "the spending chart has not settled" unless settled+ end+ page.execute_script(<<~JS)+ window.__crossed = null; window.__drawn = null;+ const element = document.querySelector(#{spending.to_json});+ const narrow = window.matchMedia("(min-width: 640px)");+ narrow.addEventListener("change", () => { window.__crossed ??= performance.now(); }, { once: true });+ new MutationObserver((mutations) => {+ if (window.__crossed !== null && window.__drawn === null && mutations.some((m) => Array.from(m.addedNodes).some((n) => n.nodeName === "svg"))) window.__drawn = performance.now();+ }).observe(element, { childList: true });+ JS+ page.driver.browser.manage.window.resize_to(600, 900)++ times = nil+ page.document.synchronize(10) do+ times = page.evaluate_script("({ crossed: window.__crossed, drawn: window.__drawn })")+ raise Capybara::ExpectationNotMet, "no redraw after crossing: #{times.inspect}" unless times["crossed"] && times["drawn"]+ end+ # A settle waits 150ms after the last resize; a layout change draws in the+ # same frame.+ assert_operator times["drawn"] - times["crossed"], :<, 100, "the chart waited to settle before showing the narrow-screen axis: #{times.inspect}"+ ensure+ page.driver.browser.manage.window.resize_to(1100, 900) rescue nil+ end++ # Resizing a sidebar from the keyboard (or resetting it) changes its+ # max-width, which animates too: its end must redraw the chart at once, not+ # a settle delay after the sidebar has stopped.+ test "a sidebar's max-width animation redraws the chart as it ends" do+ result = page.evaluate_async_script(<<~JS)+ const done = arguments[0];+ const chart = document.querySelector("#{NET_WORTH}");+ const sidebar = document.querySelector("[data-app-layout-target='leftSidebar']");+ let ended = null; let drawn = null;+ sidebar.addEventListener("transitionend", (event) => { if (event.propertyName === "max-width") ended ??= performance.now(); });+ new MutationObserver((mutations) => {+ if (ended !== null && drawn === null && mutations.some((m) => Array.from(m.addedNodes).some((n) => n.nodeName === "svg"))) drawn = performance.now();+ }).observe(chart, { childList: true, subtree: true });+ // 60px narrower than it is now, as an arrow key or a reset would.+ const width = Math.round(sidebar.getBoundingClientRect().width) - 60;+ document.querySelector("[data-controller~='sidebar-resize']").style.setProperty("--left-sidebar-width", `${width}px`);+ setTimeout(() => done({ ended, drawn }), 1200);+ JS++ assert result["ended"], "the sidebar's max-width never animated: #{result.inspect}"+ assert result["drawn"], "the chart was not redrawn after the animation: #{result.inspect}"+ assert_operator result["drawn"] - result["ended"], :<, 80, "the chart waited out the settle delay after the sidebar stopped: #{result.inspect}"+ end++ # A height change (a dashboard height preset, a dialog sized to the window)+ # is drawn at once: a vertical stretch would distort the charts' fixed+ # margins and a Sankey's flow widths until the settle.+ test "a chart whose height changes is redrawn at that height at once" do+ result = page.evaluate_async_script(<<~JS)+ const done = arguments[0];+ const element = document.querySelector("#{NET_WORTH}");+ const height = element.clientHeight + 120;+ element.style.height = `${height}px`;+ requestAnimationFrame(() => requestAnimationFrame(() => {+ const svg = element.querySelector("svg");+ done({ height, container: element.clientHeight, svg: Number(svg.getAttribute("height")), viewBox: Number(svg.getAttribute("viewBox").split(/[ ,]+/)[3]), stretched: svg.hasAttribute("preserveAspectRatio") });+ }));+ JS++ assert_equal result["height"], result["container"], "the container didn't take the new height: #{result.inspect}"+ assert_equal result["container"], result["svg"], "not drawn at the new height: #{result.inspect}"+ assert_equal result["container"], result["viewBox"], "drawn at the old height and stretched: #{result.inspect}"+ assert_not result["stretched"], "the drawing is stretched: #{result.inspect}"+ end++ private+ def toggle_left_sidebar+ # The toggle saves the preference first; the test layout has no csrf meta tag.+ page.execute_script(%(if (!document.querySelector("[name='csrf-token']")) { const m = document.createElement("meta"); m.name = "csrf-token"; m.content = "test"; document.head.append(m) }))+ find("[data-action='app-layout#toggleLeftSidebar']").click+ end++ def net_worth_width+ page.evaluate_script(%(document.querySelector(#{NET_WORTH.to_json}).clientWidth))+ end++ # Waits (bounded) until the net worth chart is drawn at its container's+ # size, unstretched, and that size has held for two checks in a row (and,+ # with changed_from, differs from that width).+ def wait_until_settled(changed_from: nil)+ last = nil+ page.document.synchronize(10) do+ state = page.evaluate_script(<<~JS)+ (() => {+ const element = document.querySelector(#{NET_WORTH.to_json});+ const svg = element.querySelector("svg");+ const viewBox = svg && Number(svg.getAttribute("viewBox").split(/[ ,]+/)[2]);+ return { width: element.clientWidth, drawn: !!svg && Number(svg.getAttribute("width")) === element.clientWidth && viewBox === element.clientWidth && !svg.hasAttribute("preserveAspectRatio") };+ })()+ JS+ stable = last && last["width"] == state["width"]+ last = state+ settled = state["drawn"] && stable && (changed_from.nil? || state["width"] != changed_from)+ raise Capybara::ExpectationNotMet, "the chart has not settled: #{state.inspect}" unless settled+ end+ end+end