Skip to content

A platform for community discussion. Free, open, simple.

UX: Redesign custom date range picker on new admin dashboard (#40355)

Alan Guo Xiang Tan4dc52d48bec1
diff --git a/app/assets/stylesheets/admin/admin_dashboard.scss b/app/assets/stylesheets/admin/admin_dashboard.scss
index 851278121eb..5a68dcab67c 100644
--- a/app/assets/stylesheets/admin/admin_dashboard.scss
+++ b/app/assets/stylesheets/admin/admin_dashboard.scss
@@ -20,6 +20,78 @@
display: flex;
gap: var(--space-4);
margin-left: auto;
+
+ @include viewport.until(sm) {
+ position: fixed;
+ bottom: calc(env(safe-area-inset-bottom) + var(--space-4));
+ right: 50%;
+ transform: translateX(50%);
+ z-index: 2;
+ margin-left: 0;
+ align-items: center;
+ gap: var(--space-2);
+ transition: bottom 0.3s ease;
+
+ .footer-nav-visible & {
+ bottom: calc(
+ var(--footer-nav-height) + env(safe-area-inset-bottom) +
+ var(--space-4)
+ );
+ }
+ }
+ }
+}
+
+.db-date-range {
+ &__trigger {
+ height: var(--space-9);
+ padding: var(--space-1) var(--space-3);
+ border-radius: var(--d-border-radius);
+ border: 1px solid var(--primary-low);
+ background: var(--secondary);
+ color: var(--primary-high);
+ display: inline-flex;
+ align-items: center;
+ gap: var(--space-1);
+
+ &:hover {
+ background: var(--primary-very-low);
+ color: var(--primary);
+ }
+
+ @include viewport.until(sm) {
+ border-radius: 999px;
+ box-shadow: var(--shadow-dropdown);
+ }
+ }
+
+ &__popover {
+ padding: 0;
+ }
+}
+
+.db-toolbar__actions .btn[data-identifier="db-configure"] {
+ height: var(--space-9);
+ padding: var(--space-1) var(--space-3);
+ border-radius: var(--d-border-radius);
+
+ @include viewport.until(sm) {
+ width: var(--space-9);
+ padding: 0;
+ min-height: 0;
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+ border-radius: 999px;
+ box-shadow: var(--shadow-dropdown);
+
+ .d-button-label {
+ display: none;
+ }
+
+ .d-icon {
+ margin-right: 0;
+ }
}
}
diff --git a/app/assets/stylesheets/common/components/_index.scss b/app/assets/stylesheets/common/components/_index.scss
index e54b2b5709d..3bf8d4cdf2b 100644
--- a/app/assets/stylesheets/common/components/_index.scss
+++ b/app/assets/stylesheets/common/components/_index.scss
@@ -24,6 +24,7 @@
@import "d-toggle-switch";
@import "date-input";
@import "date-picker";
+@import "date-range-picker";
@import "date-time-input-range";
@import "date-time-input";
@import "d-combo-button";
diff --git a/app/assets/stylesheets/common/components/date-range-picker.scss b/app/assets/stylesheets/common/components/date-range-picker.scss
new file mode 100644
index 00000000000..faf7fe16827
--- /dev/null
+++ b/app/assets/stylesheets/common/components/date-range-picker.scss
@@ -0,0 +1,230 @@
+@use "lib/viewport";
+
+.d-date-range-picker {
+ display: grid;
+ grid-template-columns: max-content 1fr;
+ background: var(--secondary);
+ min-width: 0;
+
+ @include viewport.until(sm) {
+ grid-template-columns: 1fr;
+ grid-template-rows: max-content 1fr;
+ }
+
+ &__presets {
+ display: flex;
+ flex-direction: column;
+ padding: var(--space-2) 0;
+ border-right: 1px solid var(--primary-low);
+ min-width: 8.75rem;
+
+ @include viewport.until(sm) {
+ flex-direction: row;
+ flex-wrap: nowrap;
+ gap: var(--space-1);
+ padding: var(--space-2) var(--space-4);
+ border-right: none;
+ border-bottom: 1px solid var(--primary-low);
+ min-width: 0;
+ overflow-x: auto;
+ scrollbar-width: none;
+ mask-image: linear-gradient(
+ to right,
+ transparent 0,
+ black var(--space-4),
+ black calc(100% - var(--space-6)),
+ transparent 100%
+ );
+
+ &::-webkit-scrollbar {
+ display: none;
+ }
+ }
+ }
+
+ &__preset {
+ width: 100%;
+ text-align: left;
+ background: transparent;
+ border: 0;
+ padding: var(--space-2) var(--space-3);
+ font: inherit;
+ color: var(--primary);
+ cursor: pointer;
+ border-radius: 0;
+
+ &:hover {
+ background: var(--primary-low);
+ }
+
+ &.is-active {
+ background: var(--tertiary-low);
+ color: var(--tertiary);
+ font-weight: 500;
+ }
+
+ @include viewport.until(sm) {
+ width: auto;
+ flex-shrink: 0;
+ border: 1px solid var(--primary-low);
+ border-radius: var(--space-1);
+ white-space: nowrap;
+ }
+ }
+
+ &__body {
+ display: flex;
+ flex-direction: column;
+ padding: var(--space-3);
+ min-width: 0;
+ }
+
+ &__calendar {
+ display: flex;
+ align-items: flex-start;
+ gap: var(--space-2);
+ }
+
+ &__nav {
+ background: transparent;
+ border: 0;
+ padding: var(--space-2);
+ cursor: pointer;
+ color: var(--primary-medium);
+ border-radius: var(--space-1);
+
+ &:hover {
+ background: var(--primary-low);
+ color: var(--primary);
+ }
+ }
+
+ &__months {
+ display: flex;
+ gap: var(--space-8);
+ flex: 1;
+ min-width: 0;
+ align-items: stretch;
+
+ @include viewport.until(sm) {
+ gap: 0;
+ }
+ }
+
+ &__month {
+ flex: 1;
+ min-width: 0;
+ }
+
+ &__month-header {
+ text-align: center;
+ font-weight: 500;
+ padding: var(--space-1) 0 var(--space-2);
+ }
+
+ &__weekdays {
+ display: grid;
+ grid-template-columns: repeat(7, 1fr);
+ gap: 2px;
+ color: var(--primary-medium);
+ font-size: var(--font-down-2);
+ text-align: center;
+ padding-bottom: var(--space-1);
+ }
+
+ &__grid {
+ display: flex;
+ flex-direction: column;
+ gap: 2px;
+ }
+
+ &__week {
+ display: grid;
+ grid-template-columns: repeat(7, 1fr);
+ gap: 2px;
+ }
+
+ &__day {
+ background: transparent;
+ border: 0;
+ padding: var(--space-1) 0;
+ cursor: pointer;
+ border-radius: var(--space-1);
+ font: inherit;
+ color: var(--primary);
+ aspect-ratio: 1;
+
+ &:hover:not(.--disabled) {
+ background: var(--tertiary-low);
+ }
+
+ &.--disabled {
+ color: var(--primary-low-mid);
+ cursor: not-allowed;
+ background: transparent;
+ }
+
+ &.--in-range {
+ background: var(--tertiary-very-low, var(--tertiary-low));
+ border-radius: 0;
+ }
+
+ &.--hover-preview {
+ background: repeating-linear-gradient(
+ 45deg,
+ var(--tertiary-very-low, var(--tertiary-low)),
+ var(--tertiary-very-low, var(--tertiary-low)) 4px,
+ var(--secondary) 4px,
+ var(--secondary) 8px
+ );
+ border-radius: 0;
+ }
+
+ &.--start,
+ &.--end {
+ background: var(--tertiary);
+ color: var(--secondary);
+ font-weight: 600;
+
+ &:hover {
+ background: var(--tertiary-hover, var(--tertiary));
+ }
+ }
+
+ &:focus-visible {
+ outline: 2px solid var(--tertiary);
+ outline-offset: -2px;
+ }
+ }
+
+ &__inputs {
+ display: grid;
+ grid-template-columns: 1fr 1fr;
+ gap: var(--space-2);
+ margin-top: var(--space-3);
+ }
+
+ &__input {
+ width: 100%;
+ box-sizing: border-box;
+ border: 1px solid var(--primary-low);
+ padding: var(--space-1) var(--space-2);
+ border-radius: var(--space-1);
+ background: var(--secondary);
+ color: var(--primary);
+ font-size: var(--font-down-1);
+ min-height: 1.75rem;
+
+ &:focus-visible {
+ outline: 2px solid var(--tertiary);
+ outline-offset: -1px;
+ }
+ }
+
+ &__footer {
+ display: flex;
+ justify-content: flex-end;
+ gap: var(--space-2);
+ margin-top: var(--space-3);
+ }
+}
diff --git a/config/locales/client.en.yml b/config/locales/client.en.yml
index 4c9e55f4713..aad4ba3cde5 100644
--- a/config/locales/client.en.yml
+++ b/config/locales/client.en.yml
@@ -178,6 +178,18 @@ en:
placeholder: date
from_placeholder: "from date"
to_placeholder: "to date"
+ date_range_picker:
+ apply: "Apply"
+ start_date: "Start date"
+ end_date: "End date"
+ date_placeholder: "yyyy/mm/dd"
+ presets:
+ label: "Date range presets"
+ last_7_days: "Last 7 days"
+ last_30_days: "Last 30 days"
+ last_3_months: "Last 3 months"
+ last_6_months: "Last 6 months"
+ last_year: "Last year"
languages:
ar:
name: Arabic
diff --git a/frontend/discourse/admin/components/dashboard/date-range-picker.gjs b/frontend/discourse/admin/components/dashboard/date-range-picker.gjs
new file mode 100644
index 00000000000..13e5a6be159
--- /dev/null
+++ b/frontend/discourse/admin/components/dashboard/date-range-picker.gjs
@@ -0,0 +1,658 @@
+import Component from "@glimmer/component";
+import { tracked } from "@glimmer/tracking";
+import { fn, get } 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) {
+ 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;
+
+ @tracked pendingStart = null;
+ @tracked pendingEnd = null;
+ @tracked hoveredDay = null;
+ @tracked focusedDay = null;
+ @tracked viewStartMonthOverride = null;
+
+ focusDay = modifier((element, [shouldFocus]) => {
+ if (shouldFocus) {
+ element.focus();
+ }
+ });
+
+ scrollActivePresetIntoView = modifier((element) => {
+ const active = element.querySelector(
+ ".d-date-range-picker__preset.is-active"
+ );
+ if (!active) {
+ return;
+ }
+ const railRect = element.getBoundingClientRect();
+ const activeRect = active.getBoundingClientRect();
+ element.scrollLeft +=
+ activeRect.left - railRect.left - (railRect.width - activeRect.width) / 2;
+ });
+
+ get presets() {
+ return this.args.presets ?? ALL_PRESETS;
+ }
+
+ get maxDate() {
+ return toDayMoment(this.args.maxDate) ?? moment().startOf("day");
+ }
+
+ get committed() {
+ return this.pendingStart === null;
+ }
+
+ get currentStart() {
+ return this.committed ? toDayMoment(this.args.from) : this.pendingStart;
+ }
+
+ get currentEnd() {
+ 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;
+ }
+ return (
+ ymd(this.pendingStart) === ymd(this.args.from) &&
+ ymd(this.pendingEnd) === ymd(this.args.to)
+ );
+ }
+
+ get showTwoMonths() {
+ 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");
+ }
+ 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"));
+ }
+ return months;
+ }
+
+ get effectiveFocusedDay() {
+ return (
+ this.focusedDay ?? toDayMoment(this.args.to) ?? moment().startOf("day")
+ );
+ }
+
+ get weekdayLabels() {
+ return moment.weekdaysMin(true);
+ }
+
+ get hoverRangeEnd() {
+ if (this.committed || this.pendingEnd || !this.hoveredDay) {
+ return null;
+ }
+ return this.hoveredDay.isBefore(this.pendingStart, "day")
+ ? this.pendingStart
+ : this.hoveredDay;
+ }
+
+ get hoverRangeStart() {
+ if (this.committed || this.pendingEnd || !this.hoveredDay) {
+ return null;
+ }
+ return this.hoveredDay.isBefore(this.pendingStart, "day")
+ ? this.hoveredDay
+ : this.pendingStart;
+ }
+
+ @action
+ weeksFor(monthStart) {
+ const start = monthStart.clone().startOf("month").startOf("week");
+ const end = monthStart.clone().endOf("month").endOf("week");
+ const weeks = [];
+ const cursor = start.clone();
+ while (cursor.isSameOrBefore(end)) {
+ const week = [];
+ for (let i = 0; i < 7; i++) {
+ week.push(cursor.clone());
+ cursor.add(1, "day");
+ }
+ weeks.push(week);
+ }
+ return weeks;
+ }
+
+ @action
+ isMutedDay(day, monthStart) {
+ return !day.isSame(monthStart, "month");
+ }
+
+ @action
+ isDisabledDay(day) {
+ return day.isAfter(this.maxDate, "day");
+ }
+
+ @action
+ isStartDay(day) {
+ return this.currentStart && day.isSame(this.currentStart, "day");
+ }
+
+ @action
+ isEndDay(day) {
+ return this.currentEnd && day.isSame(this.currentEnd, "day");
+ }
+
+ @action
+ isInRangeDay(day) {
+ if (!this.currentStart || !this.currentEnd) {
+ return false;
+ }
+ return (
+ day.isAfter(this.currentStart, "day") &&
+ day.isBefore(this.currentEnd, "day")
+ );
+ }
+
+ @action
+ isHoverPreviewDay(day) {
+ if (!this.hoverRangeStart || !this.hoverRangeEnd) {
+ return false;
+ }
+ return (
+ day.isAfter(this.hoverRangeStart, "day") &&
+ day.isBefore(this.hoverRangeEnd, "day")
+ );
+ }
+
+ @action
+ isFocusedDay(day) {
+ return day.isSame(this.effectiveFocusedDay, "day");
+ }
+
+ @action
+ shouldProgrammaticallyFocusDay(day) {
+ return this.focusedDay !== null && day.isSame(this.focusedDay, "day");
+ }
+
+ @action
+ isAriaSelected(day) {
+ if (this.isStartDay(day) || this.isEndDay(day)) {
+ return "true";
+ }
+ return "false";
+ }
+
+ @action
+ dayClass(day) {
+ const classes = ["d-date-range-picker__day"];
+ if (this.isDisabledDay(day)) {
+ classes.push("--disabled");
+ }
+ if (this.isStartDay(day)) {
+ classes.push("--start");
+ }
+ if (this.isEndDay(day)) {
+ classes.push("--end");
+ }
+ if (this.isInRangeDay(day)) {
+ classes.push("--in-range");
+ }
+ if (this.isHoverPreviewDay(day)) {
+ classes.push("--hover-preview");
+ }
+ return classes.join(" ");
+ }
+
+ @action
+ selectPreset(preset) {
+ const { from, to } = presetRange(preset);
+ this.args.onApply?.({
+ preset,
+ from: from.toDate(),
+ to: to.toDate(),
+ });
+ }
+
+ @action
+ clickDay(day) {
+ if (this.isDisabledDay(day)) {
+ return;
+ }
+ if (this.committed || this.pendingEnd) {
+ this.pendingStart = day.clone();
+ this.pendingEnd = null;
+ this.focusedDay = day.clone();
+ return;
+ }
+ if (day.isBefore(this.pendingStart, "day")) {
+ this.pendingStart = day.clone();
+ } else {
+ this.pendingEnd = day.clone();
+ }
+ this.focusedDay = day.clone();
+ }
+
+ @action
+ hoverDay(day) {
+ if (this.committed || this.isDisabledDay(day)) {
+ return;
+ }
+ this.hoveredDay = day.clone();
+ }
+
+ @action
+ leaveGrid() {
+ this.hoveredDay = null;
+ }
+
+ @action
+ cancel() {
+ this.pendingStart = null;
+ this.pendingEnd = null;
+ this.hoveredDay = null;
+ this.viewStartMonthOverride = null;
+ this.args.onCancel?.();
+ }
+
+ @action
+ apply() {
+ if (this.applyDisabled) {
+ return;
+ }
+ this.args.onApply?.({
+ preset: null,
+ from: this.pendingStart.toDate(),
+ to: this.pendingEnd.toDate(),
+ });
+ }
+
+ @action
+ shiftMonth(delta) {
+ this.viewStartMonthOverride = this.viewStartMonth
+ .clone()
+ .add(delta, "months");
+ }
+
+ @action
+ handleKeyDown(event) {
+ const candidate = this.effectiveFocusedDay.clone();
+ let handled = true;
+ switch (event.key) {
+ case "ArrowLeft":
+ candidate.subtract(1, "day");
+ break;
+ case "ArrowRight":
+ candidate.add(1, "day");
+ break;
+ case "ArrowUp":
+ candidate.subtract(7, "days");
+ break;
+ case "ArrowDown":
+ candidate.add(7, "days");
+ break;
+ case "PageUp":
+ candidate.subtract(1, "month");
+ break;
+ case "PageDown":
+ candidate.add(1, "month");
+ break;
+ case "Home":
+ candidate.startOf("week");
+ break;
+ case "End":
+ candidate.endOf("week");
+ break;
+ default:
+ handled = false;
+ }
+ if (!handled) {
+ return;
+ }
+ event.preventDefault();
+ const target = candidate.isAfter(this.maxDate, "day")
+ ? this.maxDate.clone()
+ : candidate;
+ this.focusedDay = target;
+ this.ensureVisible(target);
+ }
+
+ ensureVisible(day) {
+ const lastVisibleMonth = this.viewStartMonth
+ .clone()
+ .add(this.showTwoMonths ? 1 : 0, "month")
+ .endOf("month");
+ if (day.isBefore(this.viewStartMonth, "day")) {
+ this.viewStartMonthOverride = day.clone().startOf("month");
+ } else if (day.isAfter(lastVisibleMonth, "day")) {
+ this.viewStartMonthOverride = day
+ .clone()
+ .startOf("month")
+ .subtract(this.showTwoMonths ? 1 : 0, "month");
+ }
+ }
+
+ get startInputValue() {
+ return this.currentStart ? this.currentStart.format("YYYY/MM/DD") : "";
+ }
+
+ get endInputValue() {
+ return this.currentEnd ? this.currentEnd.format("YYYY/MM/DD") : "";
+ }
+
+ parseTypedDate(value) {
+ const parsed = moment(value, "YYYY/MM/DD", true);
+ if (!parsed.isValid()) {
+ return null;
+ }
+ const day = parsed.startOf("day");
+ if (day.isAfter(this.maxDate, "day")) {
+ return null;
+ }
+ return day;
+ }
+
+ @action
+ commitStartInput(event) {
+ const parsed = this.parseTypedDate(event.target.value);
+ if (!parsed) {
+ event.target.value = this.startInputValue;
+ return;
+ }
+ const end = this.currentEnd;
+ this.pendingStart = parsed;
+ this.pendingEnd = end && !end.isBefore(parsed, "day") ? end.clone() : null;
+ this.focusedDay = parsed.clone();
+ }
+
+ @action
+ commitEndInput(event) {
+ const parsed = this.parseTypedDate(event.target.value);
+ const start = this.currentStart;
+ if (!parsed || !start || parsed.isBefore(start, "day")) {
+ event.target.value = this.endInputValue;
+ return;
+ }
+ this.pendingStart = start.clone();
+ this.pendingEnd = parsed;
+ this.focusedDay = parsed.clone();
+ }
+
+ @action
+ commitInputOnEnter(event) {
+ if (event.key === "Enter") {
+ event.preventDefault();
+ event.target.blur();
+ }
+ }
+
+ <template>
+ <div class="d-date-range-picker">
+ <div
+ class="d-date-range-picker__presets"
+ role="group"
+ aria-label={{i18n "date_range_picker.presets.label"}}
+ {{this.scrollActivePresetIntoView}}
+ >
+ {{#each this.presets as |preset|}}
+ <button
+ type="button"
+ class={{dConcatClass
+ "d-date-range-picker__preset"
+ (if (eq this.activePreset preset) "is-active")
+ }}
+ aria-current={{if (eq this.activePreset preset) "true"}}
+ {{on "click" (fn this.selectPreset preset)}}
+ >
+ {{i18n (get PRESET_LABEL_KEYS preset)}}
+ </button>
+ {{/each}}
+ </div>
+
+ <div class="d-date-range-picker__body">
+ <div
+ class="d-date-range-picker__calendar"
+ {{on "mouseleave" this.leaveGrid}}
+ >
+ <button
+ type="button"
+ class="d-date-range-picker__nav"
+ aria-label={{i18n "dates.previous_month"}}
+ {{on "click" (fn this.shiftMonth -1)}}
+ >
+ {{dIcon "chevron-left"}}
+ </button>
+
+ <div class="d-date-range-picker__months">
+ {{#each this.visibleMonths as |month|}}
+ <div class="d-date-range-picker__month">
+ <div class="d-date-range-picker__month-header">
+ {{fmt month "MMMM YYYY"}}
+ </div>
+ <div class="d-date-range-picker__weekdays" aria-hidden="true">
+ {{#each this.weekdayLabels as |dow|}}
+ <span>{{dow}}</span>
+ {{/each}}
+ </div>
+ <div
+ class="d-date-range-picker__grid"
+ role="grid"
+ aria-label={{fmt month "MMMM YYYY"}}
+ {{on "keydown" this.handleKeyDown}}
+ >
+ {{#each (this.weeksFor month) as |week|}}
+ <div class="d-date-range-picker__week" role="row">
+ {{#each week as |day|}}
+ {{#if (this.isMutedDay day month)}}
+ <span aria-hidden="true"></span>
+ {{else}}
+ <button
+ type="button"
+ role="gridcell"
+ class={{this.dayClass day}}
+ tabindex={{if (this.isFocusedDay day) "0" "-1"}}
+ aria-selected={{this.isAriaSelected day}}
+ aria-disabled={{if (this.isDisabledDay day) "true"}}
+ aria-label={{fmt day "LL"}}
+ disabled={{this.isDisabledDay day}}
+ {{this.focusDay
+ (this.shouldProgrammaticallyFocusDay day)
+ }}
+ {{on "click" (fn this.clickDay day)}}
+ {{on "mouseenter" (fn this.hoverDay day)}}
+ >
+ {{fmt day "D"}}
+ </button>
+ {{/if}}
+ {{/each}}
+ </div>
+ {{/each}}
+ </div>
+ </div>
+ {{/each}}
+ </div>
+
+ <button
+ type="button"
+ class="d-date-range-picker__nav"
+ aria-label={{i18n "dates.next_month"}}
+ {{on "click" (fn this.shiftMonth 1)}}
+ >
+ {{dIcon "chevron-right"}}
+ </button>
+ </div>
+
+ <div class="d-date-range-picker__inputs">
+ <input
+ type="text"
+ class="d-date-range-picker__input"
+ inputmode="numeric"
+ autocomplete="off"
+ placeholder={{i18n "date_range_picker.date_placeholder"}}
+ aria-label={{i18n "date_range_picker.start_date"}}
+ value={{this.startInputValue}}
+ {{on "change" this.commitStartInput}}
+ {{on "keydown" this.commitInputOnEnter}}
+ />
+ <input
+ type="text"
+ class="d-date-range-picker__input"
+ inputmode="numeric"
+ autocomplete="off"
+ placeholder={{i18n "date_range_picker.date_placeholder"}}
+ aria-label={{i18n "date_range_picker.end_date"}}
+ value={{this.endInputValue}}
+ {{on "change" this.commitEndInput}}
+ {{on "keydown" this.commitInputOnEnter}}
+ />
+ </div>
+
+ <div class="d-date-range-picker__footer">
+ <DButton
+ @action={{this.cancel}}
+ @label="cancel"
+ class="btn-default d-date-range-picker__cancel"
+ />
+ <DButton
+ @action={{this.apply}}
+ @label="date_range_picker.apply"
+ @disabled={{this.applyDisabled}}
+ class="btn-primary d-date-range-picker__apply"
+ />
+ </div>
+ </div>
+ </div>
+ </template>
+}
diff --git a/frontend/discourse/admin/components/dashboard/date-range.gjs b/frontend/discourse/admin/components/dashboard/date-range.gjs
index f0b05006647..072f6023587 100644
--- a/frontend/discourse/admin/components/dashboard/date-range.gjs
+++ b/frontend/discourse/admin/components/dashboard/date-range.gjs
@@ -1,14 +1,20 @@
import Component from "@glimmer/component";
-import { array, hash } from "@ember/helper";
+import { fn } from "@ember/helper";
import { action } from "@ember/object";
-import { service } from "@ember/service";
-import DSegmentedControl from "discourse/components/d-segmented-control";
+import DashboardDateRangePicker, {
+ ALL_PRESETS,
+ formatRange,
+ PRESET_LAST_3_MONTHS,
+ PRESET_LAST_7_DAYS,
+ PRESET_LAST_30_DAYS,
+} from "discourse/admin/components/dashboard/date-range-picker";
+import DMenu from "discourse/float-kit/components/d-menu";
+import dIcon from "discourse/ui-kit/helpers/d-icon";
import { i18n } from "discourse-i18n";
-import CustomDateRangeModal from "../modal/custom-date-range";
-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_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;
@@ -20,6 +26,14 @@ export const VALID_PERIODS = [
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) {
@@ -34,76 +48,49 @@ export function calculatePresetStartDate(period) {
}
export default class DashboardDateRange extends Component {
- @service modal;
-
- get isCustom() {
- return this.args.period === PERIOD_CUSTOM;
- }
-
- get customLabel() {
- if (!this.isCustom || !this.args.startDate || !this.args.endDate) {
- return i18n("admin.dashboard.period.custom");
+ get triggerLabel() {
+ const { period, startDate, endDate } = this.args;
+ if (TOP_TIER_PRESET_I18N_KEYS[period]) {
+ return i18n(TOP_TIER_PRESET_I18N_KEYS[period]);
}
-
- return i18n("admin.dashboard.period.custom_range", {
- start: moment(this.args.startDate).format("MMM D"),
- end: moment(this.args.endDate).format("MMM D"),
- });
- }
-
- @action
- selectPeriod(value) {
- if (value === PERIOD_CUSTOM) {
- // custom is handled via handleClick to support re-opening the modal when
- // already-selected; skip preset state change here
- return;
+ if (period === PERIOD_CUSTOM && startDate && endDate) {
+ return formatRange(startDate, endDate);
}
- this.args.setPeriod?.(value);
+ return i18n(TOP_TIER_PRESET_I18N_KEYS[DEFAULT_PERIOD]);
}
@action
- handleClick(value) {
- if (value === PERIOD_CUSTOM) {
- this.openCustomModal();
+ handleApply(close, { preset, from, to }) {
+ if (preset && TOP_TIER_PRESETS.has(preset)) {
+ this.args.setPeriod?.(preset);
+ } else {
+ this.args.setCustomDateRange?.(from, to);
}
- }
-
- openCustomModal() {
- this.modal.show(CustomDateRangeModal, {
- model: {
- startDate: this.args.startDate,
- endDate: this.args.endDate,
- setCustomDateRange: this.args.setCustomDateRange,
- },
- });
+ close();
}
<template>
- <DSegmentedControl
- class="db-date-range"
- @name="dashboard-period"
- @value={{@period}}
- @onSelect={{this.selectPeriod}}
- @onClickItem={{this.handleClick}}
- @items={{array
- (hash
- value=PERIOD_LAST_7_DAYS
- label=(i18n "admin.dashboard.period.last_7_days")
- )
- (hash
- value=PERIOD_LAST_30_DAYS
- label=(i18n "admin.dashboard.period.last_30_days")
- )
- (hash
- value=PERIOD_LAST_3_MONTHS
- label=(i18n "admin.dashboard.period.last_3_months")
- )
- (hash
- value=PERIOD_CUSTOM
- label=this.customLabel
- class="db-date-range__custom"
- )
- }}
- />
+ <DMenu
+ @identifier="db-date-range-menu"
+ @triggerClass="db-date-range__trigger"
+ @modalForMobile={{true}}
+ @placement="bottom-end"
+ @maxWidth={{680}}
+ @contentClass="db-date-range__popover"
+ >
+ <:trigger>
+ {{dIcon "calendar-days"}}
+ <span class="db-date-range__trigger-label">{{this.triggerLabel}}</span>
+ </:trigger>
+ <:content as |args|>
+ <DashboardDateRangePicker
+ @from={{@startDate}}
+ @to={{@endDate}}
+ @presets={{ALL_PRESETS}}
+ @onApply={{fn this.handleApply args.close}}
+ @onCancel={{args.close}}
+ />
+ </:content>
+ </DMenu>
</template>
}
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.gjs
new file mode 100644
index 00000000000..66f190ead4d
--- /dev/null
+++ b/frontend/discourse/tests/integration/components/dashboard/date-range-picker-test.gjs
@@ -0,0 +1,508 @@
+import { tracked } from "@glimmer/tracking";
+import { click, fillIn, 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 { 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;
+ }
+}
+
+function dayButton(dateString) {
+ const m = moment(dateString);
+ return `.d-date-range-picker__day[aria-label="${m.format("LL")}"]:not(.--muted)`;
+}
+
+module(
+ "Integration | Component | Dashboard | DateRangePicker",
+ function (hooks) {
+ setupRenderingTest(hooks);
+
+ let clock;
+
+ hooks.beforeEach(function () {
+ clock = fakeTime(TODAY, null, true);
+ });
+
+ hooks.afterEach(function () {
+ 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());
+
+ await render(
+ <template>
+ <DashboardDateRangePicker
+ @from={{state.from}}
+ @to={{state.to}}
+ @presets={{ALL_PRESETS}}
+ @onApply={{state.apply}}
+ @onCancel={{state.cancel}}
+ />
+ </template>
+ );
+
+ assert
+ .dom(dayButton(from))
+ .hasClass(
+ "--start",
+ "the start day of the active period 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"
+ );
+ });
+
+ 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());
+
+ await render(
+ <template>
+ <DashboardDateRangePicker
+ @from={{state.from}}
+ @to={{state.to}}
+ @presets={{ALL_PRESETS}}
+ @onApply={{state.apply}}
+ @onCancel={{state.cancel}}
+ />
+ </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"
+ );
+ 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"
+ );
+ assert.strictEqual(
+ moment(payload.to).format("YYYY-MM-DD"),
+ expected.to.format("YYYY-MM-DD"),
+ "the emitted to matches the preset end"
+ );
+ });
+
+ 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());
+
+ await render(
+ <template>
+ <DashboardDateRangePicker
+ @from={{state.from}}
+ @to={{state.to}}
+ @presets={{ALL_PRESETS}}
+ @onApply={{state.apply}}
+ @onCancel={{state.cancel}}
+ />
+ </template>
+ );
+
+ assert
+ .dom(".d-date-range-picker__apply")
+ .isDisabled("Apply is disabled before a pending selection is made");
+
+ await click(dayButton("2026-05-01"));
+
+ assert
+ .dom(dayButton("2026-05-01"))
+ .hasClass(
+ "--start",
+ "first click sets the pending start with --start class"
+ );
+ assert
+ .dom(dayButton(to))
+ .doesNotHaveClass(
+ "--end",
+ "the previous active end is cleared from the calendar in pending state"
+ );
+ assert
+ .dom(".d-date-range-picker__apply")
+ .isDisabled(
+ "Apply stays disabled while only the start endpoint is picked"
+ );
+
+ await click(dayButton("2026-05-20"));
+
+ assert
+ .dom(dayButton("2026-05-01"))
+ .hasClass("--start", "start remains highlighted after second click");
+ assert
+ .dom(dayButton("2026-05-20"))
+ .hasClass(
+ "--end",
+ "second click sets the pending end with --end class"
+ );
+ assert.dom(".d-date-range-picker__apply").isNotDisabled();
+
+ await click(".d-date-range-picker__apply");
+
+ assert.strictEqual(state.applied.length, 1, "onApply is called once");
+ const payload = state.applied[0];
+ assert.strictEqual(payload.preset, null, "no preset is emitted");
+ assert.strictEqual(
+ moment(payload.from).format("YYYY-MM-DD"),
+ "2026-05-01",
+ "from is the picked start"
+ );
+ assert.strictEqual(
+ moment(payload.to).format("YYYY-MM-DD"),
+ "2026-05-20",
+ "to is the picked end"
+ );
+ });
+
+ 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());
+
+ await render(
+ <template>
+ <DashboardDateRangePicker
+ @from={{state.from}}
+ @to={{state.to}}
+ @presets={{ALL_PRESETS}}
+ @onApply={{state.apply}}
+ @onCancel={{state.cancel}}
+ />
+ </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"
+ );
+
+ assert
+ .dom(dayButton("2026-05-02"))
+ .hasClass("--start", "typed start date is reflected on the calendar");
+ assert
+ .dom(dayButton("2026-05-18"))
+ .hasClass("--end", "typed end date is reflected on the calendar");
+ assert.dom(".d-date-range-picker__apply").isNotDisabled();
+
+ await click(".d-date-range-picker__apply");
+
+ const payload = state.applied[0];
+ assert.strictEqual(
+ moment(payload.from).format("YYYY-MM-DD"),
+ "2026-05-02"
+ );
+ assert.strictEqual(moment(payload.to).format("YYYY-MM-DD"), "2026-05-18");
+ });
+
+ 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());
+
+ await render(
+ <template>
+ <DashboardDateRangePicker
+ @from={{state.from}}
+ @to={{state.to}}
+ @presets={{ALL_PRESETS}}
+ @onApply={{state.apply}}
+ @onCancel={{state.cancel}}
+ />
+ </template>
+ );
+
+ await fillIn(
+ ".d-date-range-picker__input[aria-label='Start date']",
+ "not-a-date"
+ );
+
+ assert
+ .dom(".d-date-range-picker__input[aria-label='Start date']")
+ .hasValue(
+ moment(from).format("YYYY/MM/DD"),
+ "the field reverts to the active start when the input is invalid"
+ );
+ });
+
+ 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());
+
+ await render(
+ <template>
+ <DashboardDateRangePicker
+ @from={{state.from}}
+ @to={{state.to}}
+ @presets={{ALL_PRESETS}}
+ @onApply={{state.apply}}
+ @onCancel={{state.cancel}}
+ />
+ </template>
+ );
+
+ await click(dayButton("2026-05-15"));
+ await click(dayButton("2026-05-05"));
+
+ assert
+ .dom(dayButton("2026-05-05"))
+ .hasClass("--start", "the earlier click becomes the new start");
+ assert
+ .dom(dayButton("2026-05-15"))
+ .doesNotHaveClass(
+ "--end",
+ "the previous click is no longer the end after re-anchor"
+ );
+ assert
+ .dom(".d-date-range-picker__apply")
+ .isDisabled(
+ "Apply is disabled because the end is unset after re-anchor"
+ );
+ });
+
+ 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());
+
+ await render(
+ <template>
+ <DashboardDateRangePicker
+ @from={{state.from}}
+ @to={{state.to}}
+ @presets={{ALL_PRESETS}}
+ @onApply={{state.apply}}
+ @onCancel={{state.cancel}}
+ />
+ </template>
+ );
+
+ await click(dayButton("2026-05-01"));
+ await click(dayButton("2026-05-20"));
+ await click(dayButton("2026-05-10"));
+
+ assert
+ .dom(dayButton("2026-05-10"))
+ .hasClass("--start", "the third click becomes the new pending start");
+ assert
+ .dom(dayButton("2026-05-01"))
+ .doesNotHaveClass(
+ "--start",
+ "the previous pending start is cleared on a third click"
+ );
+ assert
+ .dom(dayButton("2026-05-20"))
+ .doesNotHaveClass(
+ "--end",
+ "the previous pending end is cleared on a third click"
+ );
+ assert
+ .dom(".d-date-range-picker__apply")
+ .isDisabled("Apply is disabled while only a new pending start is set");
+ });
+
+ 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());
+
+ await render(
+ <template>
+ <DashboardDateRangePicker
+ @from={{state.from}}
+ @to={{state.to}}
+ @presets={{ALL_PRESETS}}
+ @onApply={{state.apply}}
+ @onCancel={{state.cancel}}
+ />
+ </template>
+ );
+
+ await click(dayButton(from));
+ await click(dayButton(to));
+
+ assert
+ .dom(".d-date-range-picker__apply")
+ .isDisabled(
+ "Apply is disabled because the picked range matches the active range"
+ );
+ });
+
+ 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());
+
+ await render(
+ <template>
+ <DashboardDateRangePicker
+ @from={{state.from}}
+ @to={{state.to}}
+ @presets={{ALL_PRESETS}}
+ @onApply={{state.apply}}
+ @onCancel={{state.cancel}}
+ />
+ </template>
+ );
+
+ 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"
+ );
+ });
+
+ 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());
+
+ await render(
+ <template>
+ <DashboardDateRangePicker
+ @from={{state.from}}
+ @to={{state.to}}
+ @presets={{ALL_PRESETS}}
+ @onApply={{state.apply}}
+ @onCancel={{state.cancel}}
+ />
+ </template>
+ );
+
+ assert.dom(dayButton("2026-05-27")).isDisabled("tomorrow is disabled");
+ assert
+ .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);
+
+ let clock;
+
+ hooks.beforeEach(function () {
+ clock = fakeTime(TODAY, null, true);
+ });
+
+ hooks.afterEach(function () {
+ clock?.restore();
+ });
+
+ 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("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
+ );
+ assert.strictEqual(
+ matchingPreset(
+ moment(from).subtract(1, "day").toDate(),
+ to.toDate(),
+ ALL_PRESETS
+ ),
+ null,
+ "an off-by-one range does not match a preset"
+ );
+ });
+ }
+);
+
+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.gjs
index c08f7f21efa..90bcc38e0b4 100644
--- a/frontend/discourse/tests/integration/components/dashboard/date-range-test.gjs
+++ b/frontend/discourse/tests/integration/components/dashboard/date-range-test.gjs
@@ -1,5 +1,5 @@
import { tracked } from "@glimmer/tracking";
-import { click, render, settled } from "@ember/test-helpers";
+import { render, settled } from "@ember/test-helpers";
import { module, test } from "qunit";
import DashboardDateRange, {
calculatePresetStartDate,
@@ -10,31 +10,28 @@ import { withFrozenTime } from "discourse/tests/helpers/qunit-helpers";
module("Integration | Component | Dashboard | DateRange", function (hooks) {
setupRenderingTest(hooks);
- test("renders all four items in the segmented control", async function (assert) {
+ test("renders a single trigger that opens the picker", async function (assert) {
await render(
<template><DashboardDateRange @period="last_30_days" /></template>
);
- assert.dom("input[value='last_7_days']").exists("renders Last 7 days");
- assert.dom("input[value='last_30_days']").exists("renders Last 30 days");
- assert.dom("input[value='last_3_months']").exists("renders Last 3 months");
- assert.dom("input[value='custom']").exists("renders Custom");
+ assert
+ .dom(".db-date-range__trigger")
+ .exists("a single trigger is rendered");
+ assert
+ .dom(".db-segmented-control")
+ .doesNotExist("no segmented control is rendered");
});
- test("checks the input matching @period", async function (assert) {
+ test("trigger label is the preset name when a top-tier preset is active", async function (assert) {
await render(
- <template><DashboardDateRange @period="last_7_days" /></template>
+ <template><DashboardDateRange @period="last_30_days" /></template>
);
- assert
- .dom("input[value='last_7_days']")
- .isChecked("active preset is checked");
- assert
- .dom("input[value='last_30_days']")
- .isNotChecked("inactive preset is not checked");
+ assert.dom(".db-date-range__trigger-label").hasText("Last 30 days");
});
- test("checks the custom input when @period is 'custom'", async function (assert) {
+ 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");
@@ -48,65 +45,15 @@ module("Integration | Component | Dashboard | DateRange", function (hooks) {
</template>
);
- assert.dom("input[value='custom']").isChecked();
+ assert.dom(".db-date-range__trigger-label").includesText("Mar 1");
+ assert.dom(".db-date-range__trigger-label").includesText("Apr 28");
});
- test("calls @setPeriod when a preset is clicked", async function (assert) {
- const calls = [];
- const setPeriod = (period) => calls.push(period);
-
- await render(
- <template>
- <DashboardDateRange @period="last_30_days" @setPeriod={{setPeriod}} />
- </template>
- );
-
- await click("input[value='last_7_days']");
- assert.deepEqual(calls, ["last_7_days"], "fires with the chosen value");
- });
-
- 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"
- );
- });
- });
-
- test("does not call @setPeriod when the custom item is clicked", async function (assert) {
- const calls = [];
- const setPeriod = (period) => calls.push(period);
-
- await render(
- <template>
- <DashboardDateRange @period="last_30_days" @setPeriod={{setPeriod}} />
- </template>
- );
-
- await click(".db-date-range__custom");
- assert.deepEqual(calls, [], "custom does not change preset state");
- });
-
- test("custom item label is 'Custom' when not in custom mode", async function (assert) {
- await render(
- <template><DashboardDateRange @period="last_30_days" /></template>
- );
-
- assert.dom(".db-date-range__custom").includesText("Custom");
- });
-
- test("custom item label shows the formatted range when in custom mode", async function (assert) {
- const start = new Date("2026-03-01");
- const end = new Date("2026-04-28");
+ 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");
await render(
<template>
@@ -118,17 +65,21 @@ module("Integration | Component | Dashboard | DateRange", function (hooks) {
</template>
);
- assert.dom(".db-date-range__custom").includesText("Mar 1");
- assert.dom(".db-date-range__custom").includesText("Apr 28");
+ 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");
});
- test("custom item label falls back to 'Custom' when dates are missing", async function (assert) {
+ test("trigger label falls back to default when in custom mode with missing dates", async function (assert) {
await render(<template><DashboardDateRange @period="custom" /></template>);
- assert.dom(".db-date-range__custom").includesText("Custom");
+ assert.dom(".db-date-range__trigger-label").hasText("Last 30 days");
});
- test("checked state on custom toggles when @period changes", async function (assert) {
+ test("trigger label reacts to @period changes", async function (assert) {
class State {
@tracked period = "last_30_days";
}
@@ -138,11 +89,28 @@ module("Integration | Component | Dashboard | DateRange", function (hooks) {
<template><DashboardDateRange @period={{state.period}} /></template>
);
- assert.dom("input[value='custom']").isNotChecked();
+ assert.dom(".db-date-range__trigger-label").hasText("Last 30 days");
- state.period = "custom";
+ state.period = "last_7_days";
await settled();
- assert.dom("input[value='custom']").isChecked();
+ 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.rb
index cb3554e6ced..4fa3ab5f346 100644
--- a/spec/system/admin_dashboard_redesign_spec.rb
+++ b/spec/system/admin_dashboard_redesign_spec.rb
@@ -51,5 +51,107 @@ describe "Admin Dashboard Redesign" do
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" do
+ freeze_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
+ end
+
+ it "Cancel closes the popover and leaves the active range unchanged" do
+ freeze_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
+ end
+
+ it "Esc closes the popover and leaves the active range unchanged" do
+ freeze_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
+ end
+
+ it "reopening the popover after dismissal starts in committed state with the active range" do
+ freeze_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
+ end
+
+ context "when on mobile", mobile: true do
+ it "renders as a bottom sheet and Cancel dismisses without applying" do
+ freeze_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
+ 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
end
end
diff --git a/spec/system/page_objects/pages/admin_dashboard.rb b/spec/system/page_objects/pages/admin_dashboard.rb
index 73b77d42fd1..23c2897a743 100644
--- a/spec/system/page_objects/pages/admin_dashboard.rb
+++ b/spec/system/page_objects/pages/admin_dashboard.rb
@@ -32,23 +32,60 @@ module PageObjects
end
def has_active_period?(period)
- has_css?(".db-date-range input[value='#{period}']:checked")
+ if period == "custom"
+ page.current_url.include?("range=custom")
+ else
+ has_css?(".db-date-range__trigger-label", text: preset_label(period))
+ end
end
def select_preset(period)
- find(".db-date-range label", text: preset_label(period)).click
+ open_custom_date_range
+ find(".d-date-range-picker__preset", text: preset_label(period)).click
self
end
def has_custom_label_text?(text)
- has_css?(".db-date-range__custom", text: text)
+ has_css?(".db-date-range__trigger-label", text: text)
end
def open_custom_date_range
- find(".db-date-range__custom").click
+ find(".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
+ 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
+ self
+ end
+
+ 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