A platform for community discussion. Free, open, simple.
UX: Anchor dashboard date range picker on the start month (#40395)
Alan Guo Xiang Tan9be3fabd4050
diff --git a/frontend/discourse/admin/components/dashboard/date-range-picker.gjs b/frontend/discourse/admin/components/dashboard/date-range-picker.gjsindex 13e5a6be159..88bdcab369b 100644--- a/frontend/discourse/admin/components/dashboard/date-range-picker.gjs+++ b/frontend/discourse/admin/components/dashboard/date-range-picker.gjs@@ -1,101 +1,23 @@import Component from "@glimmer/component";import { tracked } from "@glimmer/tracking";-import { fn, get } from "@ember/helper";+import { fn } from "@ember/helper";import { on } from "@ember/modifier";import { action } from "@ember/object";import { service } from "@ember/service";import { modifier } from "ember-modifier";-import { eq } from "discourse/truth-helpers";import DButton from "discourse/ui-kit/d-button";import dConcatClass from "discourse/ui-kit/helpers/d-concat-class";import dIcon from "discourse/ui-kit/helpers/d-icon";import { i18n } from "discourse-i18n";-export const PRESET_LAST_7_DAYS = "last_7_days";-export const PRESET_LAST_30_DAYS = "last_30_days";-export const PRESET_LAST_3_MONTHS = "last_3_months";-export const PRESET_LAST_6_MONTHS = "last_6_months";-export const PRESET_LAST_YEAR = "last_year";--export const ALL_PRESETS = [- PRESET_LAST_7_DAYS,- PRESET_LAST_30_DAYS,- PRESET_LAST_3_MONTHS,- PRESET_LAST_6_MONTHS,- PRESET_LAST_YEAR,-];--const PRESET_RANGES = {- [PRESET_LAST_7_DAYS]: (today) => ({- from: today.clone().subtract(6, "days"),- to: today.clone(),- }),- [PRESET_LAST_30_DAYS]: (today) => ({- from: today.clone().subtract(29, "days"),- to: today.clone(),- }),- [PRESET_LAST_3_MONTHS]: (today) => ({- from: today.clone().subtract(3, "months").add(1, "day"),- to: today.clone(),- }),- [PRESET_LAST_6_MONTHS]: (today) => ({- from: today.clone().subtract(6, "months").add(1, "day"),- to: today.clone(),- }),- [PRESET_LAST_YEAR]: (today) => ({- from: today.clone().subtract(1, "year").add(1, "day"),- to: today.clone(),- }),-};--const PRESET_LABEL_KEYS = {- [PRESET_LAST_7_DAYS]: "date_range_picker.presets.last_7_days",- [PRESET_LAST_30_DAYS]: "date_range_picker.presets.last_30_days",- [PRESET_LAST_3_MONTHS]: "date_range_picker.presets.last_3_months",- [PRESET_LAST_6_MONTHS]: "date_range_picker.presets.last_6_months",- [PRESET_LAST_YEAR]: "date_range_picker.presets.last_year",-};--export function presetRange(preset, today = moment().startOf("day")) {- return PRESET_RANGES[preset](today.clone().startOf("day"));-}--export function formatRange(from, to) {- if (!from || !to) {- return "";- }- const fromM = moment(from);- const toM = moment(to);- if (fromM.isSame(toM, "day")) {- return fromM.format("ll");- }- return `${fromM.format("ll")} – ${toM.format("ll")}`;-}-function toDayMoment(value) {return value ? moment(value).startOf("day") : null;}-function fmt(value, pattern) {+function formatDate(value, pattern) {return value ? moment(value).format(pattern) : "";}-function ymd(value) {- return value ? moment(value).format("YYYY-MM-DD") : null;-}--export function matchingPreset(from, to, presets, today = moment()) {- const fromYmd = ymd(from);- const toYmd = ymd(to);- const todayStart = today.clone().startOf("day");- return (- presets.find((preset) => {- const range = PRESET_RANGES[preset](todayStart);- return ymd(range.from) === fromYmd && ymd(range.to) === toYmd;- }) ?? null- );-}-export default class DashboardDateRangePicker extends Component {@service site;@@ -124,8 +46,12 @@ export default class DashboardDateRangePicker extends Component {activeRect.left - railRect.left - (railRect.width - activeRect.width) / 2;});- get presets() {- return this.args.presets ?? ALL_PRESETS;+ get presetItems() {+ const activeId = this.committed ? (this.args.activePreset ?? null) : null;+ return (this.args.presets ?? []).map((preset) => ({+ ...preset,+ active: preset.id === activeId,+ }));}get maxDate() {@@ -144,20 +70,16 @@ export default class DashboardDateRangePicker extends Component {return this.committed ? toDayMoment(this.args.to) : this.pendingEnd;}- get activePreset() {- if (!this.committed) {- return null;- }- return matchingPreset(this.args.from, this.args.to, this.presets);- }-get applyDisabled() {if (!this.pendingStart || !this.pendingEnd) {return true;}+ if (!this.args.from || !this.args.to) {+ return false;+ }return (- ymd(this.pendingStart) === ymd(this.args.from) &&- ymd(this.pendingEnd) === ymd(this.args.to)+ this.pendingStart.isSame(toDayMoment(this.args.from), "day") &&+ this.pendingEnd.isSame(toDayMoment(this.args.to), "day"));}@@ -165,44 +87,15 @@ export default class DashboardDateRangePicker extends Component {return !this.site.mobileView;}- get monthSpanCount() {- const start = toDayMoment(this.args.from);- const end = toDayMoment(this.args.to);- if (!start || !end) {- return 0;- }- return end- .clone()- .startOf("month")- .diff(start.clone().startOf("month"), "months");- }-- get useLongRangeLayout() {- return (- !this.viewStartMonthOverride &&- this.showTwoMonths &&- this.monthSpanCount > 1- );- }-get viewStartMonth() {if (this.viewStartMonthOverride) {return this.viewStartMonthOverride;}- const anchor = toDayMoment(this.args.to) ?? moment().startOf("day");- if (this.showTwoMonths) {- return anchor.clone().subtract(1, "month").startOf("month");- }+ const anchor = toDayMoment(this.args.from) ?? moment().startOf("day");return anchor.clone().startOf("month");}get visibleMonths() {- if (this.useLongRangeLayout) {- return [- toDayMoment(this.args.from).clone().startOf("month"),- toDayMoment(this.args.to).clone().startOf("month"),- ];- }const months = [this.viewStartMonth.clone()];if (this.showTwoMonths) {months.push(this.viewStartMonth.clone().add(1, "month"));@@ -338,12 +231,7 @@ export default class DashboardDateRangePicker extends Component {@actionselectPreset(preset) {- const { from, to } = presetRange(preset);- this.args.onApply?.({- preset,- from: from.toDate(),- to: to.toDate(),- });+ this.args.onApply?.({ preset: preset.id });}@action@@ -510,6 +398,27 @@ export default class DashboardDateRangePicker extends Component {this.focusedDay = parsed.clone();}+ @action+ focusStartInput() {+ const start = this.currentStart;+ if (!start) {+ return;+ }+ this.viewStartMonthOverride = start.clone().startOf("month");+ }++ @action+ focusEndInput() {+ const end = this.currentEnd;+ if (!end) {+ return;+ }+ const month = end.clone().startOf("month");+ this.viewStartMonthOverride = this.showTwoMonths+ ? month.clone().subtract(1, "month")+ : month;+ }+@actioncommitInputOnEnter(event) {if (event.key === "Enter") {@@ -526,17 +435,17 @@ export default class DashboardDateRangePicker extends Component {aria-label={{i18n "date_range_picker.presets.label"}}{{this.scrollActivePresetIntoView}}>- {{#each this.presets as |preset|}}+ {{#each this.presetItems as |preset|}}<buttontype="button"class={{dConcatClass"d-date-range-picker__preset"- (if (eq this.activePreset preset) "is-active")+ (if preset.active "is-active")}}- aria-current={{if (eq this.activePreset preset) "true"}}+ aria-current={{if preset.active "true"}}{{on "click" (fn this.selectPreset preset)}}>- {{i18n (get PRESET_LABEL_KEYS preset)}}+ {{preset.label}}</button>{{/each}}</div>@@ -559,7 +468,7 @@ export default class DashboardDateRangePicker extends Component {{{#each this.visibleMonths as |month|}}<div class="d-date-range-picker__month"><div class="d-date-range-picker__month-header">- {{fmt month "MMMM YYYY"}}+ {{formatDate month "MMMM YYYY"}}</div><div class="d-date-range-picker__weekdays" aria-hidden="true">{{#each this.weekdayLabels as |dow|}}@@ -569,7 +478,7 @@ export default class DashboardDateRangePicker extends Component {<divclass="d-date-range-picker__grid"role="grid"- aria-label={{fmt month "MMMM YYYY"}}+ aria-label={{formatDate month "MMMM YYYY"}}{{on "keydown" this.handleKeyDown}}>{{#each (this.weeksFor month) as |week|}}@@ -585,7 +494,7 @@ export default class DashboardDateRangePicker extends Component {tabindex={{if (this.isFocusedDay day) "0" "-1"}}aria-selected={{this.isAriaSelected day}}aria-disabled={{if (this.isDisabledDay day) "true"}}- aria-label={{fmt day "LL"}}+ aria-label={{formatDate day "LL"}}disabled={{this.isDisabledDay day}}{{this.focusDay(this.shouldProgrammaticallyFocusDay day)@@ -593,7 +502,7 @@ export default class DashboardDateRangePicker extends Component {{{on "click" (fn this.clickDay day)}}{{on "mouseenter" (fn this.hoverDay day)}}>- {{fmt day "D"}}+ {{formatDate day "D"}}</button>{{/if}}{{/each}}@@ -623,6 +532,7 @@ export default class DashboardDateRangePicker extends Component {placeholder={{i18n "date_range_picker.date_placeholder"}}aria-label={{i18n "date_range_picker.start_date"}}value={{this.startInputValue}}+ {{on "focus" this.focusStartInput}}{{on "change" this.commitStartInput}}{{on "keydown" this.commitInputOnEnter}}/>@@ -634,6 +544,7 @@ export default class DashboardDateRangePicker extends Component {placeholder={{i18n "date_range_picker.date_placeholder"}}aria-label={{i18n "date_range_picker.end_date"}}value={{this.endInputValue}}+ {{on "focus" this.focusEndInput}}{{on "change" this.commitEndInput}}{{on "keydown" this.commitInputOnEnter}}/>diff --git a/frontend/discourse/admin/components/dashboard/date-range.gjs b/frontend/discourse/admin/components/dashboard/date-range.gjsindex 072f6023587..2ba5232c9ea 100644--- a/frontend/discourse/admin/components/dashboard/date-range.gjs+++ b/frontend/discourse/admin/components/dashboard/date-range.gjs@@ -1,67 +1,44 @@import Component from "@glimmer/component";import { fn } from "@ember/helper";import { action } from "@ember/object";-import DashboardDateRangePicker, {+import DashboardDateRangePicker from "discourse/admin/components/dashboard/date-range-picker";+import {ALL_PRESETS,+ DEFAULT_PERIOD,formatRange,- PRESET_LAST_3_MONTHS,- PRESET_LAST_7_DAYS,- PRESET_LAST_30_DAYS,-} from "discourse/admin/components/dashboard/date-range-picker";+ PERIOD_CUSTOM,+ PRESET_LABEL_KEYS,+} from "discourse/admin/lib/dashboard-date-range";import DMenu from "discourse/float-kit/components/d-menu";import dIcon from "discourse/ui-kit/helpers/d-icon";import { i18n } from "discourse-i18n";-export const PERIOD_LAST_7_DAYS = PRESET_LAST_7_DAYS;-export const PERIOD_LAST_30_DAYS = PRESET_LAST_30_DAYS;-export const PERIOD_LAST_3_MONTHS = PRESET_LAST_3_MONTHS;-export const PERIOD_CUSTOM = "custom";--export const DEFAULT_PERIOD = PERIOD_LAST_30_DAYS;--export const VALID_PERIODS = [- PERIOD_LAST_7_DAYS,- PERIOD_LAST_30_DAYS,- PERIOD_LAST_3_MONTHS,- PERIOD_CUSTOM,-];--const TOP_TIER_PRESET_I18N_KEYS = {- [PERIOD_LAST_7_DAYS]: "date_range_picker.presets.last_7_days",- [PERIOD_LAST_30_DAYS]: "date_range_picker.presets.last_30_days",- [PERIOD_LAST_3_MONTHS]: "date_range_picker.presets.last_3_months",-};--const TOP_TIER_PRESETS = new Set(Object.keys(TOP_TIER_PRESET_I18N_KEYS));--export function calculatePresetStartDate(period) {- const today = moment();- switch (period) {- case PERIOD_LAST_7_DAYS:- return today.subtract(6, "days").startOf("day").toDate();- case PERIOD_LAST_3_MONTHS:- return today.subtract(3, "months").add(1, "day").startOf("day").toDate();- case PERIOD_LAST_30_DAYS:- default:- return today.subtract(29, "days").startOf("day").toDate();- }-}-export default class DashboardDateRange extends Component {get triggerLabel() {const { period, startDate, endDate } = this.args;- if (TOP_TIER_PRESET_I18N_KEYS[period]) {- return i18n(TOP_TIER_PRESET_I18N_KEYS[period]);+ if (PRESET_LABEL_KEYS[period]) {+ return i18n(PRESET_LABEL_KEYS[period]);}if (period === PERIOD_CUSTOM && startDate && endDate) {return formatRange(startDate, endDate);}- return i18n(TOP_TIER_PRESET_I18N_KEYS[DEFAULT_PERIOD]);+ return i18n(PRESET_LABEL_KEYS[DEFAULT_PERIOD]);+ }++ get presets() {+ return ALL_PRESETS.map((id) => ({+ id,+ label: i18n(PRESET_LABEL_KEYS[id]),+ }));+ }++ get activePreset() {+ return PRESET_LABEL_KEYS[this.args.period] ? this.args.period : null;}@actionhandleApply(close, { preset, from, to }) {- if (preset && TOP_TIER_PRESETS.has(preset)) {+ if (preset) {this.args.setPeriod?.(preset);} else {this.args.setCustomDateRange?.(from, to);@@ -86,7 +63,8 @@ export default class DashboardDateRange extends Component {<DashboardDateRangePicker@from={{@startDate}}@to={{@endDate}}- @presets={{ALL_PRESETS}}+ @presets={{this.presets}}+ @activePreset={{this.activePreset}}@onApply={{fn this.handleApply args.close}}@onCancel={{args.close}}/>diff --git a/frontend/discourse/admin/controllers/admin/dashboard.js b/frontend/discourse/admin/controllers/admin/dashboard.jsindex 69cdf749b84..6c9682739cd 100644--- a/frontend/discourse/admin/controllers/admin/dashboard.js+++ b/frontend/discourse/admin/controllers/admin/dashboard.js@@ -7,7 +7,7 @@ import {DEFAULT_PERIOD,PERIOD_CUSTOM,VALID_PERIODS,-} from "discourse/admin/components/dashboard/date-range";+} from "discourse/admin/lib/dashboard-date-range";import AdminDashboard from "discourse/admin/models/admin-dashboard";import VersionCheck from "discourse/admin/models/version-check";import { ajax } from "discourse/lib/ajax";diff --git a/frontend/discourse/admin/lib/dashboard-date-range.js b/frontend/discourse/admin/lib/dashboard-date-range.jsnew file mode 100644index 00000000000..2cf12d238d9--- /dev/null+++ b/frontend/discourse/admin/lib/dashboard-date-range.js@@ -0,0 +1,54 @@+export const PERIOD_LAST_7_DAYS = "last_7_days";+export const PERIOD_LAST_30_DAYS = "last_30_days";+export const PERIOD_LAST_3_MONTHS = "last_3_months";+export const PERIOD_LAST_6_MONTHS = "last_6_months";+export const PERIOD_LAST_YEAR = "last_year";+export const PERIOD_CUSTOM = "custom";++export const DEFAULT_PERIOD = PERIOD_LAST_30_DAYS;++export const ALL_PRESETS = [+ PERIOD_LAST_7_DAYS,+ PERIOD_LAST_30_DAYS,+ PERIOD_LAST_3_MONTHS,+ PERIOD_LAST_6_MONTHS,+ PERIOD_LAST_YEAR,+];++export const VALID_PERIODS = [...ALL_PRESETS, PERIOD_CUSTOM];++export const PRESET_LABEL_KEYS = {+ [PERIOD_LAST_7_DAYS]: "date_range_picker.presets.last_7_days",+ [PERIOD_LAST_30_DAYS]: "date_range_picker.presets.last_30_days",+ [PERIOD_LAST_3_MONTHS]: "date_range_picker.presets.last_3_months",+ [PERIOD_LAST_6_MONTHS]: "date_range_picker.presets.last_6_months",+ [PERIOD_LAST_YEAR]: "date_range_picker.presets.last_year",+};++const PRESET_RANGES = {+ [PERIOD_LAST_7_DAYS]: (today) => today.clone().subtract(6, "days"),+ [PERIOD_LAST_30_DAYS]: (today) => today.clone().subtract(29, "days"),+ [PERIOD_LAST_3_MONTHS]: (today) =>+ today.clone().subtract(3, "months").add(1, "day"),+ [PERIOD_LAST_6_MONTHS]: (today) =>+ today.clone().subtract(6, "months").add(1, "day"),+ [PERIOD_LAST_YEAR]: (today) =>+ today.clone().subtract(1, "year").add(1, "day"),+};++export function calculatePresetStartDate(period) {+ const startFor = PRESET_RANGES[period] ?? PRESET_RANGES[DEFAULT_PERIOD];+ return startFor(moment().startOf("day")).toDate();+}++export function formatRange(from, to) {+ if (!from || !to) {+ return "";+ }+ const fromM = moment(from);+ const toM = moment(to);+ if (fromM.isSame(toM, "day")) {+ return fromM.format("ll");+ }+ return `${fromM.format("ll")} – ${toM.format("ll")}`;+}diff --git a/frontend/discourse/tests/integration/components/dashboard/date-range-picker-test.gjs b/frontend/discourse/tests/integration/components/dashboard/date-range-picker-test.gjsindex 66f190ead4d..a2b92f068fd 100644--- a/frontend/discourse/tests/integration/components/dashboard/date-range-picker-test.gjs+++ b/frontend/discourse/tests/integration/components/dashboard/date-range-picker-test.gjs@@ -1,45 +1,32 @@-import { tracked } from "@glimmer/tracking";-import { click, fillIn, render } from "@ember/test-helpers";+import { click, fillIn, focus, render } from "@ember/test-helpers";import { module, test } from "qunit";-import DashboardDateRangePicker, {- ALL_PRESETS,- formatRange,- matchingPreset,- PRESET_LAST_6_MONTHS,- PRESET_LAST_7_DAYS,- PRESET_LAST_30_DAYS,- presetRange,-} from "discourse/admin/components/dashboard/date-range-picker";+import DashboardDateRangePicker from "discourse/admin/components/dashboard/date-range-picker";+import { forceMobile } from "discourse/lib/mobile";import { setupRenderingTest } from "discourse/tests/helpers/component-test";import { fakeTime } from "discourse/tests/helpers/qunit-helpers";const TODAY = "2026-05-26 12:00";-class RangeState {- @tracked from;- @tracked to;- @tracked applied = [];- @tracked cancelled = 0;-- apply = (payload) => {- this.applied = [...this.applied, payload];- };-- cancel = () => {- this.cancelled++;- };-- constructor(from, to) {- this.from = from;- this.to = to;- }-}+const START_DATE_INPUT = ".d-date-range-picker__input[aria-label='Start date']";+const END_DATE_INPUT = ".d-date-range-picker__input[aria-label='End date']";function dayButton(dateString) {const m = moment(dateString);return `.d-date-range-picker__day[aria-label="${m.format("LL")}"]:not(.--muted)`;}+function monthHeaders() {+ return [+ ...document.querySelectorAll(".d-date-range-picker__month-header"),+ ].map((el) => el.textContent.trim());+}++function activePreset() {+ return [...document.querySelectorAll(".d-date-range-picker__preset")].find(+ (el) => el.classList.contains("is-active")+ );+}+module("Integration | Component | Dashboard | DateRangePicker",function (hooks) {@@ -55,98 +42,78 @@ module(clock?.restore();});- test("highlights the active period on the calendar and in the sidebar", async function (assert) {- const { from, to } = presetRange(PRESET_LAST_30_DAYS);- const state = new RangeState(from.toDate(), to.toDate());+ test("highlights the start and end days of the active range", async function (assert) {+ const from = moment("2026-04-27");+ const to = moment("2026-05-26");await render(<template>- <DashboardDateRangePicker- @from={{state.from}}- @to={{state.to}}- @presets={{ALL_PRESETS}}- @onApply={{state.apply}}- @onCancel={{state.cancel}}- />+ <DashboardDateRangePicker @from={{from}} @to={{to}} /></template>);assert.dom(dayButton(from))- .hasClass(- "--start",- "the start day of the active period is highlighted as the start"- );+ .hasClass("--start", "the start day is highlighted as the start");assert.dom(dayButton(to))- .hasClass(- "--end",- "the end day of the active period is highlighted as the end"- );-- const activePreset = [- ...document.querySelectorAll(".d-date-range-picker__preset"),- ].find((el) => el.classList.contains("is-active"));- assert.strictEqual(- activePreset?.textContent.trim(),- "Last 30 days",- "the sidebar preset matching the active range is highlighted"- );+ .hasClass("--end", "the end day is highlighted as the end");});- test("clicking a sidebar preset emits onApply with the preset and its range", async function (assert) {- const { from, to } = presetRange(PRESET_LAST_30_DAYS);- const state = new RangeState(from.toDate(), to.toDate());+ test("marks the active preset in the sidebar", async function (assert) {+ const presets = [+ { id: "last_7_days", label: "Last 7 days" },+ { id: "last_30_days", label: "Last 30 days" },+ ];await render(<template><DashboardDateRangePicker- @from={{state.from}}- @to={{state.to}}- @presets={{ALL_PRESETS}}- @onApply={{state.apply}}- @onCancel={{state.cancel}}+ @presets={{presets}}+ @activePreset="last_30_days"/></template>);- const sixMonthsPreset = [- ...document.querySelectorAll(".d-date-range-picker__preset"),- ].find((el) => el.textContent.trim() === "Last 6 months");- await click(sixMonthsPreset);-- assert.strictEqual(state.applied.length, 1, "onApply is called once");- const payload = state.applied[0];assert.strictEqual(- payload.preset,- PRESET_LAST_6_MONTHS,- "the preset constant is emitted"+ activePreset()?.textContent.trim(),+ "Last 30 days",+ "the preset matching the active range is highlighted");- const expected = presetRange(PRESET_LAST_6_MONTHS);- assert.strictEqual(- moment(payload.from).format("YYYY-MM-DD"),- expected.from.format("YYYY-MM-DD"),- "the emitted from matches the preset start"+ });++ test("clicking a preset emits onApply with its id", async function (assert) {+ const presets = [{ id: "last_6_months", label: "Last 6 months" }];+ const applied = [];+ const onApply = (payload) => applied.push(payload);++ await render(+ <template>+ <DashboardDateRangePicker @presets={{presets}} @onApply={{onApply}} />+ </template>);- assert.strictEqual(- moment(payload.to).format("YYYY-MM-DD"),- expected.to.format("YYYY-MM-DD"),- "the emitted to matches the preset end"++ await click(".d-date-range-picker__preset");++ assert.deepEqual(+ applied,+ [{ preset: "last_6_months" }],+ "the clicked preset's id is emitted, leaving the range for the parent");});test("hand-picking a range: click start, click end, Apply commits", async function (assert) {- const { from, to } = presetRange(PRESET_LAST_30_DAYS);- const state = new RangeState(from.toDate(), to.toDate());+ const from = moment("2026-04-27");+ const to = moment("2026-05-26");+ const applied = [];+ const onApply = (payload) => applied.push(payload);await render(<template><DashboardDateRangePicker- @from={{state.from}}- @to={{state.to}}- @presets={{ALL_PRESETS}}- @onApply={{state.apply}}- @onCancel={{state.cancel}}+ @from={{from}}+ @to={{to}}+ @onApply={{onApply}}/></template>);@@ -190,8 +157,8 @@ module(await click(".d-date-range-picker__apply");- assert.strictEqual(state.applied.length, 1, "onApply is called once");- const payload = state.applied[0];+ assert.strictEqual(applied.length, 1, "onApply is called once");+ const payload = applied[0];assert.strictEqual(payload.preset, null, "no preset is emitted");assert.strictEqual(moment(payload.from).format("YYYY-MM-DD"),@@ -206,29 +173,23 @@ module(});test("typing dates in YYYY/MM/DD into the inputs updates the selection", async function (assert) {- const { from, to } = presetRange(PRESET_LAST_30_DAYS);- const state = new RangeState(from.toDate(), to.toDate());+ const from = moment("2026-04-27");+ const to = moment("2026-05-26");+ const applied = [];+ const onApply = (payload) => applied.push(payload);await render(<template><DashboardDateRangePicker- @from={{state.from}}- @to={{state.to}}- @presets={{ALL_PRESETS}}- @onApply={{state.apply}}- @onCancel={{state.cancel}}+ @from={{from}}+ @to={{to}}+ @onApply={{onApply}}/></template>);- await fillIn(- ".d-date-range-picker__input[aria-label='Start date']",- "2026/05/02"- );- await fillIn(- ".d-date-range-picker__input[aria-label='End date']",- "2026/05/18"- );+ await fillIn(START_DATE_INPUT, "2026/05/02");+ await fillIn(END_DATE_INPUT, "2026/05/18");assert.dom(dayButton("2026-05-02"))@@ -240,7 +201,7 @@ module(await click(".d-date-range-picker__apply");- const payload = state.applied[0];+ const payload = applied[0];assert.strictEqual(moment(payload.from).format("YYYY-MM-DD"),"2026-05-02"@@ -249,28 +210,19 @@ module(});test("an invalid typed date reverts the input to the current selection", async function (assert) {- const { from, to } = presetRange(PRESET_LAST_30_DAYS);- const state = new RangeState(from.toDate(), to.toDate());+ const from = moment("2026-04-27");+ const to = moment("2026-05-26");await render(<template>- <DashboardDateRangePicker- @from={{state.from}}- @to={{state.to}}- @presets={{ALL_PRESETS}}- @onApply={{state.apply}}- @onCancel={{state.cancel}}- />+ <DashboardDateRangePicker @from={{from}} @to={{to}} /></template>);- await fillIn(- ".d-date-range-picker__input[aria-label='Start date']",- "not-a-date"- );+ await fillIn(START_DATE_INPUT, "not-a-date");assert- .dom(".d-date-range-picker__input[aria-label='Start date']")+ .dom(START_DATE_INPUT).hasValue(moment(from).format("YYYY/MM/DD"),"the field reverts to the active start when the input is invalid"@@ -278,18 +230,12 @@ module(});test("clicking a date earlier than the pending start re-anchors the start", async function (assert) {- const { from, to } = presetRange(PRESET_LAST_30_DAYS);- const state = new RangeState(from.toDate(), to.toDate());+ const from = moment("2026-04-27");+ const to = moment("2026-05-26");await render(<template>- <DashboardDateRangePicker- @from={{state.from}}- @to={{state.to}}- @presets={{ALL_PRESETS}}- @onApply={{state.apply}}- @onCancel={{state.cancel}}- />+ <DashboardDateRangePicker @from={{from}} @to={{to}} /></template>);@@ -313,18 +259,12 @@ module(});test("clicking a day after both endpoints are picked starts a fresh pending selection", async function (assert) {- const { from, to } = presetRange(PRESET_LAST_30_DAYS);- const state = new RangeState(from.toDate(), to.toDate());+ const from = moment("2026-04-27");+ const to = moment("2026-05-26");await render(<template>- <DashboardDateRangePicker- @from={{state.from}}- @to={{state.to}}- @presets={{ALL_PRESETS}}- @onApply={{state.apply}}- @onCancel={{state.cancel}}- />+ <DashboardDateRangePicker @from={{from}} @to={{to}} /></template>);@@ -353,18 +293,12 @@ module(});test("Apply remains disabled when the pending range equals the active range", async function (assert) {- const { from, to } = presetRange(PRESET_LAST_30_DAYS);- const state = new RangeState(from.toDate(), to.toDate());+ const from = moment("2026-04-27");+ const to = moment("2026-05-26");await render(<template>- <DashboardDateRangePicker- @from={{state.from}}- @to={{state.to}}- @presets={{ALL_PRESETS}}- @onApply={{state.apply}}- @onCancel={{state.cancel}}- />+ <DashboardDateRangePicker @from={{from}} @to={{to}} /></template>);@@ -379,17 +313,20 @@ module(});test("Cancel discards pending selection and calls onCancel", async function (assert) {- const { from, to } = presetRange(PRESET_LAST_30_DAYS);- const state = new RangeState(from.toDate(), to.toDate());+ const from = moment("2026-04-27");+ const to = moment("2026-05-26");+ const applied = [];+ let cancelled = 0;+ const onApply = (payload) => applied.push(payload);+ const onCancel = () => (cancelled += 1);await render(<template><DashboardDateRangePicker- @from={{state.from}}- @to={{state.to}}- @presets={{ALL_PRESETS}}- @onApply={{state.apply}}- @onCancel={{state.cancel}}+ @from={{from}}+ @to={{to}}+ @onApply={{onApply}}+ @onCancel={{onCancel}}/></template>);@@ -397,27 +334,17 @@ module(await click(dayButton("2026-05-01"));await click(".d-date-range-picker__cancel");- assert.strictEqual(state.cancelled, 1, "onCancel is called");- assert.strictEqual(- state.applied.length,- 0,- "no commit happens on Cancel"- );+ assert.strictEqual(cancelled, 1, "onCancel is called");+ assert.strictEqual(applied.length, 0, "no commit happens on Cancel");});test("future dates are not selectable", async function (assert) {- const { from, to } = presetRange(PRESET_LAST_30_DAYS);- const state = new RangeState(from.toDate(), to.toDate());+ const from = moment("2026-04-27");+ const to = moment("2026-05-26");await render(<template>- <DashboardDateRangePicker- @from={{state.from}}- @to={{state.to}}- @presets={{ALL_PRESETS}}- @onApply={{state.apply}}- @onCancel={{state.cancel}}- />+ <DashboardDateRangePicker @from={{from}} @to={{to}} /></template>);@@ -426,83 +353,127 @@ module(.dom(dayButton("2026-05-27")).hasAttribute("aria-disabled", "true", "future days are aria-disabled");});- }-);-module(- "Integration | Component | Dashboard | DateRangePicker | preset math",- function (hooks) {- setupRenderingTest(hooks);+ test("on open it shows two consecutive months anchored on the start month", async function (assert) {+ const from = moment("2026-01-15");+ const to = moment("2026-04-20");- let clock;+ await render(+ <template>+ <DashboardDateRangePicker @from={{from}} @to={{to}} />+ </template>+ );- hooks.beforeEach(function () {- clock = fakeTime(TODAY, null, true);+ assert.deepEqual(+ monthHeaders(),+ ["January 2026", "February 2026"],+ "the start month and the following month are shown, not a start/end split"+ );});- hooks.afterEach(function () {- clock?.restore();+ test("focusing the end input brings the end month into the right panel", async function (assert) {+ const from = moment("2026-01-15");+ const to = moment("2026-04-20");++ await render(+ <template>+ <DashboardDateRangePicker @from={{from}} @to={{to}} />+ </template>+ );++ await focus(END_DATE_INPUT);++ assert.deepEqual(+ monthHeaders(),+ ["March 2026", "April 2026"],+ "the end month sits in the right panel with the preceding month on the left"+ );});- test("preset ranges are computed with today inclusive", function (assert) {- const cases = [- [PRESET_LAST_7_DAYS, "2026-05-20", "2026-05-26"],- [PRESET_LAST_30_DAYS, "2026-04-27", "2026-05-26"],- ];- for (const [preset, expectedFrom, expectedTo] of cases) {- const range = presetRange(preset);- assert.strictEqual(- range.from.format("YYYY-MM-DD"),- expectedFrom,- `${preset} start is ${expectedFrom}`- );- assert.strictEqual(- range.to.format("YYYY-MM-DD"),- expectedTo,- `${preset} end is ${expectedTo}`- );- }+ test("focusing the start input brings the start month into the left panel", async function (assert) {+ const from = moment("2026-01-15");+ const to = moment("2026-04-20");++ await render(+ <template>+ <DashboardDateRangePicker @from={{from}} @to={{to}} />+ </template>+ );++ await focus(END_DATE_INPUT);+ await focus(START_DATE_INPUT);++ assert.deepEqual(+ monthHeaders(),+ ["January 2026", "February 2026"],+ "the start month returns to the left panel when the start input is focused"+ );});- test("matchingPreset matches by exact start/end equality", function (assert) {- const { from, to } = presetRange(PRESET_LAST_30_DAYS);- assert.strictEqual(- matchingPreset(from.toDate(), to.toDate(), ALL_PRESETS),- PRESET_LAST_30_DAYS+ test("the month navigation arrows still move the view", async function (assert) {+ const from = moment("2026-01-15");+ const to = moment("2026-04-20");++ await render(+ <template>+ <DashboardDateRangePicker @from={{from}} @to={{to}} />+ </template>);- assert.strictEqual(- matchingPreset(- moment(from).subtract(1, "day").toDate(),- to.toDate(),- ALL_PRESETS- ),- null,- "an off-by-one range does not match a preset"++ const navButtons = document.querySelectorAll(".d-date-range-picker__nav");+ await click(navButtons[navButtons.length - 1]);++ assert.deepEqual(+ monthHeaders(),+ ["February 2026", "March 2026"],+ "the next arrow advances the visible window past the start anchor"+ );+ });++ test("focusing the end input on a same-month range keeps the end month in the right panel", async function (assert) {+ const from = moment("2026-03-10");+ const to = moment("2026-03-25");++ await render(+ <template>+ <DashboardDateRangePicker @from={{from}} @to={{to}} />+ </template>+ );++ await focus(END_DATE_INPUT);++ assert.deepEqual(+ monthHeaders(),+ ["February 2026", "March 2026"],+ "the end month stays in the right panel even when both endpoints share a month"+ );+ });++ test("on mobile the single panel anchors on the start month and follows the focused input", async function (assert) {+ forceMobile();++ const from = moment("2026-01-15");+ const to = moment("2026-04-20");++ await render(+ <template>+ <DashboardDateRangePicker @from={{from}} @to={{to}} />+ </template>+ );++ assert.deepEqual(+ monthHeaders(),+ ["January 2026"],+ "a single month, the start month, is shown on open"+ );++ await focus(END_DATE_INPUT);++ assert.deepEqual(+ monthHeaders(),+ ["April 2026"],+ "focusing the end input shows the end month itself in the single panel");});});--module("Unit | Dashboard | DateRangePicker | formatRange", function () {- test("same-year range omits the year on the first endpoint and includes it on the second", function (assert) {- const formatted = formatRange("2026-03-01", "2026-04-28");- assert.true(- formatted.includes("2026"),- "the formatted range includes the year"- );- });-- test("cross-year range includes the year on both endpoints", function (assert) {- const formatted = formatRange("2025-11-27", "2026-05-26");- assert.true(formatted.includes("2025"), "the from year is shown");- assert.true(formatted.includes("2026"), "the to year is shown");- });-- test("same-day range collapses to a single date", function (assert) {- const formatted = formatRange("2026-05-26", "2026-05-26");- assert.false(- formatted.includes("–"),- "the formatted same-day range does not include a dash separator"- );- });-});diff --git a/frontend/discourse/tests/integration/components/dashboard/date-range-test.gjs b/frontend/discourse/tests/integration/components/dashboard/date-range-test.gjsindex 90bcc38e0b4..acd62ef1211 100644--- a/frontend/discourse/tests/integration/components/dashboard/date-range-test.gjs+++ b/frontend/discourse/tests/integration/components/dashboard/date-range-test.gjs@@ -1,11 +1,8 @@import { tracked } from "@glimmer/tracking";import { render, settled } from "@ember/test-helpers";import { module, test } from "qunit";-import DashboardDateRange, {- calculatePresetStartDate,-} from "discourse/admin/components/dashboard/date-range";+import DashboardDateRange from "discourse/admin/components/dashboard/date-range";import { setupRenderingTest } from "discourse/tests/helpers/component-test";-import { withFrozenTime } from "discourse/tests/helpers/qunit-helpers";module("Integration | Component | Dashboard | DateRange", function (hooks) {setupRenderingTest(hooks);@@ -23,7 +20,7 @@ module("Integration | Component | Dashboard | DateRange", function (hooks) {.doesNotExist("no segmented control is rendered");});- test("trigger label is the preset name when a top-tier preset is active", async function (assert) {+ test("trigger label is the preset name when a preset is active", async function (assert) {await render(<template><DashboardDateRange @period="last_30_days" /></template>);@@ -31,29 +28,17 @@ module("Integration | Component | Dashboard | DateRange", function (hooks) {assert.dom(".db-date-range__trigger-label").hasText("Last 30 days");});- test("trigger label is the literal formatted range for hand-picked custom periods", async function (assert) {- const start = new Date("2026-03-01");- const end = new Date("2026-04-28");-+ test("trigger label names a six-month preset rather than showing its dates", async function (assert) {await render(- <template>- <DashboardDateRange- @period="custom"- @startDate={{start}}- @endDate={{end}}- />- </template>+ <template><DashboardDateRange @period="last_6_months" /></template>);- assert.dom(".db-date-range__trigger-label").includesText("Mar 1");- assert.dom(".db-date-range__trigger-label").includesText("Apr 28");+ assert.dom(".db-date-range__trigger-label").hasText("Last 6 months");});- test("trigger label is the literal range for a custom hand-picked range", async function (assert) {- const start = new Date("2026-02-10");- const end = new Date("2026-04-05");- const expectedStart = moment(start).format("ll");- const expectedEnd = moment(end).format("ll");+ test("trigger label is the literal formatted range for hand-picked custom periods", async function (assert) {+ const start = new Date("2026-03-01");+ const end = new Date("2026-04-28");await render(<template>@@ -65,12 +50,8 @@ module("Integration | Component | Dashboard | DateRange", function (hooks) {</template>);- assert- .dom(".db-date-range__trigger-label")- .includesText(expectedStart, "shows the literal start date");- assert- .dom(".db-date-range__trigger-label")- .includesText(expectedEnd, "shows the literal end date");+ assert.dom(".db-date-range__trigger-label").includesText("Mar 1");+ assert.dom(".db-date-range__trigger-label").includesText("Apr 28");});test("trigger label falls back to default when in custom mode with missing dates", async function (assert) {@@ -96,21 +77,4 @@ module("Integration | Component | Dashboard | DateRange", function (hooks) {assert.dom(".db-date-range__trigger-label").hasText("Last 7 days");});-- test("preset start dates include exactly the named period through today", function (assert) {- withFrozenTime("2026-05-14 12:00:00", "UTC", () => {- assert.strictEqual(- moment(calculatePresetStartDate("last_7_days")).format("YYYY-MM-DD"),- "2026-05-08"- );- assert.strictEqual(- moment(calculatePresetStartDate("last_30_days")).format("YYYY-MM-DD"),- "2026-04-15"- );- assert.strictEqual(- moment(calculatePresetStartDate("last_3_months")).format("YYYY-MM-DD"),- "2026-02-15"- );- });- });});diff --git a/spec/system/admin_dashboard_redesign_spec.rb b/spec/system/admin_dashboard_redesign_spec.rbindex 2e98ae8d68d..4ced1445caf 100644--- a/spec/system/admin_dashboard_redesign_spec.rb+++ b/spec/system/admin_dashboard_redesign_spec.rb@@ -10,142 +10,30 @@ describe "Admin Dashboard Redesign" dosign_in(current_user)end- describe "date picker" do- it "defaults to Last 30 days" do- dashboard.visit+ it "allows a user to use a preset range or select a custom range",+ time: Time.utc(2026, 5, 26, 12, 0, 0) do+ dashboard.visit+ expect(dashboard).to have_active_period("last_30_days")- expect(dashboard).to have_redesigned_toolbar- expect(dashboard).to have_active_period("last_30_days")- end+ dashboard.select_preset("last_7_days")- it "updates the URL when a preset is clicked" do- dashboard.visit- dashboard.select_preset("last_7_days")+ expect(page).to have_current_path("/admin?range=last_7_days")+ expect(dashboard).to have_active_period("last_7_days")- expect(page).to have_current_path(/range=last_7_days/)- expect(dashboard).to have_active_period("last_7_days")- end+ picker = dashboard.open_custom_date_range+ picker.pick_day("2026-05-01")+ picker.pick_day("2026-05-20")+ picker.apply- it "honours the range query param on initial load" do- page.visit("/admin?range=last_3_months")+ expect(dashboard).to have_active_period("custom")+ expect(page).to have_current_path(+ "/admin?end_date=2026-05-20&range=custom&start_date=2026-05-01",+ )+ expect(dashboard).to have_custom_label("May 1, 2026 – May 20, 2026")- expect(dashboard).to have_active_period("last_3_months")- end+ dashboard.select_preset("last_6_months")- it "falls back to default for an invalid range query param" do- page.visit("/admin?range=bogus_period")-- expect(dashboard).to have_active_period("last_30_days")- end-- it "rehydrates a custom range from query params" do- page.visit("/admin?range=custom&start_date=2026-03-01&end_date=2026-04-28")-- expect(dashboard).to have_active_period("custom")- expect(dashboard).to have_custom_label_text("Mar 1")- expect(dashboard).to have_custom_label_text("Apr 28")- end-- it "falls back to default when custom is missing dates" do- page.visit("/admin?range=custom")-- expect(dashboard).to have_active_period("last_30_days")- end-- it "picking a sidebar-only preset applies a custom range" do- today = Date.today- start_date = today - 6.months + 1.day-- dashboard.visit- dashboard.open_custom_date_range- dashboard.select_sidebar_preset("Last 6 months")-- expect(dashboard).to have_active_period("custom")- expect(page).to have_current_path(- "/admin?end_date=#{today.strftime("%Y-%m-%d")}&range=custom&start_date=#{start_date.strftime("%Y-%m-%d")}",- )- expect(dashboard).to have_custom_label_text(start_date.strftime("%b %-d, %Y"))- expect(dashboard).to have_custom_label_text(today.strftime("%b %-d, %Y"))- end-- it "hand-picking a range applies after clicking Apply", time: Time.utc(2026, 5, 26, 12, 0, 0) do- dashboard.visit- dashboard.open_custom_date_range- dashboard.pick_calendar_day("2026-05-01")- dashboard.pick_calendar_day("2026-05-20")- dashboard.apply_custom_range-- expect(dashboard).to have_active_period("custom")- expect(page).to have_current_path(- "/admin?end_date=2026-05-20&range=custom&start_date=2026-05-01",- )- expect(dashboard).to have_custom_label_text("May 1")- expect(dashboard).to have_custom_label_text("May 20")- end-- it "Cancel closes the popover and leaves the active range unchanged",- time: Time.utc(2026, 5, 26, 12, 0, 0) do- dashboard.visit- dashboard.open_custom_date_range- dashboard.pick_calendar_day("2026-05-01")- dashboard.cancel_custom_range-- expect(dashboard).to have_no_picker_open- expect(dashboard).to have_active_period("last_30_days")- end-- it "Esc closes the popover and leaves the active range unchanged",- time: Time.utc(2026, 5, 26, 12, 0, 0) do- dashboard.visit- dashboard.open_custom_date_range- dashboard.pick_calendar_day("2026-05-01")- dashboard.dismiss_picker_via_escape-- expect(dashboard).to have_no_picker_open- expect(dashboard).to have_active_period("last_30_days")- end-- it "reopening the popover after dismissal starts in committed state with the active range",- time: Time.utc(2026, 5, 26, 12, 0, 0) do- dashboard.visit- dashboard.open_custom_date_range- dashboard.pick_calendar_day("2026-05-01")- dashboard.cancel_custom_range- dashboard.open_custom_date_range-- # Apply is disabled when no pending selection differs from the active range,- # which confirms the picker reopened in committed state.- expect(page).to have_css(".d-date-range-picker__apply[disabled]")- expect(page).to have_css(".d-date-range-picker__day.--end")- end-- context "when on mobile", mobile: true do- it "renders as a bottom sheet and Cancel dismisses without applying",- time: Time.utc(2026, 5, 26, 12, 0, 0) do- dashboard.visit- dashboard.open_custom_date_range-- expect(page).to have_css(".fk-d-menu-modal .d-date-range-picker")-- dashboard.pick_calendar_day("2026-05-01")- dashboard.cancel_custom_range-- expect(dashboard).to have_no_picker_open- expect(dashboard).to have_active_period("last_30_days")- end-- it "applies a sidebar-only preset and closes the bottom sheet" do- today = Date.today- start_date = today - 6.months + 1.day-- dashboard.visit- dashboard.open_custom_date_range- dashboard.select_sidebar_preset("Last 6 months")-- expect(dashboard).to have_no_picker_open- expect(dashboard).to have_active_period("custom")- expect(dashboard).to have_custom_label_text(start_date.strftime("%b %-d, %Y"))- end- end+ expect(page).to have_current_path("/admin?range=last_6_months")+ expect(dashboard).to have_active_period("last_6_months")endenddiff --git a/spec/system/page_objects/components/admin_dashboard_date_range_picker.rb b/spec/system/page_objects/components/admin_dashboard_date_range_picker.rbnew file mode 100644index 00000000000..95ba2a44161--- /dev/null+++ b/spec/system/page_objects/components/admin_dashboard_date_range_picker.rb@@ -0,0 +1,29 @@+# frozen_string_literal: true++module PageObjects+ module Components+ class AdminDashboardDateRangePicker < PageObjects::Components::Base+ SELECTOR = ".d-date-range-picker"++ def open?+ has_css?(SELECTOR)+ end++ def select_preset(label)+ find("#{SELECTOR}__preset", text: label).click+ self+ end++ def pick_day(date)+ parsed = Date.parse(date.to_s)+ find("#{SELECTOR}__day[aria-label='#{parsed.strftime("%B %-d, %Y")}']:not(.--muted)").click+ self+ end++ def apply+ find("#{SELECTOR}__apply").click+ self+ end+ end+ end+enddiff --git a/spec/system/page_objects/pages/admin_dashboard.rb b/spec/system/page_objects/pages/admin_dashboard.rbindex 23c2897a743..be31f20ac68 100644--- a/spec/system/page_objects/pages/admin_dashboard.rb+++ b/spec/system/page_objects/pages/admin_dashboard.rb@@ -39,53 +39,24 @@ module PageObjectsendend- def select_preset(period)- open_custom_date_range- find(".d-date-range-picker__preset", text: preset_label(period)).click- self+ def has_custom_label?(text)+ has_css?(".db-date-range__trigger-label", exact_text: text)end- def has_custom_label_text?(text)- has_css?(".db-date-range__trigger-label", text: text)+ def date_range_picker+ PageObjects::Components::AdminDashboardDateRangePicker.newenddef open_custom_date_rangefind(".db-date-range__trigger").click- has_css?(".d-date-range-picker")- self- end-- def select_sidebar_preset(label)- find(".d-date-range-picker__preset", text: label).click- self- end-- def pick_calendar_day(date)- moment_date = Date.parse(date.to_s)- aria_label = moment_date.strftime("%B %-d, %Y")- find(".d-date-range-picker__day[aria-label='#{aria_label}']:not(.--muted)").click- self+ date_range_picker.tap(&:open?)end- def apply_custom_range- find(".d-date-range-picker__apply").click- self- end-- def cancel_custom_range- find(".d-date-range-picker__cancel").click- self- end-- def dismiss_picker_via_escape- find(".d-date-range-picker").send_keys :escape+ def select_preset(period)+ open_custom_date_range.select_preset(preset_label(period))selfend- def has_no_picker_open?- has_no_css?(".d-date-range-picker")- end-def has_configure_button?has_css?(".btn[data-identifier='db-configure']")end@@ -165,6 +136,10 @@ module PageObjects"Last 30 days"when "last_3_months""Last 3 months"+ when "last_6_months"+ "Last 6 months"+ when "last_year"+ "Last year"endendend