The personal finance app for everyone (by everyone)
Ruby
Add drag-to-select date range on balance charts (#2733)
Anthony8bae95c6dd89
diff --git a/app/components/UI/account/chart.html.erb b/app/components/UI/account/chart.html.erbindex b96d3b9267..1bfe5997d6 100644--- a/app/components/UI/account/chart.html.erb+++ b/app/components/UI/account/chart.html.erb@@ -48,7 +48,8 @@id="lineChart"class="w-full h-full privacy-sensitive"data-controller="time-series-chart"- data-time-series-chart-data-value="<%= series.to_json %>"></div>+ data-time-series-chart-data-value="<%= series.to_json %>"+ data-time-series-chart-selectable-value="true"></div><% else %><div class="w-full h-full flex items-center justify-center"><p class="text-secondary text-sm"><%= t("UI.account.chart.no_data_available") %></p>diff --git a/app/components/UI/period_picker.html.erb b/app/components/UI/period_picker.html.erbindex d7ccbf3024..b4296cd1ef 100644--- a/app/components/UI/period_picker.html.erb+++ b/app/components/UI/period_picker.html.erb@@ -8,13 +8,35 @@<%= helpers.icon("chevron-down", size: "sm") %><% end %>+ <%# Both pickers navigate a Turbo frame — the dashboard's `dashboard_sections`+ and, implicitly, the account page's own container frame — and a frame+ navigation leaves the address bar alone. Without an explicit visit action+ a stale ?start_date/&end_date from a chart drag-select would outlive a+ preset pick and come back on refresh. See `turbo_action_for` for why the+ checked row replaces rather than advances. %><% periods.each do |period| %>+ <% period_selected = selected?(period.key) %><% menu.with_item(variant: :link,text: period.label_short,href: href_for(period.key),frame: frame,- selected: selected?(period.key)+ selected: period_selected,+ data: { turbo_action: turbo_action_for(period_selected) }+ ) %>+ <% end %>++ <% if custom_selected? %>+ <%# Last, so the presets keep their positions. Without this row a custom+ range leaves the list with nothing checked, which reads as "no selection"+ and hides the fact that picking a preset is how you leave it. %>+ <% menu.with_item(+ variant: :link,+ text: selected.label_short,+ href: custom_href,+ frame: frame,+ selected: true,+ data: { turbo_action: turbo_action_for(true) }) %><% end %><% end %>diff --git a/app/components/UI/period_picker.rb b/app/components/UI/period_picker.rbindex 60d75a459e..9dd04efa53 100644--- a/app/components/UI/period_picker.rb+++ b/app/components/UI/period_picker.rb@@ -9,11 +9,16 @@ class UI::PeriodPicker < ApplicationComponent# The selected period is marked with a check icon and `aria-current`, and the# trigger button shows its label.#+ # A custom range (no preset key — e.g. drag-selected on a chart) gets its own+ # trailing row so the list always has exactly one checked item, and the+ # trigger shows the range's actual dates rather than a bare "Custom".+ ## NOTE: `url` must be a path without a query string; pass query state via# `extra_params` so the picker can compose `?period=…` cleanly.- attr_reader :selected_key, :url, :frame, :extra_params, :placement+ attr_reader :selected, :selected_key, :url, :frame, :extra_params, :placementdef initialize(selected:, url:, frame: nil, extra_params: {}, placement: "bottom-end")+ @selected = selected@selected_key = selected.respond_to?(:key) ? selected.key : selected.to_s@url = url@frame = frame@@ -26,7 +31,18 @@ class UI::PeriodPicker < ApplicationComponentenddef selected_label- period_for(selected_key).label_short+ # A custom range's own label is just "Custom", which says nothing about what+ # the chart is showing. Show the dates instead.+ return selected.label_range if custom_selected?++ # A Period object knows its own label — no need to round-trip through PERIODS.+ selected.respond_to?(:label_short) ? selected.label_short : period_for(selected_key).label_short+ end++ # True when the selection is a Period with no preset key, i.e. an explicit+ # date range (drag-selected on a chart) rather than one of PERIODS.+ def custom_selected?+ selected_key.blank? && selected.is_a?(Period)enddef selected?(key)@@ -37,6 +53,36 @@ class UI::PeriodPicker < ApplicationComponent"#{url}?#{extra_params.merge(period: key).to_query}"end+ # Re-applies the range that is already active. Selecting it is a no-op by+ # design — the row exists to *represent* the current selection in a+ # single-select list, not to introduce a second way to set it.+ #+ # It stays a real link rather than an inert `aria-checked` row because the+ # list is a `role="menu"` with roving tabindex: a non-link row would either+ # drop out of arrow-key navigation or need bespoke keyboard handling to fake+ # what an anchor gives for free. A checked radio you can focus, announce and+ # re-activate for no effect is exactly how a radio group behaves anyway.+ def custom_href+ "#{url}?#{extra_params.merge(start_date: selected.start_date, end_date: selected.end_date).to_query}"+ end++ # Both pickers navigate a Turbo frame, and a frame navigation leaves the+ # address bar alone — hence an explicit visit action on every row.+ #+ # A pick that actually changes the range is a new view state, so it advances:+ # that restores what an unframed link would have done, and keeps a range+ # reachable with Back, which matters because the chart's drag-select pushes an+ # entry too (`Turbo.visit` defaults to advance). Advancing on one and+ # replacing on the other would make Back mean different things depending on+ # how the range was set.+ #+ # Re-picking the row that is already checked changes nothing, so it replaces+ # instead: a no-op has no business stacking a duplicate history entry the user+ # then has to press Back through twice to escape.+ def turbo_action_for(item_selected)+ item_selected ? "replace" : "advance"+ end+privatedef period_for(key)Period.from_key(key)diff --git a/app/controllers/concerns/periodable.rb b/app/controllers/concerns/periodable.rbindex bac4752537..7cd9de7d62 100644--- a/app/controllers/concerns/periodable.rb+++ b/app/controllers/concerns/periodable.rb@@ -7,6 +7,11 @@ module Periodableprivatedef set_period+ if params[:start_date].present? && params[:end_date].present?+ @period = custom_period_from_params+ return+ end+if params[:period].present?period_key = params[:period]Current.user&.update!(default_period: period_key) if Period.valid_key?(period_key)@@ -24,4 +29,13 @@ module Periodablerescue Period::InvalidKeyError@period = Period.last_30_daysend++ # Scoped to its own rescue so a bad/backwards date range (the only+ # expected failure here) can't be confused with an unrelated failure+ # elsewhere in #set_period, e.g. persisting the user's default_period.+ def custom_period_from_params+ Period.custom(start_date: Date.parse(params[:start_date]), end_date: Date.parse(params[:end_date]))+ rescue ArgumentError, TypeError, ActiveModel::ValidationError+ Period.last_30_days+ endenddiff --git a/app/javascript/controllers/time_series_chart_controller.js b/app/javascript/controllers/time_series_chart_controller.jsindex 5a13d2c9c8..a81ac43333 100644--- a/app/javascript/controllers/time_series_chart_controller.js+++ b/app/javascript/controllers/time_series_chart_controller.js@@ -10,6 +10,7 @@ export default class extends Controller {strokeWidth: { type: Number, default: 2 },useLabels: { type: Boolean, default: true },useTooltip: { type: Boolean, default: true },+ selectable: { type: Boolean, default: false },};_d3SvgMemo = null;@@ -19,6 +20,13 @@ export default class extends Controller {_d3InitialContainerHeight = 0;_normalDataPoints = [];_resizeObserver = null;+ _d3DragSelectBrush = null;+ _d3DragSelectGroup = null;+ // d3 only nulls a truly zero-width selection, so 1-3px of jitter on a click+ // still arrives here as a real drag. On a dense period (365D is ~2px per+ // point) that is enough to straddle two data points and navigate somewhere+ // the user never aimed at, so treat anything this small as a click.+ _dragSelectMinPx = 4;connect() {this._install();@@ -42,6 +50,8 @@ export default class extends Controller {this._d3GroupMemo = null;this._d3Tooltip = null;this._normalDataPoints = [];+ this._d3DragSelectBrush = null;+ this._d3DragSelectGroup = null;this._d3Container.selectAll("*").remove();}@@ -125,7 +135,10 @@ export default class extends Controller {if (this.useTooltipValue) {this._drawTooltip();- this._trackMouseForShowingTooltip();+ }++ if (this.useTooltipValue || this.selectableValue) {+ this._drawInteractionOverlay();}}@@ -303,97 +316,228 @@ export default class extends Controller {.attr("class", `${CHART_TOOLTIP_CLASSES} opacity-0 top-0`);}- _trackMouseForShowingTooltip() {- const bisectDate = d3.bisector((d) => d.date).left;+ // The interaction surface is either a plain full-size rect (hover-only charts)+ // or a d3-brush overlay (selectable charts, which also need drag capture).+ // Either way, tooltip handlers bind to whichever element ends up on top so+ // hover and drag-select never fight over the same pointer events.+ _drawInteractionOverlay() {+ if (this.selectableValue) {+ this._drawDragSelectOverlay();+ } else {+ this._drawHoverOverlay();+ }+ }- this._d3Group+ _drawHoverOverlay() {+ const rect = this._d3Group.append("rect").attr("class", "bg-container").attr("width", this._d3ContainerWidth).attr("height", this._d3ContainerHeight).attr("fill", "none")- .attr("pointer-events", "all")- .on("mousemove", (event) => {- const estimatedTooltipWidth = 250;- const pageWidth = document.body.clientWidth;- const tooltipX = event.pageX + 10;- const overflowX = tooltipX + estimatedTooltipWidth - pageWidth;- const adjustedX =- overflowX > 0 ? event.pageX - overflowX - 20 : tooltipX;+ .attr("pointer-events", "all");++ this._bindTooltipHandlers(rect);+ }++ _drawDragSelectOverlay() {+ const brush = d3+ .brushX()+ .extent([+ [0, 0],+ [this._d3ContainerWidth, this._d3ContainerHeight],+ ])+ // d3-brush treats any touch-capable device as "touchable" by default,+ // which makes it bind touchstart/touchmove and set touch-action: none+ // on the overlay — silently disabling native scroll on these full-width+ // charts. Drag-select is a mouse-only affordance for now, so opt out of+ // touch handling and leave scrolling/panning untouched on mobile.+ .touchable(false)+ .on("start brush", (event) => this._handleDragSelectMove(event))+ .on("end", (event) => this._handleDragSelectEnd(event));++ const brushGroup = this._d3Group+ .append("g")+ .attr("class", "drag-select-brush")+ .call(brush);++ brushGroup+ .select(".selection")+ .attr("fill", this._trendColor)+ .attr("fill-opacity", 0.12)+ .attr("stroke", this._trendColor)+ .attr("stroke-opacity", 0.5);++ // Idle hovering (before any mousedown) still goes through the overlay's+ // own mousemove — only an in-progress drag needs the brush events above.+ if (this.useTooltipValue) {+ this._bindTooltipHandlers(brushGroup.select(".overlay"));+ }++ this._d3DragSelectBrush = brush;+ this._d3DragSelectGroup = brushGroup;+ }++ // d3-brush captures mousemove at the window level while dragging, so the+ // overlay's own "mousemove" listener (used for plain hover) never fires+ // mid-drag. Drive the same tooltip off the brush's own events instead,+ // reading the pointer position from its sourceEvent — this is also what+ // keeps the tooltip glued to an exact data point instead of drifting to+ // whatever fraction-of-a-day pixel the mouse happens to be over.+ _handleDragSelectMove(event) {+ const sourceEvent = event.sourceEvent;+ if (!sourceEvent || typeof sourceEvent.pageX !== "number") return;++ const [xPos] = d3.pointer(sourceEvent, this._d3Group.node());+ const datum = this._nearestDataPointForPixel(xPos);++ this._renderTooltipAt(datum, sourceEvent.pageX, sourceEvent.pageY);+ }++ _handleDragSelectEnd(event) {+ this._hideTooltip();++ if (!event.selection) return;++ const [x0, x1] = event.selection;++ if (x1 - x0 < this._dragSelectMinPx) {+ this._d3DragSelectGroup?.call(this._d3DragSelectBrush.move, null);+ return;+ }++ // Snap to the actual plotted data points (same as the tooltip shown+ // during the drag) rather than the raw continuous pixel-to-time value —+ // a few pixels of mouse imprecision can otherwise land on a date that's+ // days away from the one the user was looking at on a wide chart.+ const startDatum = this._nearestDataPointForPixel(x0);+ const endDatum = this._nearestDataPointForPixel(x1);++ // Reject *after* snapping, which is where the outcome is actually decided:+ // a 30D chart is ~27px per point, so a drag can clear the pixel floor above+ // and still collapse to a single date. That range renders one value, which+ // sends _draw() down the empty-state path — and the empty state has no+ // brush left to drag back out of.+ if (startDatum === endDatum) {+ this._d3DragSelectGroup?.call(this._d3DragSelectBrush.move, null);+ return;+ }++ this._navigateToDateRange(startDatum.date, endDatum.date);+ }++ _navigateToDateRange(startDate, endDate) {+ const formatDate = d3.timeFormat("%Y-%m-%d");+ const url = new URL(window.location.href);++ url.searchParams.delete("period");+ url.searchParams.set("start_date", formatDate(startDate));+ url.searchParams.set("end_date", formatDate(endDate));++ Turbo.visit(url.toString());+ }++ _nearestDataPointForPixel(xPos) {+ const bisectDate = d3.bisector((d) => d.date).left;+ const clampedX = Math.max(0, Math.min(xPos, this._d3ContainerWidth));+ const x0 = bisectDate(+ this._normalDataPoints,+ this._d3XScale.invert(clampedX),+ 1,+ );+ const d0 = this._normalDataPoints[Math.max(x0 - 1, 0)];+ const d1 =+ this._normalDataPoints[Math.min(x0, this._normalDataPoints.length - 1)];++ return clampedX - this._d3XScale(d0.date) >+ this._d3XScale(d1.date) - clampedX+ ? d1+ : d0;+ }+ _bindTooltipHandlers(selection) {+ selection+ .on("mousemove", (event) => {const [xPos] = d3.pointer(event);- const x0 = bisectDate(- this._normalDataPoints,- this._d3XScale.invert(xPos),- 1,- );- const d0 = this._normalDataPoints[x0 - 1];- const d1 = this._normalDataPoints[x0];- const d =- xPos - this._d3XScale(d0.date) > this._d3XScale(d1.date) - xPos- ? d1- : d0;- const xPercent = this._d3XScale(d.date) / this._d3ContainerWidth;-- this._setTrendlineSplitAt(xPercent);-- // Reset- this._d3Group.selectAll(".data-point-circle").remove();- this._d3Group.selectAll(".guideline").remove();-- // Guideline- this._d3Group- .append("line")- .attr("class", "guideline text-subdued")- .attr("x1", this._d3XScale(d.date))- .attr("y1", 0)- .attr("x2", this._d3XScale(d.date))- .attr("y2", this._d3ContainerHeight)- .attr("stroke", "currentColor")- .attr("stroke-dasharray", "4, 4");-- // Big circle- this._d3Group- .append("circle")- .attr("class", "data-point-circle")- .attr("cx", this._d3XScale(d.date))- .attr("cy", this._d3YScale(this._getDatumValue(d)))- .attr("r", 10)- .attr("fill", this._trendColor)- .attr("fill-opacity", "0.1")- .attr("pointer-events", "none");-- // Small circle- this._d3Group- .append("circle")- .attr("class", "data-point-circle")- .attr("cx", this._d3XScale(d.date))- .attr("cy", this._d3YScale(this._getDatumValue(d)))- .attr("r", 5)- .attr("fill", this._trendColor)- .attr("pointer-events", "none");-- // Render tooltip- this._d3Tooltip- .html(this._tooltipTemplate(d))- .style("opacity", 1)- .style("z-index", 999)- .style("left", `${adjustedX}px`)- .style("top", `${event.pageY - 10}px`);+ const datum = this._nearestDataPointForPixel(xPos);++ this._renderTooltipAt(datum, event.pageX, event.pageY);}).on("mouseout", (event) => {const hoveringOnGuideline =event.toElement?.classList.contains("guideline");if (!hoveringOnGuideline) {- this._d3Group.selectAll(".guideline").remove();- this._d3Group.selectAll(".data-point-circle").remove();- this._d3Tooltip.style("opacity", 0);- this._setTrendlineSplitAt(1);+ this._hideTooltip();}});}+ _renderTooltipAt(datum, pageX, pageY) {+ const estimatedTooltipWidth = 250;+ const pageWidth = document.body.clientWidth;+ const tooltipX = pageX + 10;+ const overflowX = tooltipX + estimatedTooltipWidth - pageWidth;+ const adjustedX = overflowX > 0 ? pageX - overflowX - 20 : tooltipX;++ const xPercent = this._d3XScale(datum.date) / this._d3ContainerWidth;++ this._setTrendlineSplitAt(xPercent);++ // Reset+ this._d3Group.selectAll(".data-point-circle").remove();+ this._d3Group.selectAll(".guideline").remove();++ // Guideline+ this._d3Group+ .append("line")+ .attr("class", "guideline text-subdued")+ .attr("x1", this._d3XScale(datum.date))+ .attr("y1", 0)+ .attr("x2", this._d3XScale(datum.date))+ .attr("y2", this._d3ContainerHeight)+ .attr("stroke", "currentColor")+ .attr("stroke-dasharray", "4, 4");++ // Big circle+ this._d3Group+ .append("circle")+ .attr("class", "data-point-circle")+ .attr("cx", this._d3XScale(datum.date))+ .attr("cy", this._d3YScale(this._getDatumValue(datum)))+ .attr("r", 10)+ .attr("fill", this._trendColor)+ .attr("fill-opacity", "0.1")+ .attr("pointer-events", "none");++ // Small circle+ this._d3Group+ .append("circle")+ .attr("class", "data-point-circle")+ .attr("cx", this._d3XScale(datum.date))+ .attr("cy", this._d3YScale(this._getDatumValue(datum)))+ .attr("r", 5)+ .attr("fill", this._trendColor)+ .attr("pointer-events", "none");++ // Render tooltip. Optional, to match _hideTooltip: the brush drives this+ // method unconditionally, so a selectable chart with use_tooltip=false has+ // no tooltip node — but it still gets the guideline and circles above.+ this._d3Tooltip+ ?.html(this._tooltipTemplate(datum))+ .style("opacity", 1)+ .style("z-index", 999)+ .style("left", `${adjustedX}px`)+ .style("top", `${pageY - 10}px`);+ }++ _hideTooltip() {+ this._d3Group.selectAll(".guideline").remove();+ this._d3Group.selectAll(".data-point-circle").remove();+ this._d3Tooltip?.style("opacity", 0);+ this._setTrendlineSplitAt(1);+ }+_tooltipTemplate(datum) {return `<div class="text-xs text-secondary mb-1">diff --git a/app/models/period.rb b/app/models/period.rbindex b5a3c80b6b..087e7bc715 100644--- a/app/models/period.rb+++ b/app/models/period.rb@@ -147,11 +147,12 @@ class Periodendend- def initialize(start_date: nil, end_date: nil, key: nil, date_format: "%b %d, %Y")+ # NOTE: dates are rendered through `I18n.l`, so there is no `date_format:`+ # knob — the format follows the active locale, not the caller.+ def initialize(start_date: nil, end_date: nil, key: nil)@key = key@start_date = start_date@end_date = end_date- @date_format = date_formatvalidate!end@@ -199,17 +200,57 @@ class Perioddef comparison_labelif key- I18n.t("period.#{key}.comparison_label", default: key_metadata&.fetch(:comparison_label) || "#{start_date.strftime(@date_format)} to #{end_date.strftime(@date_format)}")+ I18n.t("period.#{key}.comparison_label", default: key_metadata&.fetch(:comparison_label) || custom_comparison_label)else- "#{start_date.strftime(@date_format)} to #{end_date.strftime(@date_format)}"+ custom_comparison_labelendend+ # Compact rendering of the actual dates, sized for a control that has to show+ # its own value (the period picker trigger). `label_short` answers "which+ # option is this" and degrades to a bare "Custom" for a keyless range, which+ # tells the reader nothing; `comparison_label` is the long form shown beside+ # trend values and is too wide for a button.+ #+ # The year is dropped while the whole range sits inside the current year — it+ # adds width without disambiguating anything.+ def label_range+ return label_short if start_date.nil? || end_date.nil?++ # `:short_with_year` matches `comparison_label`'s format so the trigger and+ # the range printed above the chart read as the same range.+ format = within_current_year? ? :short : :short_with_year++ I18n.t(+ "period.range",+ start_date: I18n.l(start_date, format: format),+ end_date: I18n.l(end_date, format: format),+ default: "%{start_date} – %{end_date}"+ )+ end+privatedef key_metadata@key_metadata ||= PERIODS[key]end+ # The year is dropped while the whole range sits inside the current year — it+ # adds width without disambiguating anything.+ def within_current_year?+ start_date.year == end_date.year && end_date.year == Date.current.year+ end++ # Both the separator and the date order are translatable: `to` is a word, and+ # locales disagree on where the day, month and year go. `I18n.l` resolves the+ # month name against the active locale, which `strftime` cannot do.+ def custom_comparison_label+ I18n.t(+ "period.custom.comparison_label",+ start_date: I18n.l(start_date, format: :short_with_year),+ end_date: I18n.l(end_date, format: :short_with_year)+ )+ end+def must_be_valid_date_rangereturn if start_date.nil? || end_date.nil?unless start_date.is_a?(Date) && end_date.is_a?(Date)diff --git a/app/views/pages/dashboard/_net_worth_chart.html.erb b/app/views/pages/dashboard/_net_worth_chart.html.erbindex e858f199af..693e4789dc 100644--- a/app/views/pages/dashboard/_net_worth_chart.html.erb+++ b/app/views/pages/dashboard/_net_worth_chart.html.erb@@ -21,7 +21,9 @@class="w-full min-h-52 privacy-sensitive"style="height: var(--dash-widget-h, 13rem);"data-controller="time-series-chart"- data-time-series-chart-data-value="<%= series.to_json %>"></div>+ data-time-series-chart-data-value="<%= series.to_json %>"+ data-time-series-chart-selectable-value="true"+ draggable="false"></div><% else %><div class="w-full h-full flex items-center justify-center"><p class="text-secondary text-sm"><%= t(".data_not_available") %></p>diff --git a/config/locales/defaults/en.yml b/config/locales/defaults/en.ymlindex 481258c453..44f417a5d1 100644--- a/config/locales/defaults/en.yml+++ b/config/locales/defaults/en.yml@@ -58,6 +58,7 @@ en:short: "%b %d"month_year: "%B %Y"short_month_year: "%b %Y"+ short_with_year: "%b %d, %Y"month_names:-- Januarydiff --git a/config/locales/defaults/fr.yml b/config/locales/defaults/fr.ymlindex 5b5147c946..7139b25803 100644--- a/config/locales/defaults/fr.yml+++ b/config/locales/defaults/fr.yml@@ -46,6 +46,7 @@ fr:month_year: "%B %Y"short: "%-d %b"short_month_year: "%b %Y"+ short_with_year: "%-d %b %Y"month_names:-- janvierdiff --git a/config/locales/models/period/en.yml b/config/locales/models/period/en.ymlindex 96e3bb21c3..a2e6f305d7 100644--- a/config/locales/models/period/en.yml+++ b/config/locales/models/period/en.yml@@ -52,3 +52,5 @@ en:custom:label_short: "Custom"label: "Custom Period"+ comparison_label: "%{start_date} to %{end_date}"+ range: "%{start_date} – %{end_date}"diff --git a/config/locales/models/period/fr.yml b/config/locales/models/period/fr.ymlindex 49ccdbbd18..001cb2da60 100644--- a/config/locales/models/period/fr.yml+++ b/config/locales/models/period/fr.yml@@ -18,6 +18,7 @@ fr:label: Année en courslabel_short: ACcustom:+ comparison_label: "%{start_date} au %{end_date}"label: Période personnaliséelabel_short: Personnalisélast_10_years:diff --git a/test/application_system_test_case.rb b/test/application_system_test_case.rbindex 57f01828c7..19fc5cceef 100644--- a/test/application_system_test_case.rb+++ b/test/application_system_test_case.rb@@ -86,13 +86,33 @@ class ApplicationSystemTestCase < ActionDispatch::SystemTestCasedef sign_in(user)visit new_session_pathwithin %(form[action='#{sessions_path}']) do- fill_in "Email", with: user.email- fill_in "Password", with: user_password_test- click_on "Log in"+ # Look fields up by type rather than label text: the labels are+ # translated, so a browser negotiating a non-English locale would+ # otherwise break every system test's login.+ find("input[type='email']").set(user.email)+ find("input[type='password']").set(user_password_test)+ find("[type='submit']").clickend- # Trigger Capybara's wait mechanism to avoid timing issues with logins- find("h1", text: "Welcome back, #{user.first_name}")+ # Trigger Capybara's wait mechanism to avoid timing issues with logins.+ # The greeting around it is translated; the user's own name is not.+ find("h1", text: user.first_name)+ end++ # Drags horizontally across the full width of `element`. Driven off the+ # element's own rendered width rather than fixed offsets — chart widths vary+ # with viewport and font metrics (they differ between local and CI headless+ # Chrome), and a start point outside the element never begins the gesture.+ def drag_across(element)+ inset = 20+ width = element.native.rect.width++ page.driver.browser.action+ .move_to(element.native, -(width / 2 - inset).round, 0)+ .click_and_hold+ .move_by((width - (2 * inset)).round, 0)+ .release+ .performenddef login_as(user)diff --git a/test/components/UI/period_picker_test.rb b/test/components/UI/period_picker_test.rbindex ee54db16e7..fe0dee217f 100644--- a/test/components/UI/period_picker_test.rb+++ b/test/components/UI/period_picker_test.rb@@ -55,4 +55,74 @@ class UI::PeriodPickerTest < ViewComponent::TestCaseassert_text Period.from_key("last_7_days").label_shortassert_equal 1, page.all("a[aria-checked='true']").sizeend++ test "trigger shows a custom range's dates rather than falling back to a preset label" do+ custom_period = Period.custom(start_date: 15.days.ago.to_date, end_date: Date.current)++ render_inline(UI::PeriodPicker.new(selected: custom_period, url: "/"))++ assert_selector "button[aria-label='Time period: #{custom_period.label_range}']"+ end++ test "a custom range adds a trailing checked row so the list still has one selection" do+ custom_period = Period.custom(start_date: 15.days.ago.to_date, end_date: Date.current)++ render_inline(UI::PeriodPicker.new(selected: custom_period, url: "/"))++ links = page.all("a[role='menuitemradio']")+ assert_equal Period.all.size + 1, links.size+ assert_equal custom_period.label_short, links.last.text.strip++ checked = page.all("a[role='menuitemradio'][aria-checked='true']")+ assert_equal 1, checked.size+ # Round-trips the active range, so selecting it re-applies rather than clears.+ assert_match(/start_date=#{custom_period.start_date}/, checked.first[:href])+ assert_match(/end_date=#{custom_period.end_date}/, checked.first[:href])+ end++ test "a preset selection renders no custom row" do+ render_inline(UI::PeriodPicker.new(selected: Period.last_30_days, url: "/"))++ assert_equal Period.all.size, page.all("a[role='menuitemradio']").size+ end++ test "framed options advance the URL so a preset pick clears a stale custom range" do+ render_inline(UI::PeriodPicker.new(selected: Period.last_30_days, url: "/", frame: "dashboard_sections"))++ links = page.all("a[role='menuitemradio'][aria-checked='false']")+ assert links.any?+ links.each { |link| assert_equal "advance", link["data-turbo-action"] }+ end++ test "options advance the URL without an explicit frame too" do+ # The account page renders its picker inside the account's own container+ # frame, so those links are frame navigations as well and need the same+ # address-bar update.+ render_inline(UI::PeriodPicker.new(selected: Period.last_30_days, url: "/"))++ links = page.all("a[role='menuitemradio'][aria-checked='false']")+ assert links.any?+ links.each { |link| assert_equal "advance", link["data-turbo-action"] }+ end++ test "re-picking the checked preset replaces instead of stacking a history entry" do+ render_inline(UI::PeriodPicker.new(selected: Period.last_30_days, url: "/", frame: "dashboard_sections"))++ checked = page.all("a[role='menuitemradio'][aria-checked='true']")+ assert_equal 1, checked.size+ # Selecting the active row is a no-op; advancing would make Back a no-op too.+ assert_equal "replace", checked.first["data-turbo-action"]+ end++ test "the custom row replaces so re-selecting the active range costs no history" do+ custom_period = Period.custom(start_date: 15.days.ago.to_date, end_date: Date.current)++ render_inline(UI::PeriodPicker.new(selected: custom_period, url: "/"))++ links = page.all("a[role='menuitemradio']")+ assert_equal "replace", links.last["data-turbo-action"]+ # Leaving the custom range for a preset is a real change, so it still advances+ # and stays reachable with Back — the drag-select that set it advanced too.+ assert_equal "advance", links.first["data-turbo-action"]+ endenddiff --git a/test/controllers/accounts_controller_test.rb b/test/controllers/accounts_controller_test.rbindex 44fa65cc51..9831291baf 100644--- a/test/controllers/accounts_controller_test.rb+++ b/test/controllers/accounts_controller_test.rb@@ -105,6 +105,26 @@ class AccountsControllerTest < ActionDispatch::IntegrationTestassert_response :successend+ test "show renders the balance chart as drag-selectable for a custom date range" do+ get account_url(@account)++ assert_response :success+ assert_select "#lineChart[data-time-series-chart-selectable-value='true']"+ end++ test "show honors a custom start_date/end_date range" do+ start_date = 15.days.ago.to_date+ end_date = Date.current++ get account_url(@account), params: { start_date: start_date.to_s, end_date: end_date.to_s }++ assert_response :success+ # If the params were ignored, the user's default preset would render as the+ # checked option instead of the custom row.+ assert_select "a[role='menuitemradio'][aria-checked='true'][href*='period=']", count: 0+ assert_select "a[role='menuitemradio'][aria-checked='true'][href*='start_date=']", count: 1+ end+test "sync all requests fresh Plaid transactions before syncing the family" dosequence = sequence("manual sync all")Family.any_instancediff --git a/test/controllers/concerns/periodable_test.rb b/test/controllers/concerns/periodable_test.rbnew file mode 100644index 0000000000..a585817a50--- /dev/null+++ b/test/controllers/concerns/periodable_test.rb@@ -0,0 +1,58 @@+require "test_helper"++class PeriodableTest < ActionDispatch::IntegrationTest+ setup do+ sign_in @user = users(:family_admin)++ @start_date = 15.days.ago.to_date+ @end_date = 5.days.ago.to_date+ # The picker trigger shows the range's own dates, so derive the expected+ # label instead of hardcoding a format that shifts at the year boundary.+ @custom_label = Period.custom(start_date: @start_date, end_date: @end_date).label_range+ end++ test "start_date and end_date params build a custom period" do+ get root_path, params: { start_date: @start_date.to_s, end_date: @end_date.to_s }++ assert_response :success+ assert_select "button[aria-label='Time period: #{@custom_label}']"+ end++ test "invalid start_date or end_date falls back to last 30 days" do+ get root_path, params: { start_date: "not-a-date", end_date: @end_date.to_s }++ assert_response :success+ assert_select "button[aria-label='Time period: 30D']"+ end++ test "start_date and end_date range where start is after end falls back to last 30 days" do+ get root_path, params: { start_date: @end_date.to_s, end_date: @start_date.to_s }++ assert_response :success+ assert_select "button[aria-label='Time period: 30D']"+ end++ test "start_date without end_date is ignored and the user's default period wins" do+ @user.update!(default_period: "last_7_days")++ get root_path, params: { start_date: @start_date.to_s }++ assert_response :success+ assert_select "button[aria-label='Time period: #{Period.last_7_days.label_short}']"+ end++ test "start_date and end_date do not persist as the user's default period" do+ @user.update!(default_period: "last_7_days")++ get root_path, params: { start_date: @start_date.to_s, end_date: @end_date.to_s }++ assert_equal "last_7_days", @user.reload.default_period+ end++ test "start_date and end_date take precedence over a period param" do+ get root_path, params: { period: "last_7_days", start_date: @start_date.to_s, end_date: @end_date.to_s }++ assert_response :success+ assert_select "button[aria-label='Time period: #{@custom_label}']"+ end+enddiff --git a/test/controllers/pages_controller_test.rb b/test/controllers/pages_controller_test.rbindex ebad8a535f..137fcbd506 100644--- a/test/controllers/pages_controller_test.rb+++ b/test/controllers/pages_controller_test.rb@@ -14,6 +14,13 @@ class PagesControllerTest < ActionDispatch::IntegrationTestassert_response :okend+ test "dashboard renders the net worth chart as drag-selectable, opting it out of card drag-and-drop" do+ get root_path++ assert_response :ok+ assert_select "#netWorthChart[data-time-series-chart-selectable-value='true'][draggable='false']"+ end+test "inactive user's existing session is revoked" dosession_record = @user.sessions.order(:created_at).last@user.update_column(:active, false)diff --git a/test/models/period_test.rb b/test/models/period_test.rbindex 33e01bb02f..ad4dd14229 100644--- a/test/models/period_test.rb+++ b/test/models/period_test.rb@@ -45,6 +45,50 @@ class PeriodTest < ActiveSupport::TestCaseassert_equal "Custom Period", period.labelend+ test "label_range omits the year for a range inside the current year" do+ period = Period.custom(+ start_date: Date.new(Date.current.year, 6, 1),+ end_date: Date.new(Date.current.year, 6, 15)+ )++ assert_equal "Jun 01 – Jun 15", period.label_range+ end++ test "label_range includes the year when the range leaves the current year" do+ period = Period.custom(start_date: Date.new(2020, 12, 20), end_date: Date.new(2021, 1, 5))++ assert_equal "Dec 20, 2020 – Jan 05, 2021", period.label_range+ end++ test "comparison_label spells out a custom range" do+ period = Period.custom(start_date: Date.new(2020, 12, 20), end_date: Date.new(2021, 1, 5))++ assert_equal "Dec 20, 2020 to Jan 05, 2021", period.comparison_label+ end++ # Both of these read the month name out of the locale rather than out of a+ # strftime format string, so they would regress to English month abbreviations+ # (and an English "to") the moment either one goes back to `strftime`.+ test "label_range and comparison_label localize month names and date order" do+ period = Period.custom(start_date: Date.new(2020, 12, 20), end_date: Date.new(2021, 1, 5))++ I18n.with_locale(:fr) do+ assert_equal "20 déc. 2020 – 5 jan. 2021", period.label_range+ assert_equal "20 déc. 2020 au 5 jan. 2021", period.comparison_label+ end+ end++ test "label_range localizes the year-less range too" do+ period = Period.custom(+ start_date: Date.new(Date.current.year, 6, 1),+ end_date: Date.new(Date.current.year, 6, 15)+ )++ I18n.with_locale(:fr) do+ assert_equal "1 juin – 15 juin", period.label_range+ end+ end+test "all_time period can be created" doperiod = Period.from_key("all_time")assert_equal "all_time", period.keydiff --git a/test/system/account_chart_drag_select_test.rb b/test/system/account_chart_drag_select_test.rbnew file mode 100644index 0000000000..dd03cf3718--- /dev/null+++ b/test/system/account_chart_drag_select_test.rb@@ -0,0 +1,19 @@+require "application_system_test_case"++class AccountChartDragSelectTest < ApplicationSystemTestCase+ setup do+ @user = users(:family_admin)+ @account = accounts(:depository)+ end++ test "dragging across the balance chart navigates to the dragged date range" do+ sign_in @user++ visit account_url(@account)+ assert_text @account.name++ drag_across find("#lineChart .drag-select-brush .overlay", visible: :all)++ assert_current_path(%r{/accounts/#{@account.id}\?.*start_date=.*end_date=})+ end+enddiff --git a/test/system/dashboard_chart_drag_select_test.rb b/test/system/dashboard_chart_drag_select_test.rbnew file mode 100644index 0000000000..cdf94a6697--- /dev/null+++ b/test/system/dashboard_chart_drag_select_test.rb@@ -0,0 +1,29 @@+require "application_system_test_case"++class DashboardChartDragSelectTest < ApplicationSystemTestCase+ setup do+ @user = users(:family_admin)+ end++ test "dragging across the net worth chart navigates to the dragged date range instead of reordering the card" do+ sign_in @user++ original_order = page.all("[data-section-key]").map { |el| el["data-section-key"] }++ # The net worth chart sits inside a `<section draggable="true">` used by+ # dashboard-sortable for card reordering. Without an explicit+ # `draggable="false"` on the chart container, this same gesture would be+ # hijacked by the native HTML5 drag-and-drop instead of the chart's brush.+ drag_across find("#netWorthChart .drag-select-brush .overlay", visible: :all)++ assert_current_path(%r{/\?.*start_date=.*end_date=})++ # Some sections (e.g. the outflows donut) hide themselves when the+ # selected range has no matching data — that's expected, so only assert+ # that whatever sections persist keep their relative order (i.e. nothing+ # got dragged to a new position).+ new_order = page.all("[data-section-key]").map { |el| el["data-section-key"] }+ common_keys = original_order & new_order+ assert_equal common_keys, new_order & common_keys+ end+end