A local-first personal finance app
[AI]: Replacing month picker with day picker (#8427)
tabedzkife363a264388
diff --git a/packages/component-library/package.json b/packages/component-library/package.jsonindex 86e5f7c444..60635f9f75 100644--- a/packages/component-library/package.json+++ b/packages/component-library/package.json@@ -3,7 +3,16 @@"version": "0.0.1","license": "MIT","imports": {- "#tokens": "./src/tokens.ts"+ "#tokens": "./src/tokens.ts",+ "#Button": "./src/Button.tsx",+ "#ModeButton": "./src/ModeButton.tsx",+ "#Popover": "./src/Popover.tsx",+ "#styles": "./src/styles.ts",+ "#Text": "./src/Text.tsx",+ "#theme": "./src/theme.ts",+ "#View": "./src/View.tsx",+ "#hooks/*": "./src/hooks/*.ts",+ "#icons/v1": "./src/icons/v1/index.ts"},"exports": {"./hooks/*": "./src/hooks/*.ts",@@ -23,6 +32,7 @@"./input": "./src/Input.tsx","./label": "./src/Label.tsx","./menu": "./src/Menu.tsx",+ "./mode-button": "./src/ModeButton.tsx","./paragraph": "./src/Paragraph.tsx","./popover": "./src/Popover.tsx","./select": "./src/Select.tsx",@@ -39,7 +49,8 @@"./toggle": "./src/Toggle.tsx","./tooltip": "./src/Tooltip.tsx","./view": "./src/View.tsx",- "./color-picker": "./src/ColorPicker.tsx"+ "./color-picker": "./src/ColorPicker.tsx",+ "./date-range-picker": "./src/DateRangePicker.tsx"},"scripts": {"generate:icons": "rm src/icons/*/*.tsx; cd src/icons && svgr --template template.ts --index-template index-template.ts --typescript --expand-props start -d . .",@@ -50,6 +61,7 @@},"dependencies": {"@emotion/css": "^11.13.5",+ "@internationalized/date": "^3.12.2","react-aria-components": "^1.18.0","usehooks-ts": "^3.1.1"},diff --git a/packages/component-library/src/DateRangePicker.stories.tsx b/packages/component-library/src/DateRangePicker.stories.tsxnew file mode 100644index 0000000000..78a4dc5aa5--- /dev/null+++ b/packages/component-library/src/DateRangePicker.stories.tsx@@ -0,0 +1,79 @@+import { useState } from 'react';++import type { Meta, StoryObj } from '@storybook/react-vite';+import { fn } from 'storybook/test';++import type { DateRangePickerLabels } from './date-range-picker/util';+import { DateRangePicker } from './DateRangePicker';++const labels: DateRangePickerLabels = {+ selectBy: 'Select by',+ quickSelect: 'Quick select',+ month: 'Month',+ day: 'Day',+ previous: 'Previous',+ next: 'Next',+ previousMonth: 'Previous month',+ nextMonth: 'Next month',+ year: 'Year',+ dateRange: 'Date range',+};++const meta = {+ title: 'Components/DateRangePicker',+ component: DateRangePicker,+ parameters: {+ layout: 'centered',+ },+ args: {+ start: '2024-02',+ end: '2024-06',+ minDate: '2022-01',+ maxDate: '2025-12',+ locale: 'en-US',+ labels,+ onChangeDates: fn(),+ },+ tags: ['autodocs'],+} satisfies Meta<typeof DateRangePicker>;++export default meta;++type Story = StoryObj<typeof meta>;++export const MonthsOnly: Story = {};++export const WithDayGranularity: Story = {+ args: {+ granularities: ['month', 'day'],+ },+};++export const WithPresets: Story = {+ render: args => {+ const [range, setRange] = useState({ start: args.start, end: args.end });+ return (+ <DateRangePicker+ {...args}+ start={range.start}+ end={range.end}+ granularities={['month', 'day']}+ presets={[+ {+ key: '3-months',+ label: '3 months',+ getRange: () => ['2024-04', '2024-06'],+ onSelect: () => setRange({ start: '2024-04', end: '2024-06' }),+ },+ {+ key: '1-year',+ label: '1 year',+ getRange: () => ['2023-07', '2024-06'],+ onSelect: () => setRange({ start: '2023-07', end: '2024-06' }),+ },+ ]}+ onChangeDates={(start, end) => setRange({ start, end })}+ />+ );+ },+};diff --git a/packages/component-library/src/DateRangePicker.tsx b/packages/component-library/src/DateRangePicker.tsxnew file mode 100644index 0000000000..1992f3b3ba--- /dev/null+++ b/packages/component-library/src/DateRangePicker.tsx@@ -0,0 +1,306 @@+import { useRef, useState } from 'react';++import { Button } from '#Button';+import { useResponsive } from '#hooks/useResponsive';+import { Popover } from '#Popover';+import type { CSSProperties } from '#styles';+import { Text } from '#Text';+import { theme } from '#theme';+import { View } from '#View';++import { DayRangeCalendar } from './date-range-picker/DayRangeCalendar';+import { GranularityToggle } from './date-range-picker/GranularityToggle';+import { RangeSelector } from './date-range-picker/RangeSelector';+import {+ clamp,+ currentDay,+ currentMonth,+ firstDayOfMonth,+ formatDate,+ getMonth,+ lastDayOfMonth,+ valueIsDay,+} from './date-range-picker/util';+import type {+ DateRangeGranularity,+ DateRangePickerLabels,+ DateRangePreset,+ FirstDayOfWeek,+} from './date-range-picker/util';++export type {+ DateRangeGranularity,+ DateRangePickerLabels,+ DateRangePreset,+ FirstDayOfWeek,+} from './date-range-picker/util';++type DateRangePickerProps = {+ start: string;+ end: string;+ /** Inclusive lower bound (`yyyy-MM` or `yyyy-MM-dd`). */+ minDate: string;+ /** Inclusive upper bound; omit for no upper limit. */+ maxDate?: string;+ /** Pass `['month', 'day']` for callers that handle day-shaped values. */+ granularities?: DateRangeGranularity[];+ presets?: DateRangePreset[];+ firstDayOfWeek?: FirstDayOfWeek;+ /** BCP 47 language tag driving all date formatting. */+ locale: string;+ /**+ * Formats a `yyyy-MM-dd` value for the trigger label; falls back to a+ * locale-numeric date. Pass this when the app has its own date format.+ */+ formatDayLabel?: (date: string) => string;+ labels: DateRangePickerLabels;+ onChangeDates: (start: string, end: string) => void;+};++// Far-future sentinel: sorts after any real date string.+const NO_MAX = '9999-12-31';++const sectionTitleStyle = {+ fontWeight: 'bold',+ marginBottom: 8,+ fontSize: 12,+ textTransform: 'uppercase',+ color: theme.pageTextSubdued,+} satisfies CSSProperties;++export function DateRangePicker({+ start,+ end,+ minDate,+ maxDate,+ granularities = ['month'],+ presets,+ firstDayOfWeek = 'sun',+ locale,+ formatDayLabel,+ labels,+ onChangeDates,+}: DateRangePickerProps) {+ const effectiveMax = maxDate ?? NO_MAX;+ const triggerRef = useRef<HTMLButtonElement>(null);+ const [isOpen, setIsOpen] = useState(false);+ const { isNarrowWidth } = useResponsive();++ const allowsDay = granularities.includes('day');+ const showGranularityToggle = allowsDay && granularities.includes('month');++ // Edit a local draft while open; the caller only recomputes on commit. The+ // draft's shape encodes the granularity, so it survives the remounts that+ // callers with a loading early-return cause on every commit.+ const [draftStart, setDraftStart] = useState(start);+ const [draftEnd, setDraftEnd] = useState(end);+ // The preset behind the current draft; its onSelect commits on close so the+ // caller keeps the preset's semantics (e.g. a live range) over a plain+ // static range. Cleared by any manual edit.+ const [draftPreset, setDraftPreset] = useState<DateRangePreset | null>(null);+ const isDay = allowsDay && valueIsDay(draftStart);+ // Guards against committing twice when the trigger button and the popover's+ // close event both fire.+ const skipCommitRef = useRef(false);++ // Normalize the bounds to each granularity once: month-shaped bounds widen+ // to whole months in day mode, day-shaped bounds stay exact. A month-shaped+ // cap that reaches the current month would otherwise widen to that month's+ // last day, allowing days after today.+ const monthMin = getMonth(minDate);+ const monthMax = getMonth(effectiveMax);+ const dayMin = valueIsDay(minDate) ? minDate : firstDayOfMonth(minDate);+ const dayMax =+ monthMax === currentMonth()+ ? currentDay()+ : valueIsDay(effectiveMax)+ ? effectiveMax+ : lastDayOfMonth(effectiveMax);++ function openPopover() {+ if (allowsDay && valueIsDay(start)) {+ setDraftStart(start);+ setDraftEnd(end);+ } else {+ setDraftStart(getMonth(start));+ setDraftEnd(getMonth(end));+ }+ setDraftPreset(null);+ skipCommitRef.current = false;+ setIsOpen(true);+ }++ function changeGranularity(next: DateRangeGranularity) {+ if (next === (isDay ? 'day' : 'month')) return;+ // Only reshape the draft; committing here recomputes the caller's view,+ // which can unmount this picker and close the popover. Commit on close.+ setDraftStart(+ next === 'day'+ ? clamp(firstDayOfMonth(draftStart), dayMin, dayMax)+ : getMonth(draftStart),+ );+ setDraftEnd(+ next === 'day'+ ? clamp(lastDayOfMonth(draftEnd), dayMin, dayMax)+ : getMonth(draftEnd),+ );+ setDraftPreset(null);+ }++ function closeAndCommit() {+ setIsOpen(false);+ if (skipCommitRef.current) {+ return;+ }+ skipCommitRef.current = true;+ if (draftPreset) {+ draftPreset.onSelect();+ } else if (draftStart !== start || draftEnd !== end) {+ onChangeDates(draftStart, draftEnd);+ }+ }++ const hasSidebar = showGranularityToggle || Boolean(presets?.length);++ function setDraft(nextStart: string, nextEnd: string) {+ // Keep the range ordered regardless of which grid the user clicked.+ if (nextStart > nextEnd) {+ [nextStart, nextEnd] = [nextEnd, nextStart];+ }+ setDraftStart(nextStart);+ setDraftEnd(nextEnd);+ setDraftPreset(null);+ }++ const shownStart = isOpen ? draftStart : start;+ const shownEnd = isOpen ? draftEnd : end;++ // Format by the values' actual shape; the committed values may be+ // day-shaped even when day mode is off.+ const formatLabel = (value: string) =>+ valueIsDay(value)+ ? (formatDayLabel?.(value) ??+ formatDate(value, locale, {+ year: 'numeric',+ month: 'numeric',+ day: 'numeric',+ }))+ : formatDate(value, locale, { month: 'short', year: 'numeric' });+ const label = `${formatLabel(shownStart)} – ${formatLabel(shownEnd)}`;++ return (+ <View>+ <Button+ ref={triggerRef}+ data-testid="date-range-picker-trigger"+ onPress={() => (isOpen ? closeAndCommit() : openPopover())}+ >+ {label}+ </Button>++ <Popover+ triggerRef={triggerRef}+ placement="bottom start"+ isOpen={isOpen}+ onOpenChange={nextOpen => {+ if (!nextOpen) {+ closeAndCommit();+ }+ }}+ style={{ padding: 0 }}+ >+ <View style={{ flexDirection: isNarrowWidth ? 'column' : 'row' }}>+ <View+ style={{+ padding: 15,+ ...(hasSidebar &&+ (isNarrowWidth+ ? { borderBottom: `1px solid ${theme.tableBorder}` }+ : { borderRight: `1px solid ${theme.tableBorder}` })),+ }}+ >+ {isDay ? (+ <DayRangeCalendar+ start={draftStart}+ end={draftEnd}+ min={dayMin}+ max={dayMax}+ firstDayOfWeek={firstDayOfWeek}+ locale={locale}+ labels={labels}+ onChange={setDraft}+ />+ ) : (+ <RangeSelector+ start={draftStart}+ end={draftEnd}+ min={monthMin}+ max={monthMax}+ locale={locale}+ labels={labels}+ onChange={setDraft}+ />+ )}+ </View>++ {hasSidebar && (+ <View style={{ padding: 15, minWidth: 140, gap: 16 }}>+ {showGranularityToggle && (+ <View>+ <Text style={sectionTitleStyle}>{labels.selectBy}</Text>+ <GranularityToggle+ value={isDay ? 'day' : 'month'}+ monthLabel={labels.month}+ dayLabel={labels.day}+ onChange={changeGranularity}+ />+ </View>+ )}++ {Boolean(presets?.length) && (+ <View>+ <Text style={sectionTitleStyle}>{labels.quickSelect}</Text>+ <View style={{ gap: 4 }}>+ {presets?.map(preset => {+ // Derive the active preset from the shown range instead+ // of storing it, so it survives closing and reopening+ // without persisting anything.+ const [presetStart, presetEnd] = preset.getRange();+ const isActive =+ presetStart === draftStart && presetEnd === draftEnd;+ return (+ <Button+ key={preset.key}+ variant={isActive ? 'primary' : 'bare'}+ aria-pressed={isActive}+ onPress={() => {+ // Preview in the draft; the commit happens on+ // close, like manual selection.+ setDraftStart(presetStart);+ setDraftEnd(presetEnd);+ setDraftPreset(preset);+ }}+ style={{+ justifyContent: 'flex-start',+ fontSize: 13,+ // Match primary's 1px border so toggling the+ // active preset doesn't shift the list.+ ...(!isActive && {+ border: '1px solid transparent',+ }),+ }}+ >+ {preset.label}+ </Button>+ );+ })}+ </View>+ </View>+ )}+ </View>+ )}+ </View>+ </Popover>+ </View>+ );+}diff --git a/packages/component-library/src/ModeButton.stories.tsx b/packages/component-library/src/ModeButton.stories.tsxnew file mode 100644index 0000000000..2951acc132--- /dev/null+++ b/packages/component-library/src/ModeButton.stories.tsx@@ -0,0 +1,66 @@+import { useState } from 'react';++import type { Meta, StoryObj } from '@storybook/react-vite';+import { fn } from 'storybook/test';++import { ModeButton } from './ModeButton';+import { View } from './View';++const meta = {+ title: 'Components/ModeButton',+ component: ModeButton,+ parameters: {+ layout: 'centered',+ },+ args: {+ children: 'Monthly',+ onSelect: fn(),+ },+ tags: ['autodocs'],+} satisfies Meta<typeof ModeButton>;++export default meta;++type Story = StoryObj<typeof meta>;++export const Unselected: Story = {+ args: {+ selected: false,+ },+};++export const Selected: Story = {+ args: {+ selected: true,+ },+};++export const ModeGroup: Story = {+ args: {+ selected: false,+ },+ render: function Render() {+ const [mode, setMode] = useState('Monthly');++ return (+ <View style={{ flexDirection: 'row', gap: 4 }}>+ {['Monthly', 'Yearly', 'All time'].map(label => (+ <ModeButton+ key={label}+ selected={mode === label}+ onSelect={() => setMode(label)}+ >+ {label}+ </ModeButton>+ ))}+ </View>+ );+ },+ parameters: {+ docs: {+ description: {+ story: 'A group of mode buttons acting as an exclusive choice.',+ },+ },+ },+};diff --git a/packages/desktop-client/src/components/reports/ModeButton.tsx b/packages/component-library/src/ModeButton.tsxsimilarity index 80%rename from packages/desktop-client/src/components/reports/ModeButton.tsxrename to packages/component-library/src/ModeButton.tsxindex a12360850d..320787fbaf 100644--- a/packages/desktop-client/src/components/reports/ModeButton.tsx+++ b/packages/component-library/src/ModeButton.tsx@@ -1,11 +1,11 @@-import React from 'react';import type { ReactNode } from 'react';-import { Button } from '@actual-app/components/button';-import type { CSSProperties } from '@actual-app/components/styles';-import { theme } from '@actual-app/components/theme';import { css } from '@emotion/css';+import { Button } from '#Button';+import type { CSSProperties } from '#styles';+import { theme } from '#theme';+type ModeButtonProps = {selected: boolean;children: ReactNode;diff --git a/packages/component-library/src/date-range-picker/DayRangeCalendar.tsx b/packages/component-library/src/date-range-picker/DayRangeCalendar.tsxnew file mode 100644index 0000000000..199d9fb2f3--- /dev/null+++ b/packages/component-library/src/date-range-picker/DayRangeCalendar.tsx@@ -0,0 +1,200 @@+import {+ Button as AriaButton,+ CalendarCell,+ CalendarGrid,+ CalendarGridBody,+ CalendarGridHeader,+ CalendarHeaderCell,+ CalendarMonthPicker,+ I18nProvider,+ RangeCalendar,+} from 'react-aria-components';++import { css } from '@emotion/css';+import { parseDate } from '@internationalized/date';++import { SvgCheveronLeft, SvgCheveronRight } from '#icons/v1';+import type { CSSProperties } from '#styles';+import { theme } from '#theme';+import { View } from '#View';++import type { DateRangePickerLabels, FirstDayOfWeek } from './util';+import { YearSelect } from './YearSelect';++const calendarStyles: CSSProperties = {+ // A definite width so the header and the percentage-sized grid line up;+ // a 100%-wide table inside the shrink-to-fit popover blows up otherwise.+ width: 260,+ '& .calendar-header': {+ display: 'flex',+ flexDirection: 'row',+ alignItems: 'center',+ justifyContent: 'space-between',+ gap: 4,+ marginBottom: 10,+ '& button': {+ color: 'inherit',+ background: 'none',+ border: 'none',+ borderRadius: 4,+ padding: 5,+ cursor: 'pointer',+ display: 'flex',+ '&:hover': { backgroundColor: theme.buttonBareBackgroundHover },+ '&[disabled]': { opacity: 0.4, cursor: 'default' },+ },+ '& select': {+ color: 'inherit',+ background: 'none',+ border: 'none',+ borderRadius: 4,+ padding: 4,+ fontWeight: 'bold',+ fontSize: 13,+ cursor: 'pointer',+ '&:hover': { backgroundColor: theme.buttonBareBackgroundHover },+ // The open dropdown paints the browser's default (light) popup, so+ // inherited light text is invisible without explicit option colors.+ '& option': {+ backgroundColor: theme.tooltipBackground,+ color: theme.tooltipText,+ },+ },+ },+ '& .react-aria-CalendarGrid': {+ borderCollapse: 'collapse',+ // Stretch to the header's width (month/year selects) with equal columns.+ width: '100%',+ tableLayout: 'fixed',+ },+ '& .react-aria-CalendarHeaderCell': {+ color: theme.pageTextSubdued,+ fontSize: 10,+ fontWeight: 'bold',+ textAlign: 'center',+ padding: '2px 0',+ },+ '& .react-aria-CalendarCell': {+ minWidth: 28,+ height: 28,+ lineHeight: '28px',+ textAlign: 'center',+ fontSize: 12,+ cursor: 'pointer',+ '&[data-outside-month]': {+ display: 'none',+ },+ '&[data-hovered]': {+ backgroundColor: theme.buttonBareBackgroundHover,+ borderRadius: 4,+ },+ // Same current-day treatment as the month grid's GridButton.+ '&[data-today]': {+ fontWeight: 'bold',+ boxShadow: `inset 0 0 0 1px ${theme.pageTextPositive}`,+ borderRadius: 4,+ color: theme.pageTextPositive,+ },+ '&[data-selected]': {+ backgroundColor: theme.datePickerRangeBackground,+ borderRadius: 0,+ },+ '&[data-selection-start], &[data-selection-end]': {+ backgroundColor: theme.buttonPrimaryBackground,+ color: theme.buttonPrimaryText,+ },+ '&[data-selection-start]': {+ borderRadius: '4px 0 0 4px',+ },+ '&[data-selection-end]': {+ borderRadius: '0 4px 4px 0',+ },+ '&[data-disabled]': {+ opacity: 0.4,+ cursor: 'default',+ },+ '&[data-focus-visible]': {+ outline: `2px solid ${theme.buttonPrimaryBackground}`,+ outlineOffset: -2,+ },+ },+};++const calendarClassName = css(calendarStyles);++type DayRangeCalendarProps = {+ /** Inclusive day-shaped (`yyyy-MM-dd`) range and bounds. */+ start: string;+ end: string;+ min: string;+ max: string;+ firstDayOfWeek: FirstDayOfWeek;+ locale: string;+ labels: Pick<+ DateRangePickerLabels,+ 'dateRange' | 'previousMonth' | 'nextMonth' | 'year'+ >;+ onChange: (start: string, end: string) => void;+};++/** Day-granularity range calendar with month/year dropdowns in the header. */+export function DayRangeCalendar({+ start,+ end,+ min,+ max,+ firstDayOfWeek,+ locale,+ labels,+ onChange,+}: DayRangeCalendarProps) {+ return (+ <View className={calendarClassName}>+ <I18nProvider locale={locale}>+ <RangeCalendar+ aria-label={labels.dateRange}+ value={{ start: parseDate(start), end: parseDate(end) }}+ minValue={parseDate(min)}+ maxValue={parseDate(max)}+ firstDayOfWeek={firstDayOfWeek}+ onChange={range =>+ onChange(range.start.toString(), range.end.toString())+ }+ >+ <View className="calendar-header">+ <AriaButton slot="previous" aria-label={labels.previousMonth}>+ <SvgCheveronLeft width={16} height={16} />+ </AriaButton>+ <CalendarMonthPicker format="long">+ {({ 'aria-label': ariaLabel, value, onChange, items }) => (+ <select+ aria-label={ariaLabel}+ value={value as number}+ onChange={e => onChange(Number(e.target.value))}+ >+ {items.map(item => (+ <option key={item.id} value={item.id}>+ {item.formatted}+ </option>+ ))}+ </select>+ )}+ </CalendarMonthPicker>+ <YearSelect label={labels.year} />+ <AriaButton slot="next" aria-label={labels.nextMonth}>+ <SvgCheveronRight width={16} height={16} />+ </AriaButton>+ </View>+ <CalendarGrid weekdayStyle="narrow">+ <CalendarGridHeader>+ {day => <CalendarHeaderCell>{day}</CalendarHeaderCell>}+ </CalendarGridHeader>+ <CalendarGridBody>+ {date => <CalendarCell date={date} />}+ </CalendarGridBody>+ </CalendarGrid>+ </RangeCalendar>+ </I18nProvider>+ </View>+ );+}diff --git a/packages/component-library/src/date-range-picker/GranularityToggle.tsx b/packages/component-library/src/date-range-picker/GranularityToggle.tsxnew file mode 100644index 0000000000..f58842543a--- /dev/null+++ b/packages/component-library/src/date-range-picker/GranularityToggle.tsx@@ -0,0 +1,48 @@+import { ModeButton } from '#ModeButton';+import { theme } from '#theme';+import { View } from '#View';++import type { DateRangeGranularity } from './util';++const segmentStyle = { borderRadius: 0, fontSize: 12, padding: '4px 12px' };++type GranularityToggleProps = {+ value: DateRangeGranularity;+ monthLabel: string;+ dayLabel: string;+ onChange: (value: DateRangeGranularity) => void;+};++export function GranularityToggle({+ value,+ monthLabel,+ dayLabel,+ onChange,+}: GranularityToggleProps) {+ return (+ <View+ style={{+ flexDirection: 'row',+ border: `1px solid ${theme.buttonNormalBorder}`,+ borderRadius: 4,+ overflow: 'hidden',+ alignSelf: 'flex-start',+ }}+ >+ <ModeButton+ selected={value === 'month'}+ onSelect={() => onChange('month')}+ style={segmentStyle}+ >+ {monthLabel}+ </ModeButton>+ <ModeButton+ selected={value === 'day'}+ onSelect={() => onChange('day')}+ style={segmentStyle}+ >+ {dayLabel}+ </ModeButton>+ </View>+ );+}diff --git a/packages/component-library/src/date-range-picker/GridButton.tsx b/packages/component-library/src/date-range-picker/GridButton.tsxnew file mode 100644index 0000000000..8209135e22--- /dev/null+++ b/packages/component-library/src/date-range-picker/GridButton.tsx@@ -0,0 +1,71 @@+import type { ReactNode } from 'react';++import { Button } from '#Button';+import { theme } from '#theme';++import type { RangePosition } from './util';++type GridButtonProps = {+ selected: boolean;+ disabled: boolean;+ /** Marks the current month/day so it stands out even when not selected. */+ isToday?: boolean;+ /** Where the cell falls in the range band (or the hover preview). */+ position?: RangePosition;+ /** Full accessible name (e.g. the complete localized date). */+ label: string;+ onSelect: () => void;+ /** Called on pointer-enter to preview the range band. */+ onHover?: () => void;+ children: ReactNode;+};++export function GridButton({+ selected,+ disabled,+ isToday = false,+ position = null,+ label,+ onSelect,+ onHover,+ children,+}: GridButtonProps) {+ const inRange = position != null;+ const rangeEdge = position === 'middle' || position == null ? null : position;+ return (+ <Button+ variant={selected ? 'primary' : 'bare'}+ isDisabled={disabled}+ aria-label={label}+ aria-pressed={selected}+ onPress={onSelect}+ onHoverStart={onHover}+ style={{+ padding: '8px 4px',+ fontSize: 12,+ minWidth: 0,+ // Match the selected (primary) variant's 1px border so selecting a+ // cell doesn't resize the grid.+ ...(!selected && { border: '1px solid transparent' }),+ ...(isToday && {+ fontWeight: 'bold',+ // Inset ring marks the current period without shifting layout.+ boxShadow: `inset 0 0 0 1px ${theme.pageTextPositive}`,+ ...(!selected && { color: theme.pageTextPositive }),+ }),+ ...(inRange &&+ !selected && {+ backgroundColor: theme.datePickerRangeBackground,+ borderRadius:+ rangeEdge === 'start'+ ? '4px 0 0 4px'+ : rangeEdge === 'end'+ ? '0 4px 4px 0'+ : 0,+ }),+ }}+ >+ {children}+ </Button>+ );+}diff --git a/packages/component-library/src/date-range-picker/MonthGrid.tsx b/packages/component-library/src/date-range-picker/MonthGrid.tsxnew file mode 100644index 0000000000..fe4937044e--- /dev/null+++ b/packages/component-library/src/date-range-picker/MonthGrid.tsx@@ -0,0 +1,78 @@+import { useMemo } from 'react';++import { View } from '#View';++import { GridButton } from './GridButton';+import {+ currentMonth,+ formatDate,+ monthFromIndex,+ rangePosition,+} from './util';++type MonthGridProps = {+ year: string;+ rangeStart: string;+ rangeEnd: string;+ minMonth: string;+ maxMonth: string;+ /** BCP 47 language tag driving the month labels. */+ locale: string;+ onSelect: (month: string) => void;+ /** Called on pointer-enter of a cell to preview the range band. */+ onHover?: (month: string) => void;+};++export function MonthGrid({+ year,+ rangeStart,+ rangeEnd,+ minMonth,+ maxMonth,+ locale,+ onSelect,+ onHover,+}: MonthGridProps) {+ const thisMonth = currentMonth();+ // Manual memo: React Compiler doesn't cover this package, and this body+ // re-renders on every hover while a range is being picked.+ const months = useMemo(+ () =>+ Array.from({ length: 12 }, (_, i) => {+ const month = monthFromIndex(year, i);+ return {+ month,+ label: formatDate(month, locale, { month: 'short' }),+ fullLabel: formatDate(month, locale, {+ month: 'long',+ year: 'numeric',+ }),+ };+ }),+ [year, locale],+ );+ return (+ <View+ style={{+ display: 'grid',+ gridTemplateColumns: 'repeat(4, 1fr)',+ gap: 4,+ }}+ >+ {months.map(({ month, label, fullLabel }) => (+ <GridButton+ key={month}+ selected={month === rangeStart || month === rangeEnd}+ disabled={month < minMonth || month > maxMonth}+ isToday={month === thisMonth}+ position={rangePosition(month, rangeStart, rangeEnd)}+ label={fullLabel}+ onSelect={() => onSelect(month)}+ onHover={onHover ? () => onHover(month) : undefined}+ >+ {label}+ </GridButton>+ ))}+ </View>+ );+}diff --git a/packages/component-library/src/date-range-picker/NavRow.tsx b/packages/component-library/src/date-range-picker/NavRow.tsxnew file mode 100644index 0000000000..c0632c57af--- /dev/null+++ b/packages/component-library/src/date-range-picker/NavRow.tsx@@ -0,0 +1,53 @@+import { Button } from '#Button';+import { SvgCheveronLeft, SvgCheveronRight } from '#icons/v1';+import { Text } from '#Text';+import { View } from '#View';++type NavRowProps = {+ label: string;+ previousLabel: string;+ nextLabel: string;+ canPrev: boolean;+ canNext: boolean;+ onPrev: () => void;+ onNext: () => void;+};++export function NavRow({+ label,+ previousLabel,+ nextLabel,+ canPrev,+ canNext,+ onPrev,+ onNext,+}: NavRowProps) {+ return (+ <View+ style={{+ flexDirection: 'row',+ justifyContent: 'space-between',+ alignItems: 'center',+ marginBottom: 10,+ }}+ >+ <Button+ aria-label={previousLabel}+ variant="bare"+ isDisabled={!canPrev}+ onPress={onPrev}+ >+ <SvgCheveronLeft width={16} height={16} />+ </Button>+ <Text style={{ fontWeight: 'bold' }}>{label}</Text>+ <Button+ aria-label={nextLabel}+ variant="bare"+ isDisabled={!canNext}+ onPress={onNext}+ >+ <SvgCheveronRight width={16} height={16} />+ </Button>+ </View>+ );+}diff --git a/packages/component-library/src/date-range-picker/RangeSelector.tsx b/packages/component-library/src/date-range-picker/RangeSelector.tsxnew file mode 100644index 0000000000..6e50311b4e--- /dev/null+++ b/packages/component-library/src/date-range-picker/RangeSelector.tsx@@ -0,0 +1,92 @@+import { useState } from 'react';++import { View } from '#View';++import { MonthGrid } from './MonthGrid';+import { NavRow } from './NavRow';+import { getYear } from './util';+import type { DateRangePickerLabels } from './util';++type RangeSelectorProps = {+ /** Inclusive month-shaped (`yyyy-MM`) range and bounds. */+ start: string;+ end: string;+ min: string;+ max: string;+ locale: string;+ labels: Pick<DateRangePickerLabels, 'previous' | 'next'>;+ onChange: (start: string, end: string) => void;+};++/** Month grid for picking a range: one click anchors, a second click sets the other end. */+export function RangeSelector({+ start,+ end,+ min,+ max,+ locale,+ labels,+ onChange,+}: RangeSelectorProps) {+ const [viewYear, setViewYear] = useState(() => getYear(start));++ // When the range changes from outside (e.g. a quick-select preset) and the+ // shown year no longer touches it, jump to the range's start.+ const [prevRange, setPrevRange] = useState([start, end]);+ if (start !== prevRange[0] || end !== prevRange[1]) {+ setPrevRange([start, end]);+ if (viewYear < getYear(start) || viewYear > getYear(end)) {+ setViewYear(getYear(start));+ }+ }++ const [anchor, setAnchor] = useState<string | null>(null);+ const [hoverValue, setHoverValue] = useState<string | null>(null);++ function pick(cell: string) {+ if (anchor == null) {+ setAnchor(cell);+ onChange(cell, cell);+ } else {+ const [newStart, newEnd] =+ cell < anchor ? [cell, anchor] : [anchor, cell];+ onChange(newStart, newEnd);+ setAnchor(null);+ setHoverValue(null);+ }+ }++ // While picking a second end, preview the band against the hovered cell.+ const previewCell = hoverValue ?? anchor;+ const [bandStart, bandEnd] =+ anchor != null && previewCell != null+ ? previewCell < anchor+ ? [previewCell, anchor]+ : [anchor, previewCell]+ : [start, end];++ return (+ <View onMouseLeave={() => setHoverValue(null)} style={{ minWidth: 180 }}>+ <NavRow+ label={viewYear}+ previousLabel={labels.previous}+ nextLabel={labels.next}+ canPrev={viewYear > getYear(min)}+ canNext={viewYear < getYear(max)}+ onPrev={() => setViewYear(String(Number(viewYear) - 1))}+ onNext={() => setViewYear(String(Number(viewYear) + 1))}+ />++ <MonthGrid+ year={viewYear}+ rangeStart={bandStart}+ rangeEnd={bandEnd}+ minMonth={min}+ maxMonth={max}+ locale={locale}+ onSelect={pick}+ onHover={anchor ? setHoverValue : undefined}+ />+ </View>+ );+}diff --git a/packages/component-library/src/date-range-picker/RangeSelector.web.test.tsx b/packages/component-library/src/date-range-picker/RangeSelector.web.test.tsxnew file mode 100644index 0000000000..c2c7447f4d--- /dev/null+++ b/packages/component-library/src/date-range-picker/RangeSelector.web.test.tsx@@ -0,0 +1,32 @@+import { render, screen } from '@testing-library/react';++import { RangeSelector } from './RangeSelector';++const defaultProps = {+ min: '2020-01',+ max: '2030-12',+ locale: 'en-US',+ labels: { previous: 'Previous', next: 'Next' },+ onChange: () => {},+};++describe('RangeSelector', () => {+ it('jumps the shown year to a range set from outside it', () => {+ const { rerender } = render(+ <RangeSelector {...defaultProps} start="2025-01" end="2025-06" />,+ );+ expect(screen.getByText('2025')).toBeTruthy();++ // e.g. a quick-select preset picks a range in another year+ rerender(<RangeSelector {...defaultProps} start="2026-05" end="2026-07" />);+ expect(screen.getByText('2026')).toBeTruthy();+ });++ it('keeps the shown year when it already touches the new range', () => {+ const { rerender } = render(+ <RangeSelector {...defaultProps} start="2025-01" end="2025-06" />,+ );+ rerender(<RangeSelector {...defaultProps} start="2024-05" end="2025-03" />);+ expect(screen.getByText('2025')).toBeTruthy();+ });+});diff --git a/packages/component-library/src/date-range-picker/YearSelect.tsx b/packages/component-library/src/date-range-picker/YearSelect.tsxnew file mode 100644index 0000000000..40e9d6540d--- /dev/null+++ b/packages/component-library/src/date-range-picker/YearSelect.tsx@@ -0,0 +1,40 @@+import { useContext } from 'react';+import { RangeCalendarStateContext } from 'react-aria-components';++// react-aria's CalendarYearPicker windows its year list by stepping whole+// years from minValue, which drops maxValue's year whenever the range doesn't+// span full years — for a budget that's most of the time. Build the list from+// the bounds' years instead; setFocusedDate clamps to [minValue, maxValue].+export function YearSelect({ label }: { label: string }) {+ const state = useContext(RangeCalendarStateContext);+ if (!state) return null;+ const minYear = state.minValue?.year ?? state.focusedDate.year;+ // An omitted upper bound arrives as a far-future sentinel; don't render+ // thousands of year options for it. Keep the focused year listed so the+ // select stays valid when navigating past the cap via the arrow buttons.+ const maxYear = Math.min(+ state.maxValue?.year ?? state.focusedDate.year,+ Math.max(state.focusedDate.year, new Date().getFullYear() + 10),+ );+ const years = Array.from(+ { length: maxYear - minYear + 1 },+ (_, i) => minYear + i,+ );+ return (+ <select+ aria-label={label}+ value={state.focusedDate.year}+ onChange={e =>+ state.setFocusedDate(+ state.focusedDate.set({ year: Number(e.target.value) }),+ )+ }+ >+ {years.map(year => (+ <option key={year} value={year}>+ {year}+ </option>+ ))}+ </select>+ );+}diff --git a/packages/component-library/src/date-range-picker/util.ts b/packages/component-library/src/date-range-picker/util.tsnew file mode 100644index 0000000000..ff7f223fcd--- /dev/null+++ b/packages/component-library/src/date-range-picker/util.ts@@ -0,0 +1,141 @@+import type { ReactNode } from 'react';++import {+ endOfMonth,+ getLocalTimeZone,+ parseDate,+ today,+} from '@internationalized/date';++/**+ * Granularity the picker operates at: `month` values are `yyyy-MM`, `day`+ * values are `yyyy-MM-dd`. (A custom picker rather than a native+ * `<input type="month">`, which Firefox and Safari don't support.)+ */+export type DateRangeGranularity = 'month' | 'day';++export type DateRangePreset = {+ key: string;+ label: ReactNode;+ /** The range shown in the still-open picker when the preset is clicked. */+ getRange: () => [string, string];+ /** Commits the preset; called on close if it is still the selection. */+ onSelect: () => void;+};++/** All user-facing strings, translated by the caller. */+export type DateRangePickerLabels = {+ /** Heading above the granularity toggle, e.g. "Select by". */+ selectBy: string;+ /** Heading above the presets, e.g. "Quick select". */+ quickSelect: string;+ /** Granularity toggle segments. */+ month: string;+ day: string;+ /** Year navigation arrows in the month grid. */+ previous: string;+ next: string;+ /** Month navigation arrows in the day calendar. */+ previousMonth: string;+ nextMonth: string;+ /** Year dropdown in the day calendar header. */+ year: string;+ /** Accessible name of the day calendar. */+ dateRange: string;+};++export type FirstDayOfWeek =+ | 'sun'+ | 'mon'+ | 'tue'+ | 'wed'+ | 'thu'+ | 'fri'+ | 'sat';++// Whether a value is day-shaped (`yyyy-MM-dd`) rather than month-shaped+// (`yyyy-MM`).+export function valueIsDay(value: string): boolean {+ const match = /^(\d{4})-(\d{2})-(\d{2})$/.exec(value);+ if (!match) return false;+ const month = Number(match[2]);+ const day = Number(match[3]);+ return month >= 1 && month <= 12 && day >= 1 && day <= 31;+}++// Clamp an ISO date string to [min, max]; all three must share a granularity.+export function clamp(value: string, min: string, max: string): string {+ if (value < min) return min;+ if (value > max) return max;+ return value;+}++// Where a cell falls relative to a (start, end) range, for the band highlight.+export type RangePosition = 'start' | 'end' | 'middle' | null;++export function rangePosition(+ cell: string,+ start: string,+ end: string,+): RangePosition {+ if (cell < start || cell > end) return null;+ if (cell === start) return 'start';+ if (cell === end) return 'end';+ return 'middle';+}++// Plain string date helpers — the small loot-core/date-fns subset the picker+// needs, since the library can depend on neither. Built on Intl and the+// already-present `@internationalized/date`; values are local dates, never+// timezone-shifted.++function toDate(value: string): Date {+ const [year, month = 1, day = 1] = value.split('-').map(Number);+ return new Date(year, month - 1, day);+}++// Intl.DateTimeFormat construction is expensive and the picker uses only a+// handful of (locale, options) shapes, so cache the formatters.+const formatters = new Map<string, Intl.DateTimeFormat>();++export function formatDate(+ value: string,+ locale: string,+ options: Intl.DateTimeFormatOptions,+): string {+ const key = `${locale}|${JSON.stringify(options)}`;+ let formatter = formatters.get(key);+ if (!formatter) {+ formatter = new Intl.DateTimeFormat(locale, options);+ formatters.set(key, formatter);+ }+ return formatter.format(toDate(value));+}++export function getYear(value: string): string {+ return value.slice(0, 4);+}++export function getMonth(value: string): string {+ return value.slice(0, 7);+}++export function firstDayOfMonth(value: string): string {+ return `${getMonth(value)}-01`;+}++export function lastDayOfMonth(value: string): string {+ return endOfMonth(parseDate(firstDayOfMonth(value))).toString();+}++export function currentDay(): string {+ return today(getLocalTimeZone()).toString();+}++export function currentMonth(): string {+ return getMonth(currentDay());+}++export function monthFromIndex(year: string, index: number): string {+ return `${year}-${String(index + 1).padStart(2, '0')}`;+}diff --git a/packages/component-library/src/date-range-picker/util.web.test.ts b/packages/component-library/src/date-range-picker/util.web.test.tsnew file mode 100644index 0000000000..748e1b950c--- /dev/null+++ b/packages/component-library/src/date-range-picker/util.web.test.ts@@ -0,0 +1,90 @@+import { describe, expect, it } from 'vitest';++import {+ clamp,+ firstDayOfMonth,+ formatDate,+ lastDayOfMonth,+ monthFromIndex,+ rangePosition,+ valueIsDay,+} from './util';++describe('valueIsDay', () => {+ it('is false for month-shaped values', () => {+ expect(valueIsDay('2020-01')).toBe(false);+ });++ it('is true for day-shaped values', () => {+ expect(valueIsDay('2020-01-15')).toBe(true);+ });++ it('is false for empty or malformed values', () => {+ expect(valueIsDay('')).toBe(false);+ expect(valueIsDay('garbage')).toBe(false);+ expect(valueIsDay('2020-1-15')).toBe(false);+ expect(valueIsDay('2020-13-01')).toBe(false);+ expect(valueIsDay('2020-01-32')).toBe(false);+ });+});++describe('clamp', () => {+ it('leaves a value within bounds unchanged', () => {+ expect(clamp('2020-05', '2020-01', '2020-12')).toBe('2020-05');+ expect(clamp('2020-02-15', '2020-01-01', '2020-12-31')).toBe('2020-02-15');+ });++ it('clamps a value outside the bounds', () => {+ expect(clamp('2019-12', '2020-01', '2020-12')).toBe('2020-01');+ expect(clamp('2021-01', '2020-01', '2020-12')).toBe('2020-12');+ expect(clamp('2019-12-31', '2020-01-01', '2020-12-31')).toBe('2020-01-01');+ expect(clamp('2021-01-01', '2020-01-01', '2020-12-31')).toBe('2020-12-31');+ });+});++describe('rangePosition', () => {+ it('is null outside the range', () => {+ expect(rangePosition('2020-01', '2020-03', '2020-06')).toBe(null);+ expect(rangePosition('2020-08', '2020-03', '2020-06')).toBe(null);+ });++ it('marks the start and end edges', () => {+ expect(rangePosition('2020-03', '2020-03', '2020-06')).toBe('start');+ expect(rangePosition('2020-06', '2020-03', '2020-06')).toBe('end');+ });++ it('marks interior cells as middle', () => {+ expect(rangePosition('2020-04', '2020-03', '2020-06')).toBe('middle');+ });++ it('treats a single-cell range as start', () => {+ expect(rangePosition('2020-03', '2020-03', '2020-03')).toBe('start');+ });+});++describe('date helpers', () => {+ it('widens month values to their first and last day', () => {+ expect(firstDayOfMonth('2020-02')).toBe('2020-02-01');+ expect(lastDayOfMonth('2020-02')).toBe('2020-02-29');+ expect(lastDayOfMonth('2021-02-10')).toBe('2021-02-28');+ expect(lastDayOfMonth('2020-12')).toBe('2020-12-31');+ });++ it('builds months from a year and index', () => {+ expect(monthFromIndex('2020', 0)).toBe('2020-01');+ expect(monthFromIndex('2020', 11)).toBe('2020-12');+ });++ it('formats month- and day-shaped values without timezone shifts', () => {+ expect(+ formatDate('2020-01', 'en-US', { month: 'short', year: 'numeric' }),+ ).toBe('Jan 2020');+ expect(+ formatDate('2020-01-15', 'en-US', {+ year: 'numeric',+ month: 'numeric',+ day: 'numeric',+ }),+ ).toBe('1/15/2020');+ });+});diff --git a/packages/component-library/src/theme.ts b/packages/component-library/src/theme.tsindex fd5b759a75..873da230ed 100644--- a/packages/component-library/src/theme.ts+++ b/packages/component-library/src/theme.ts@@ -131,6 +131,7 @@ export const theme = {calendarItemText: 'var(--color-calendarItemText)',calendarItemBackground: 'var(--color-calendarItemBackground)',calendarSelectedBackground: 'var(--color-calendarSelectedBackground)',+ datePickerRangeBackground: 'var(--color-datePickerRangeBackground)',noticeBackground: 'var(--color-noticeBackground)',noticeBackgroundLight: 'var(--color-noticeBackgroundLight)',noticeBackgroundDark: 'var(--color-noticeBackgroundDark)',diff --git a/packages/component-library/src/themes/dark.css b/packages/component-library/src/themes/dark.cssindex 31c1e1ff3e..cbb3bdd0a7 100644--- a/packages/component-library/src/themes/dark.css+++ b/packages/component-library/src/themes/dark.css@@ -142,6 +142,7 @@--color-calendarSelectedBackground: var(--color-buttonNormalSelectedBackground);+ --color-datePickerRangeBackground: var(--palette-purple600);--color-buttonBareText: var(--color-pageText);--color-buttonBareTextHover: var(--color-pageText);diff --git a/packages/component-library/src/themes/light.css b/packages/component-library/src/themes/light.cssindex 5bb780de2a..b69618af77 100644--- a/packages/component-library/src/themes/light.css+++ b/packages/component-library/src/themes/light.css@@ -142,6 +142,7 @@--color-calendarItemText: var(--palette-navy150);--color-calendarItemBackground: var(--palette-navy800);--color-calendarSelectedBackground: var(--palette-navy500);+ --color-datePickerRangeBackground: var(--palette-purple150);--color-buttonBareText: var(--color-pageText);--color-buttonBareTextHover: var(--color-pageText);diff --git a/packages/component-library/src/themes/midnight.css b/packages/component-library/src/themes/midnight.cssindex d4d1f60061..71f26f450a 100644--- a/packages/component-library/src/themes/midnight.css+++ b/packages/component-library/src/themes/midnight.css@@ -143,6 +143,7 @@--color-calendarSelectedBackground: var(--color-buttonNormalSelectedBackground);+ --color-datePickerRangeBackground: var(--palette-purple600);--color-buttonBareText: var(--color-pageText);--color-buttonBareTextHover: var(--color-pageText);diff --git a/packages/desktop-client/e2e/reports.test.ts b/packages/desktop-client/e2e/reports.test.tsindex 8a57775766..c7a393d78e 100644--- a/packages/desktop-client/e2e/reports.test.ts+++ b/packages/desktop-client/e2e/reports.test.ts@@ -64,6 +64,18 @@ test.describe('Reports', () => {await expect(page).toMatchThemeScreenshots();});+ test('opens the date range picker and checks visuals', async () => {+ await reportsPage.goToNetWorthPage();++ await page.getByTestId('date-range-picker-trigger').click();+ const picker = page.locator('[data-popover]');+ await expect(picker).toMatchThemeScreenshots();++ // Switch to day granularity+ await picker.getByRole('button', { name: 'Day', exact: true }).click();+ await expect(picker).toMatchThemeScreenshots();+ });+test.describe('balance forecast', () => {test.beforeEach(async () => {const settingsPage = await navigation.goToSettingsPage();diff --git a/packages/desktop-client/e2e/reports.test.ts-snapshots/Reports-balance-forecast-loads-balance-forecast-report-with-monthly-granularity-1-chromium-linux.png b/packages/desktop-client/e2e/reports.test.ts-snapshots/Reports-balance-forecast-loads-balance-forecast-report-with-monthly-granularity-1-chromium-linux.pngindex 4cb6792ff2..ee144694fa 100644Binary files a/packages/desktop-client/e2e/reports.test.ts-snapshots/Reports-balance-forecast-loads-balance-forecast-report-with-monthly-granularity-1-chromium-linux.png and b/packages/desktop-client/e2e/reports.test.ts-snapshots/Reports-balance-forecast-loads-balance-forecast-report-with-monthly-granularity-1-chromium-linux.png differdiff --git a/packages/desktop-client/e2e/reports.test.ts-snapshots/Reports-balance-forecast-loads-balance-forecast-report-with-monthly-granularity-2-chromium-linux.png b/packages/desktop-client/e2e/reports.test.ts-snapshots/Reports-balance-forecast-loads-balance-forecast-report-with-monthly-granularity-2-chromium-linux.pngindex d5703db181..043c22c2a2 100644Binary files a/packages/desktop-client/e2e/reports.test.ts-snapshots/Reports-balance-forecast-loads-balance-forecast-report-with-monthly-granularity-2-chromium-linux.png and b/packages/desktop-client/e2e/reports.test.ts-snapshots/Reports-balance-forecast-loads-balance-forecast-report-with-monthly-granularity-2-chromium-linux.png differdiff --git a/packages/desktop-client/e2e/reports.test.ts-snapshots/Reports-balance-forecast-loads-balance-forecast-report-with-monthly-granularity-3-chromium-linux.png b/packages/desktop-client/e2e/reports.test.ts-snapshots/Reports-balance-forecast-loads-balance-forecast-report-with-monthly-granularity-3-chromium-linux.pngindex 035146321a..351758f4d1 100644Binary files a/packages/desktop-client/e2e/reports.test.ts-snapshots/Reports-balance-forecast-loads-balance-forecast-report-with-monthly-granularity-3-chromium-linux.png and b/packages/desktop-client/e2e/reports.test.ts-snapshots/Reports-balance-forecast-loads-balance-forecast-report-with-monthly-granularity-3-chromium-linux.png differdiff --git a/packages/desktop-client/e2e/reports.test.ts-snapshots/Reports-balance-forecast-loads-tracking-budget-forecast-report-1-chromium-linux.png b/packages/desktop-client/e2e/reports.test.ts-snapshots/Reports-balance-forecast-loads-tracking-budget-forecast-report-1-chromium-linux.pngindex a1f812b250..a0cf8962f8 100644Binary files a/packages/desktop-client/e2e/reports.test.ts-snapshots/Reports-balance-forecast-loads-tracking-budget-forecast-report-1-chromium-linux.png and b/packages/desktop-client/e2e/reports.test.ts-snapshots/Reports-balance-forecast-loads-tracking-budget-forecast-report-1-chromium-linux.png differdiff --git a/packages/desktop-client/e2e/reports.test.ts-snapshots/Reports-balance-forecast-loads-tracking-budget-forecast-report-2-chromium-linux.png b/packages/desktop-client/e2e/reports.test.ts-snapshots/Reports-balance-forecast-loads-tracking-budget-forecast-report-2-chromium-linux.pngindex 8291ecd524..55a63027b9 100644Binary files a/packages/desktop-client/e2e/reports.test.ts-snapshots/Reports-balance-forecast-loads-tracking-budget-forecast-report-2-chromium-linux.png and b/packages/desktop-client/e2e/reports.test.ts-snapshots/Reports-balance-forecast-loads-tracking-budget-forecast-report-2-chromium-linux.png differdiff --git a/packages/desktop-client/e2e/reports.test.ts-snapshots/Reports-balance-forecast-loads-tracking-budget-forecast-report-3-chromium-linux.png b/packages/desktop-client/e2e/reports.test.ts-snapshots/Reports-balance-forecast-loads-tracking-budget-forecast-report-3-chromium-linux.pngindex c57c9de29b..43de70506a 100644Binary files a/packages/desktop-client/e2e/reports.test.ts-snapshots/Reports-balance-forecast-loads-tracking-budget-forecast-report-3-chromium-linux.png and b/packages/desktop-client/e2e/reports.test.ts-snapshots/Reports-balance-forecast-loads-tracking-budget-forecast-report-3-chromium-linux.png differdiff --git a/packages/desktop-client/e2e/reports.test.ts-snapshots/Reports-balance-forecast-switches-to-daily-granularity-1-chromium-linux.png b/packages/desktop-client/e2e/reports.test.ts-snapshots/Reports-balance-forecast-switches-to-daily-granularity-1-chromium-linux.pngindex 99f0508c93..666ead65ea 100644Binary files a/packages/desktop-client/e2e/reports.test.ts-snapshots/Reports-balance-forecast-switches-to-daily-granularity-1-chromium-linux.png and b/packages/desktop-client/e2e/reports.test.ts-snapshots/Reports-balance-forecast-switches-to-daily-granularity-1-chromium-linux.png differdiff --git a/packages/desktop-client/e2e/reports.test.ts-snapshots/Reports-balance-forecast-switches-to-daily-granularity-2-chromium-linux.png b/packages/desktop-client/e2e/reports.test.ts-snapshots/Reports-balance-forecast-switches-to-daily-granularity-2-chromium-linux.pngindex 1f5928d691..acd534eab6 100644Binary files a/packages/desktop-client/e2e/reports.test.ts-snapshots/Reports-balance-forecast-switches-to-daily-granularity-2-chromium-linux.png and b/packages/desktop-client/e2e/reports.test.ts-snapshots/Reports-balance-forecast-switches-to-daily-granularity-2-chromium-linux.png differdiff --git a/packages/desktop-client/e2e/reports.test.ts-snapshots/Reports-balance-forecast-switches-to-daily-granularity-3-chromium-linux.png b/packages/desktop-client/e2e/reports.test.ts-snapshots/Reports-balance-forecast-switches-to-daily-granularity-3-chromium-linux.pngindex 7420be046d..74aa794c18 100644Binary files a/packages/desktop-client/e2e/reports.test.ts-snapshots/Reports-balance-forecast-switches-to-daily-granularity-3-chromium-linux.png and b/packages/desktop-client/e2e/reports.test.ts-snapshots/Reports-balance-forecast-switches-to-daily-granularity-3-chromium-linux.png differdiff --git a/packages/desktop-client/e2e/reports.test.ts-snapshots/Reports-loads-cash-flow-graph-and-checks-visuals-1-chromium-linux.png b/packages/desktop-client/e2e/reports.test.ts-snapshots/Reports-loads-cash-flow-graph-and-checks-visuals-1-chromium-linux.pngindex 9b0e734e33..27ad3d6b0f 100644Binary files a/packages/desktop-client/e2e/reports.test.ts-snapshots/Reports-loads-cash-flow-graph-and-checks-visuals-1-chromium-linux.png and b/packages/desktop-client/e2e/reports.test.ts-snapshots/Reports-loads-cash-flow-graph-and-checks-visuals-1-chromium-linux.png differdiff --git a/packages/desktop-client/e2e/reports.test.ts-snapshots/Reports-loads-cash-flow-graph-and-checks-visuals-2-chromium-linux.png b/packages/desktop-client/e2e/reports.test.ts-snapshots/Reports-loads-cash-flow-graph-and-checks-visuals-2-chromium-linux.pngindex b1ba3a8fa2..99189f10ef 100644Binary files a/packages/desktop-client/e2e/reports.test.ts-snapshots/Reports-loads-cash-flow-graph-and-checks-visuals-2-chromium-linux.png and b/packages/desktop-client/e2e/reports.test.ts-snapshots/Reports-loads-cash-flow-graph-and-checks-visuals-2-chromium-linux.png differdiff --git a/packages/desktop-client/e2e/reports.test.ts-snapshots/Reports-loads-cash-flow-graph-and-checks-visuals-3-chromium-linux.png b/packages/desktop-client/e2e/reports.test.ts-snapshots/Reports-loads-cash-flow-graph-and-checks-visuals-3-chromium-linux.pngindex b620d62c10..0a89726591 100644Binary files a/packages/desktop-client/e2e/reports.test.ts-snapshots/Reports-loads-cash-flow-graph-and-checks-visuals-3-chromium-linux.png and b/packages/desktop-client/e2e/reports.test.ts-snapshots/Reports-loads-cash-flow-graph-and-checks-visuals-3-chromium-linux.png differdiff --git a/packages/desktop-client/e2e/reports.test.ts-snapshots/Reports-loads-net-worth-graph-and-checks-visuals-1-chromium-linux.png b/packages/desktop-client/e2e/reports.test.ts-snapshots/Reports-loads-net-worth-graph-and-checks-visuals-1-chromium-linux.pngindex 0c15849b58..b194a6c016 100644Binary files a/packages/desktop-client/e2e/reports.test.ts-snapshots/Reports-loads-net-worth-graph-and-checks-visuals-1-chromium-linux.png and b/packages/desktop-client/e2e/reports.test.ts-snapshots/Reports-loads-net-worth-graph-and-checks-visuals-1-chromium-linux.png differdiff --git a/packages/desktop-client/e2e/reports.test.ts-snapshots/Reports-loads-net-worth-graph-and-checks-visuals-2-chromium-linux.png b/packages/desktop-client/e2e/reports.test.ts-snapshots/Reports-loads-net-worth-graph-and-checks-visuals-2-chromium-linux.pngindex e4cbe213b9..fda6a9897f 100644Binary files a/packages/desktop-client/e2e/reports.test.ts-snapshots/Reports-loads-net-worth-graph-and-checks-visuals-2-chromium-linux.png and b/packages/desktop-client/e2e/reports.test.ts-snapshots/Reports-loads-net-worth-graph-and-checks-visuals-2-chromium-linux.png differdiff --git a/packages/desktop-client/e2e/reports.test.ts-snapshots/Reports-loads-net-worth-graph-and-checks-visuals-3-chromium-linux.png b/packages/desktop-client/e2e/reports.test.ts-snapshots/Reports-loads-net-worth-graph-and-checks-visuals-3-chromium-linux.pngindex 7b0464a2c2..65abceb8a8 100644Binary files a/packages/desktop-client/e2e/reports.test.ts-snapshots/Reports-loads-net-worth-graph-and-checks-visuals-3-chromium-linux.png and b/packages/desktop-client/e2e/reports.test.ts-snapshots/Reports-loads-net-worth-graph-and-checks-visuals-3-chromium-linux.png differdiff --git a/packages/desktop-client/e2e/reports.test.ts-snapshots/Reports-opens-the-date-range-picker-and-checks-visuals-1-chromium-linux.png b/packages/desktop-client/e2e/reports.test.ts-snapshots/Reports-opens-the-date-range-picker-and-checks-visuals-1-chromium-linux.pngnew file mode 100644index 0000000000..bd22a82ceeBinary files /dev/null and b/packages/desktop-client/e2e/reports.test.ts-snapshots/Reports-opens-the-date-range-picker-and-checks-visuals-1-chromium-linux.png differdiff --git a/packages/desktop-client/e2e/reports.test.ts-snapshots/Reports-opens-the-date-range-picker-and-checks-visuals-2-chromium-linux.png b/packages/desktop-client/e2e/reports.test.ts-snapshots/Reports-opens-the-date-range-picker-and-checks-visuals-2-chromium-linux.pngnew file mode 100644index 0000000000..fd30bf9c17Binary files /dev/null and b/packages/desktop-client/e2e/reports.test.ts-snapshots/Reports-opens-the-date-range-picker-and-checks-visuals-2-chromium-linux.png differdiff --git a/packages/desktop-client/e2e/reports.test.ts-snapshots/Reports-opens-the-date-range-picker-and-checks-visuals-3-chromium-linux.png b/packages/desktop-client/e2e/reports.test.ts-snapshots/Reports-opens-the-date-range-picker-and-checks-visuals-3-chromium-linux.pngnew file mode 100644index 0000000000..81764480e8Binary files /dev/null and b/packages/desktop-client/e2e/reports.test.ts-snapshots/Reports-opens-the-date-range-picker-and-checks-visuals-3-chromium-linux.png differdiff --git a/packages/desktop-client/e2e/reports.test.ts-snapshots/Reports-opens-the-date-range-picker-and-checks-visuals-4-chromium-linux.png b/packages/desktop-client/e2e/reports.test.ts-snapshots/Reports-opens-the-date-range-picker-and-checks-visuals-4-chromium-linux.pngnew file mode 100644index 0000000000..8c2b1d7303Binary files /dev/null and b/packages/desktop-client/e2e/reports.test.ts-snapshots/Reports-opens-the-date-range-picker-and-checks-visuals-4-chromium-linux.png differdiff --git a/packages/desktop-client/e2e/reports.test.ts-snapshots/Reports-opens-the-date-range-picker-and-checks-visuals-5-chromium-linux.png b/packages/desktop-client/e2e/reports.test.ts-snapshots/Reports-opens-the-date-range-picker-and-checks-visuals-5-chromium-linux.pngnew file mode 100644index 0000000000..4ccbb04505Binary files /dev/null and b/packages/desktop-client/e2e/reports.test.ts-snapshots/Reports-opens-the-date-range-picker-and-checks-visuals-5-chromium-linux.png differdiff --git a/packages/desktop-client/e2e/reports.test.ts-snapshots/Reports-opens-the-date-range-picker-and-checks-visuals-6-chromium-linux.png b/packages/desktop-client/e2e/reports.test.ts-snapshots/Reports-opens-the-date-range-picker-and-checks-visuals-6-chromium-linux.pngnew file mode 100644index 0000000000..611d5594f5Binary files /dev/null and b/packages/desktop-client/e2e/reports.test.ts-snapshots/Reports-opens-the-date-range-picker-and-checks-visuals-6-chromium-linux.png differdiff --git a/packages/desktop-client/e2e/transactions.test.ts-snapshots/Transactions-filters-transactions-by-date-4-chromium-linux.png b/packages/desktop-client/e2e/transactions.test.ts-snapshots/Transactions-filters-transactions-by-date-4-chromium-linux.pngindex d8840b2f54..add9fe6873 100644Binary files a/packages/desktop-client/e2e/transactions.test.ts-snapshots/Transactions-filters-transactions-by-date-4-chromium-linux.png and b/packages/desktop-client/e2e/transactions.test.ts-snapshots/Transactions-filters-transactions-by-date-4-chromium-linux.png differdiff --git a/packages/desktop-client/e2e/transactions.test.ts-snapshots/Transactions-filters-transactions-by-date-5-chromium-linux.png b/packages/desktop-client/e2e/transactions.test.ts-snapshots/Transactions-filters-transactions-by-date-5-chromium-linux.pngindex 803923aeac..657c80bf69 100644Binary files a/packages/desktop-client/e2e/transactions.test.ts-snapshots/Transactions-filters-transactions-by-date-5-chromium-linux.png and b/packages/desktop-client/e2e/transactions.test.ts-snapshots/Transactions-filters-transactions-by-date-5-chromium-linux.png differdiff --git a/packages/desktop-client/e2e/transactions.test.ts-snapshots/Transactions-filters-transactions-by-date-6-chromium-linux.png b/packages/desktop-client/e2e/transactions.test.ts-snapshots/Transactions-filters-transactions-by-date-6-chromium-linux.pngindex eac05407ee..1c6774b5b7 100644Binary files a/packages/desktop-client/e2e/transactions.test.ts-snapshots/Transactions-filters-transactions-by-date-6-chromium-linux.png and b/packages/desktop-client/e2e/transactions.test.ts-snapshots/Transactions-filters-transactions-by-date-6-chromium-linux.png differdiff --git a/packages/desktop-client/package.json b/packages/desktop-client/package.jsonindex 9238deed20..b7d8d89d54 100644--- a/packages/desktop-client/package.json+++ b/packages/desktop-client/package.json@@ -139,6 +139,7 @@"@emotion/css": "^11.13.5","@fontsource-variable/inter": "^5.2.8","@fontsource/redacted-script": "^5.2.8",+ "@internationalized/date": "^3.12.2","@lezer/highlight": "^1.2.3","@playwright/test": "1.59.1","@react-aria/interactions": "^3.28.1",@@ -150,7 +151,6 @@"@testing-library/jest-dom": "^6.9.1","@testing-library/react": "16.3.2","@testing-library/user-event": "14.6.1",- "@types/pikaday": "^1.7.10","@types/react": "^19.2.17","@types/react-dom": "^19.2.3","@typescript/native-preview": "beta",@@ -175,7 +175,6 @@"jsdom": "^29.1.1","lru-cache": "^11.5.1","mdast-util-newline-to-break": "^2.0.0",- "pikaday": "1.8.2","plugins-service": "workspace:*","re-resizable": "^6.11.2","react": "19.2.7",diff --git a/packages/desktop-client/src/components/formula/QueryManager.tsx b/packages/desktop-client/src/components/formula/QueryManager.tsxindex 7117d0ff09..4f386a8b2a 100644--- a/packages/desktop-client/src/components/formula/QueryManager.tsx+++ b/packages/desktop-client/src/components/formula/QueryManager.tsx@@ -24,6 +24,7 @@ import { AppliedFilters } from '#components/filters/AppliedFilters';import { FilterButton } from '#components/filters/FiltersMenu';import { getLiveRange } from '#components/reports/getLiveRange';import {+ asMonthSlidingTimeFrame,calculateTimeRange,getLatestRange,validateEnd,@@ -669,11 +670,13 @@ function QueryItem({onPress={() => {const newMode =timeRangeMode === 'static' ? 'sliding-window' : 'static';- const [newStart, newEnd] = calculateTimeRange({- start: startDate,- end: endDate,- mode: newMode,- });+ const [newStart, newEnd] = calculateTimeRange(+ asMonthSlidingTimeFrame({+ start: startDate,+ end: endDate,+ mode: newMode,+ }),+ );setStartDate(newStart);setEndDate(newEnd);diff --git a/packages/desktop-client/src/components/mobile/transactions/TransactionList.tsx b/packages/desktop-client/src/components/mobile/transactions/TransactionList.tsxindex 471ae99fc3..8d947f9692 100644--- a/packages/desktop-client/src/components/mobile/transactions/TransactionList.tsx+++ b/packages/desktop-client/src/components/mobile/transactions/TransactionList.tsx@@ -546,8 +546,6 @@ function SelectedTransactionsFloatingActionBar({}}items={[// Add support later on.- // Pikaday doesn't play well will mobile.- // We should consider switching to react-aria date picker.// {// name: 'date',// text: 'Date',diff --git a/packages/desktop-client/src/components/reports/Header.tsx b/packages/desktop-client/src/components/reports/Header.tsxindex 0114c5dde7..470fcb6de1 100644--- a/packages/desktop-client/src/components/reports/Header.tsx+++ b/packages/desktop-client/src/components/reports/Header.tsx@@ -2,8 +2,12 @@ import type { ComponentProps, ReactNode } from 'react';import { Trans, useTranslation } from 'react-i18next';import { Button } from '@actual-app/components/button';+import { DateRangePicker } from '@actual-app/components/date-range-picker';+import type {+ DateRangeGranularity,+ DateRangePreset,+} from '@actual-app/components/date-range-picker';import { useResponsive } from '@actual-app/components/hooks/useResponsive';-import { Select } from '@actual-app/components/select';import { SpaceBetween } from '@actual-app/components/space-between';import { View } from '@actual-app/components/view';import * as monthUtils from '@actual-app/core/shared/months';@@ -15,7 +19,9 @@ import type { SyncedPrefs } from '@actual-app/core/types/prefs';import { AppliedFilters } from '#components/filters/AppliedFilters';import { FilterButton } from '#components/filters/FiltersMenu';-import { useLocale } from '#hooks/useLocale';+import { getFirstDayOfWeek } from '#components/select/DateSelect';+import { useDateFormat } from '#hooks/useDateFormat';+import { useLanguage } from '#hooks/useLocale';import { getLiveRange } from './getLiveRange';import {@@ -24,8 +30,6 @@ import {getFullRange,getLatestRange,getNextRange,- validateEnd,- validateStart,} from './reportRanges';type HeaderProps = {@@ -35,7 +39,7 @@ type HeaderProps = {show1Month?: boolean;showFutureRange?: boolean;hideModeToggle?: boolean;- allMonths: Array<{ name: string; pretty: string }>;+ allMonths: Array<{ name: string }>;earliestTransaction: string;latestTransaction: string;firstDayOfWeekIdx?: SyncedPrefs['firstDayOfWeekIdx'];@@ -44,6 +48,9 @@ type HeaderProps = {end: TimeFrame['end'],mode: TimeFrame['mode'],) => void;+ // Granularities the picker offers; defaults to month-only. In day mode the+ // picker emits `yyyy-MM-dd` start/end.+ granularities?: DateRangeGranularity[];children?: ReactNode;inlineContent?: ReactNode;// no separate category filter; use main filters instead@@ -70,193 +77,6 @@ type HeaderProps = {});-type RangePresetProps = {- show1Month?: boolean;- earliestTransaction: string;- latestTransaction: string;- firstDayOfWeekIdx?: SyncedPrefs['firstDayOfWeekIdx'];- allMonths: Array<{ name: string; pretty: string }>;- onChangeDates: HeaderProps['onChangeDates'];-};--type PastRangePresetsProps = RangePresetProps & {- convertToMonth: (- start: string,- end: string,- currentMode: TimeFrame['mode'],- mode: TimeFrame['mode'],- ) => [string, string, TimeFrame['mode']];-};--type FutureRangePresetsProps = Pick<- RangePresetProps,- 'show1Month' | 'latestTransaction' | 'onChangeDates'->;--function PastRangePresets({- show1Month,- earliestTransaction,- latestTransaction,- firstDayOfWeekIdx,- allMonths,- onChangeDates,- convertToMonth,-}: PastRangePresetsProps) {- return (- <>- {show1Month && (- <Button- variant="bare"- onPress={() => onChangeDates(...getLatestRange(0))}- >- <Trans>1 month</Trans>- </Button>- )}- <Button- variant="bare"- onPress={() => onChangeDates(...getLatestRange(2))}- >- <Trans>3 months</Trans>- </Button>- <Button- variant="bare"- onPress={() => onChangeDates(...getLatestRange(5))}- >- <Trans>6 months</Trans>- </Button>- <Button- variant="bare"- onPress={() => onChangeDates(...getLatestRange(11))}- >- <Trans>1 year</Trans>- </Button>- <Button- variant="bare"- onPress={() =>- onChangeDates(- ...convertToMonth(- ...getLiveRange(- 'Year to date',- earliestTransaction,- latestTransaction,- true,- firstDayOfWeekIdx,- ),- 'yearToDate',- ),- )- }- >- <Trans>Year to date</Trans>- </Button>- <Button- variant="bare"- onPress={() =>- onChangeDates(- ...convertToMonth(- ...getLiveRange(- 'Last month',- earliestTransaction,- latestTransaction,- false,- firstDayOfWeekIdx,- ),- 'lastMonth',- ),- )- }- >- <Trans>Last month</Trans>- </Button>- <Button- variant="bare"- onPress={() =>- onChangeDates(- ...convertToMonth(- ...getLiveRange(- 'Last year',- earliestTransaction,- latestTransaction,- false,- firstDayOfWeekIdx,- ),- 'lastYear',- ),- )- }- >- <Trans>Last year</Trans>- </Button>- <Button- variant="bare"- onPress={() =>- onChangeDates(- ...convertToMonth(- ...getLiveRange(- 'Prior year to date',- earliestTransaction,- latestTransaction,- false,- firstDayOfWeekIdx,- ),- 'priorYearToDate',- ),- )- }- >- <Trans>Prior year to date</Trans>- </Button>- <Button- variant="bare"- onPress={() =>- onChangeDates(- ...getFullRange(- allMonths[allMonths.length - 1].name,- allMonths[0].name,- ),- )- }- >- <Trans>All time</Trans>- </Button>- </>- );-}--function FutureRangePresets({- show1Month,- latestTransaction,- onChangeDates,-}: FutureRangePresetsProps) {- return (- <>- {show1Month && (- <Button- variant="bare"- onPress={() => onChangeDates(...getNextRange(0))}- >- <Trans>Next month</Trans>- </Button>- )}- <Button variant="bare" onPress={() => onChangeDates(...getNextRange(2))}>- <Trans>Next 3 months</Trans>- </Button>- <Button variant="bare" onPress={() => onChangeDates(...getNextRange(5))}>- <Trans>Next 6 months</Trans>- </Button>- <Button variant="bare" onPress={() => onChangeDates(...getNextRange(11))}>- <Trans>Next year</Trans>- </Button>- <Button- variant="bare"- onPress={() => onChangeDates(...getFullFutureRange(latestTransaction))}- >- <Trans>All future</Trans>- </Button>- </>- );-}-export function Header({start,end,@@ -275,24 +95,121 @@ export function Header({onUpdateFilter,onDeleteFilter,onConditionsOpChange,+ granularities,children,inlineContent,filterExclude,filterInclude,}: HeaderProps) {- const locale = useLocale();const { t } = useTranslation();const { isNarrowWidth } = useResponsive();+ const language = useLanguage();+ const dateFormat = useDateFormat() || 'MM/dd/yyyy';- function convertToMonth(- start: string,- end: string,- _: TimeFrame['mode'],+ // Live-range presets return day-shaped bounds; collapse them to months.+ function liveRangeAsMonths(+ rangeName: string,+ includeCurrentInterval: boolean,mode: TimeFrame['mode'],): [string, string, TimeFrame['mode']] {- return [monthUtils.getMonth(start), monthUtils.getMonth(end), mode];+ const [rangeStart, rangeEnd] = getLiveRange(+ rangeName,+ earliestTransaction,+ latestTransaction,+ includeCurrentInterval,+ firstDayOfWeekIdx,+ );+ return [+ monthUtils.getMonth(rangeStart),+ monthUtils.getMonth(rangeEnd),+ mode,+ ];}+ // The picker previews the range via getRange while staying open, then+ // commits via onSelect on close so the preset's mode is preserved.+ function makePreset(+ key: string,+ label: ReactNode,+ getFullRange: () => readonly [string, string, TimeFrame['mode']],+ ): DateRangePreset {+ return {+ key,+ label,+ getRange: () => {+ const [rangeStart, rangeEnd] = getFullRange();+ return [rangeStart, rangeEnd];+ },+ onSelect: () => onChangeDates(...getFullRange()),+ };+ }++ const presets: DateRangePreset[] = showFutureRange+ ? [+ ...(show1Month+ ? [+ makePreset('next-month', <Trans>Next month</Trans>, () =>+ getNextRange(0),+ ),+ ]+ : []),+ makePreset('next-3-months', <Trans>Next 3 months</Trans>, () =>+ getNextRange(2),+ ),+ makePreset('next-6-months', <Trans>Next 6 months</Trans>, () =>+ getNextRange(5),+ ),+ makePreset('next-year', <Trans>Next year</Trans>, () =>+ getNextRange(11),+ ),+ makePreset('all-future', <Trans>All future</Trans>, () =>+ getFullFutureRange(latestTransaction),+ ),+ ]+ : [+ ...(show1Month+ ? [+ makePreset('1-month', <Trans>1 month</Trans>, () =>+ getLatestRange(0),+ ),+ ]+ : []),+ makePreset('3-months', <Trans>3 months</Trans>, () =>+ getLatestRange(2),+ ),+ makePreset('6-months', <Trans>6 months</Trans>, () =>+ getLatestRange(5),+ ),+ makePreset('1-year', <Trans>1 year</Trans>, () => getLatestRange(11)),+ makePreset('year-to-date', <Trans>Year to date</Trans>, () =>+ liveRangeAsMonths('Year to date', true, 'yearToDate'),+ ),+ makePreset('last-month', <Trans>Last month</Trans>, () =>+ liveRangeAsMonths('Last month', false, 'lastMonth'),+ ),+ makePreset('last-year', <Trans>Last year</Trans>, () =>+ liveRangeAsMonths('Last year', false, 'lastYear'),+ ),+ makePreset(+ 'prior-year-to-date',+ <Trans>Prior year to date</Trans>,+ () =>+ liveRangeAsMonths('Prior year to date', false, 'priorYearToDate'),+ ),+ // `allMonths` may still be empty before the report's async load+ // finishes.+ ...(allMonths.length+ ? [+ makePreset('all-time', <Trans>All time</Trans>, () =>+ getFullRange(+ allMonths[allMonths.length - 1].name,+ allMonths[0].name,+ ),+ ),+ ]+ : []),+ ];+return (<Viewstyle={{@@ -307,110 +224,85 @@ export function Header({alignItems: isNarrowWidth ? 'flex-start' : 'center',}}>- <View- style={{- display: 'flex',- flexWrap: 'wrap',- flexDirection: 'row',- }}- >- <SpaceBetween gap={isNarrowWidth ? 5 : undefined}>- {mode && !hideModeToggle && (- <Button- variant={mode === 'static' ? 'normal' : 'primary'}- onPress={() => {- const newMode =- mode === 'static' ? 'sliding-window' : 'static';- const [newStart, newEnd] = calculateTimeRange({- start,- end,- mode: newMode,- });+ <SpaceBetween gap={isNarrowWidth ? 5 : undefined}>+ {mode && !hideModeToggle && (+ <Button+ variant={mode === 'static' ? 'normal' : 'primary'}+ onPress={() => {+ const newMode = mode === 'static' ? 'sliding-window' : 'static';+ const [newStart, newEnd] = calculateTimeRange({+ start,+ end,+ mode: newMode,+ });- onChangeDates(newStart, newEnd, newMode);- }}- >- {mode === 'static' ? t('Static') : t('Live')}- </Button>- )}+ onChangeDates(newStart, newEnd, newMode);+ }}+ >+ {mode === 'static' ? t('Static') : t('Live')}+ </Button>+ )}- <SpaceBetween gap={5}>- <Select- onChange={newValue =>- onChangeDates(- ...validateStart(- allMonths[allMonths.length - 1].name,- allMonths[0].name,- newValue,- end,- ),- )- }- value={start}- defaultLabel={monthUtils.format(start, 'MMMM yyyy', locale)}- options={allMonths.map(({ name, pretty }) => [name, pretty])}- />- <View>{t('to')}</View>- <Select- onChange={newValue =>- onChangeDates(- ...validateEnd(- allMonths[allMonths.length - 1].name,- allMonths[0].name,- start,- newValue,- ),- )- }- value={end}- options={allMonths.map(({ name, pretty }) => [name, pretty])}- style={{ marginRight: 10 }}- />- </SpaceBetween>- </SpaceBetween>-- <SpaceBetween gap={3}>- {showFutureRange ? (- <FutureRangePresets- show1Month={show1Month}- latestTransaction={latestTransaction}- onChangeDates={onChangeDates}- />- ) : (- <PastRangePresets- show1Month={show1Month}- earliestTransaction={earliestTransaction}- latestTransaction={latestTransaction}- firstDayOfWeekIdx={firstDayOfWeekIdx}- allMonths={allMonths}- onChangeDates={onChangeDates}- convertToMonth={convertToMonth}- />- )}- {filters && (- <FilterButton- compact={isNarrowWidth}- onApply={onApply}- hover={false}- exclude={filterExclude}- include={filterInclude}- />- )}- {inlineContent}- </SpaceBetween>- </View>+ <DateRangePicker+ start={start}+ end={end}+ granularities={granularities}+ // allMonths is newest-first and may be empty before reports load.+ minDate={+ allMonths.length+ ? allMonths[allMonths.length - 1].name+ : monthUtils.currentMonth()+ }+ maxDate={+ showFutureRange+ ? undefined+ : allMonths.length+ ? allMonths[0].name+ : monthUtils.currentMonth()+ }+ firstDayOfWeek={getFirstDayOfWeek(firstDayOfWeekIdx)}+ locale={language}+ formatDayLabel={date => monthUtils.format(date, dateFormat)}+ labels={{+ selectBy: t('Select by'),+ quickSelect: t('Quick select'),+ month: t('Month'),+ day: t('Day'),+ previous: t('Previous'),+ next: t('Next'),+ previousMonth: t('Previous month'),+ nextMonth: t('Next month'),+ year: t('Year'),+ dateRange: t('Date range'),+ }}+ presets={presets}+ onChangeDates={(newStart, newEnd) =>+ onChangeDates(newStart, newEnd, 'static')+ }+ />+ {filters && (+ <FilterButton+ compact={isNarrowWidth}+ onApply={onApply}+ hover={false}+ exclude={filterExclude}+ include={filterInclude}+ />+ )}+ {inlineContent}+ </SpaceBetween>{children && (- <View+ <SpaceBetween+ gap={isNarrowWidth ? 5 : undefined}style={{gridColumn: 2,- flexDirection: 'row',justifySelf: 'flex-end',alignSelf: 'flex-start',}}>{children}- </View>+ </SpaceBetween>)}</View>diff --git a/packages/desktop-client/src/components/reports/ReportSidebar.tsx b/packages/desktop-client/src/components/reports/ReportSidebar.tsxindex fde06b4a69..7d001b21a8 100644--- a/packages/desktop-client/src/components/reports/ReportSidebar.tsx+++ b/packages/desktop-client/src/components/reports/ReportSidebar.tsx@@ -3,6 +3,7 @@ import { Trans, useTranslation } from 'react-i18next';import { Button } from '@actual-app/components/button';import { Menu } from '@actual-app/components/menu';+import { ModeButton } from '@actual-app/components/mode-button';import { Popover } from '@actual-app/components/popover';import { Select } from '@actual-app/components/select';import type { SelectOption } from '@actual-app/components/select';@@ -29,7 +30,6 @@ import { useLocale } from '#hooks/useLocale';import { CategorySelector } from './CategorySelector';import { defaultsList, disabledList } from './disabledList';import { getLiveRange } from './getLiveRange';-import { ModeButton } from './ModeButton';import { ReportOptions } from './ReportOptions';import type { dateRangeProps } from './ReportOptions';import { validateEnd, validateStart } from './reportRanges';diff --git a/packages/desktop-client/src/components/reports/reportRanges.test.ts b/packages/desktop-client/src/components/reports/reportRanges.test.tsindex 2edd86e769..bc45cc9d0f 100644--- a/packages/desktop-client/src/components/reports/reportRanges.test.ts+++ b/packages/desktop-client/src/components/reports/reportRanges.test.ts@@ -5,6 +5,7 @@ import {calculateSpendingReportTimeRange,calculateTimeRange,getFullFutureRange,+ getLatestRange,} from './reportRanges';// In test mode, monthUtils.currentMonth() returns '2017-01'@@ -20,6 +21,52 @@ describe('calculateTimeRange', () => {expect(end).toBe('2016-12');expect(mode).toBe('lastMonth');});++ it('anchors a live window that ends at the current month to now', () => {+ // Saved 6-month window ending at the (then-)current month.+ const [start, end, mode] = calculateTimeRange({+ start: '2016-08',+ end: '2017-01',+ mode: 'sliding-window',+ });++ expect(start).toBe('2016-08');+ expect(end).toBe('2017-01');+ expect(mode).toBe('sliding-window');+ });++ it('anchors a live window that ends before the current month to now', () => {+ // Saved 6-month window ending one month before the (then-)current month;+ // a live window always slides so its end is the current month.+ const [start, end, mode] = calculateTimeRange({+ start: '2016-07',+ end: '2016-12',+ mode: 'sliding-window',+ });++ expect(end).toBe('2017-01');+ expect(start).toBe('2016-08'); // width of 5 preserved+ expect(mode).toBe('sliding-window');+ });++ it('anchors a live day-shaped window to today, preserving its width in days', () => {+ const [start, end, mode] = calculateTimeRange({+ start: '2016-12-15',+ end: '2016-12-29',+ mode: 'sliding-window',+ });++ expect(end).toBe('2017-01-01'); // currentDay() in test mode+ expect(start).toBe('2016-12-18'); // width of 14 days preserved+ expect(mode).toBe('sliding-window');+ });+});++// In test mode, monthUtils.currentMonth() returns '2017-01'+describe('getLatestRange', () => {+ it('ends at the current month', () => {+ expect(getLatestRange(5)).toEqual(['2016-08', '2017-01', 'sliding-window']);+ });});// In test mode, monthUtils.currentMonth() returns '2017-01'diff --git a/packages/desktop-client/src/components/reports/reportRanges.ts b/packages/desktop-client/src/components/reports/reportRanges.tsindex 6d312f5d9c..ad41e8fe57 100644--- a/packages/desktop-client/src/components/reports/reportRanges.ts+++ b/packages/desktop-client/src/components/reports/reportRanges.ts@@ -189,6 +189,22 @@ export function getFullFutureRange(latestMonth?: string) {return [start, end, 'static'] as const;}+// For month-granular consumers (e.g. formula queries): collapse day-shaped+// bounds so a live range keeps sliding by whole months rather than days.+export function asMonthSlidingTimeFrame(+ timeFrame: Partial<TimeFrame>,+): Partial<TimeFrame> {+ const { start, end, mode } = timeFrame;+ if (mode !== 'sliding-window' || !start || !end) {+ return timeFrame;+ }+ return {+ ...timeFrame,+ start: monthUtils.getMonth(start),+ end: monthUtils.getMonth(end),+ };+}+export function calculateTimeRange(timeFrame?: Partial<TimeFrame>,defaultTimeFrame?: TimeFrame,@@ -215,6 +231,20 @@ export function calculateTimeRange(return getFullRange(start, fullEnd);}if (mode === 'sliding-window') {+ // Day-shaped ranges slide by days: same width, ending today.+ if (+ monthUtils.isValidYearMonthDay(start) &&+ monthUtils.isValidYearMonthDay(end)+ ) {+ const dayOffset = monthUtils.differenceInCalendarDays(end, start);+ const today = monthUtils.currentDay();+ return [+ monthUtils.subDays(today, Math.max(dayOffset, 0)),+ today,+ 'sliding-window',+ ] as const;+ }+const offset = monthUtils.differenceInCalendarMonths(end, start);if (start > end) {diff --git a/packages/desktop-client/src/components/reports/reports/AgeOfMoney.tsx b/packages/desktop-client/src/components/reports/reports/AgeOfMoney.tsxindex 96d9993b63..4533277f8e 100644--- a/packages/desktop-client/src/components/reports/reports/AgeOfMoney.tsx+++ b/packages/desktop-client/src/components/reports/reports/AgeOfMoney.tsx@@ -170,14 +170,15 @@ function AgeOfMoneyInner({ widget }: AgeOfMoneyInnerProps) {}}, [latestTransaction, widget?.meta?.timeFrame]);- const onChangeDates = useCallback(- (newStart: string, newEnd: string, newMode: TimeFrame['mode']) => {- setStart(newStart);- setEnd(newEnd);- setMode(newMode);- },- [],- );+ function onChangeDates(+ newStart: string,+ newEnd: string,+ newMode: TimeFrame['mode'],+ ) {+ setStart(newStart);+ setEnd(newEnd);+ setMode(newMode);+ }const updateDashboardWidgetMutation = useUpdateDashboardWidgetMutation();@@ -285,6 +286,7 @@ function AgeOfMoneyInner({ widget }: AgeOfMoneyInnerProps) {earliestTransaction={earliestTransaction}latestTransaction={latestTransaction}firstDayOfWeekIdx={firstDayOfWeekIdx}+ granularities={['month', 'day']}mode={mode}onChangeDates={onChangeDates}filters={conditions}diff --git a/packages/desktop-client/src/components/reports/reports/BalanceForecast.tsx b/packages/desktop-client/src/components/reports/reports/BalanceForecast.tsxindex d2c12fa39f..b4863015a3 100644--- a/packages/desktop-client/src/components/reports/reports/BalanceForecast.tsx+++ b/packages/desktop-client/src/components/reports/reports/BalanceForecast.tsx@@ -133,7 +133,8 @@ function BalanceForecastInner({ widget }: BalanceForecastInnerProps) {[accounts, widget?.meta?.accounts],);const hasMonthOptions = allMonths != null;- const startDate = start + '-01';+ // `start` may be `yyyy-MM` or `yyyy-MM-dd`; `firstDayOfMonth` handles both.+ const startDate = monthUtils.firstDayOfMonth(start);const endDate = monthUtils.lastDayOfMonth(end);const {data: forecastData,@@ -307,9 +308,12 @@ function BalanceForecastInner({ widget }: BalanceForecastInnerProps) {);const isUpdatingForecast = isFetching && isPlaceholderData;- const scheduledOccurrenceCount = countForecastScheduledOccurrences(- normalizedForecastData,- );+ const scheduledOccurrenceCount = countForecastScheduledOccurrences({+ forecastData: normalizedForecastData,+ start: chartRange.start,+ end: chartRange.end,+ granularity,+ });if (!allMonths) {return <LoadingIndicator />;@@ -331,7 +335,7 @@ function BalanceForecastInner({ widget }: BalanceForecastInnerProps) {dataPoint => dataPoint.date === todayReferenceDate,);const headerInlineContent = (- <View style={{ flexDirection: 'row', gap: 10 }}>+ <>{budgetType === 'tracking' && (<Selectvalue={source}@@ -351,7 +355,7 @@ function BalanceForecastInner({ widget }: BalanceForecastInnerProps) {['Daily', t('Daily')],]}/>- </View>+ </>);const headerChildren = widget ? (<Button variant="primary" onPress={onSaveWidget}>@@ -394,6 +398,7 @@ function BalanceForecastInner({ widget }: BalanceForecastInnerProps) {? monthUtils.monthFromDate(forecastData.forecastEndDate): (allMonths[0]?.name ?? monthUtils.addMonths(currentMonth, 24))}+ granularities={['month', 'day']}mode={mode}onChangeDates={onChangeDates}filters={conditions}diff --git a/packages/desktop-client/src/components/reports/reports/BalanceForecastCard.tsx b/packages/desktop-client/src/components/reports/reports/BalanceForecastCard.tsxindex 0a51b8de0f..34cca7f904 100644--- a/packages/desktop-client/src/components/reports/reports/BalanceForecastCard.tsx+++ b/packages/desktop-client/src/components/reports/reports/BalanceForecastCard.tsx@@ -78,7 +78,8 @@ export function BalanceForecastCard({[accounts, meta?.accounts],);- const startDate = start + '-01';+ // `start` may be `yyyy-MM` or `yyyy-MM-dd`; `firstDayOfMonth` handles both.+ const startDate = monthUtils.firstDayOfMonth(start);const endDate = monthUtils.lastDayOfMonth(end);const {@@ -137,9 +138,12 @@ export function BalanceForecastCard({dataPoint => dataPoint.date === todayReferenceDate,);- const scheduledOccurrenceCount = countForecastScheduledOccurrences(- normalizedForecastData,- );+ const scheduledOccurrenceCount = countForecastScheduledOccurrences({+ forecastData: normalizedForecastData,+ start: chartRange.start,+ end: chartRange.end,+ granularity: 'Monthly',+ });const hasFilters =!isTrackingBudgetForecast && (meta?.conditions?.length ?? 0) > 0;diff --git a/packages/desktop-client/src/components/reports/reports/BudgetAnalysis.tsx b/packages/desktop-client/src/components/reports/reports/BudgetAnalysis.tsxindex ee983dcf81..6fad3267e6 100644--- a/packages/desktop-client/src/components/reports/reports/BudgetAnalysis.tsx+++ b/packages/desktop-client/src/components/reports/reports/BudgetAnalysis.tsx@@ -185,7 +185,10 @@ function BudgetAnalysisInternal({ widget }: BudgetAnalysisInternalProps) {const [_firstDayOfWeekIdx] = useSyncedPref('firstDayOfWeekIdx');const firstDayOfWeekIdx = _firstDayOfWeekIdx || '0';- const calculateIsConcise = (startMonth: string, endMonth: string) => {+ // Normalize in case a persisted timeFrame still holds `yyyy-MM-dd` values.+ const calculateIsConcise = (start: string, end: string) => {+ const startMonth = monthUtils.getMonth(start);+ const endMonth = monthUtils.getMonth(end);const numDays = d.differenceInCalendarDays(d.parseISO(endMonth + '-01'),d.parseISO(startMonth + '-01'),@@ -256,8 +259,9 @@ function BudgetAnalysisInternal({ widget }: BudgetAnalysisInternalProps) {void run();}, [locale, widget?.meta?.timeFrame]);- const startDate = start + '-01';- const endDate = monthUtils.getMonthEnd(end + '-01');+ // `start`/`end` may be `yyyy-MM` or `yyyy-MM-dd`; collapse to months first.+ const startDate = `${monthUtils.getMonth(start)}-01`;+ const endDate = monthUtils.getMonthEnd(`${monthUtils.getMonth(end)}-01`);const getGraphData = useMemo(() =>@@ -413,38 +417,34 @@ function BudgetAnalysisInternal({ widget }: BudgetAnalysisInternalProps) {onConditionsOpChange={onConditionsOpChange}filterInclude={['category', 'saved']}>- <View style={{ flexDirection: 'row', gap: 10 }}>- <OptionsButton- graphType={graphType}- onToggleGraphType={() =>- setGraphType(graphType === 'Line' ? 'Bar' : 'Line')- }- showBalance={showBalance}- onToggleShowBalance={() => setShowBalance(v => !v)}- showCategories={showCategories}- onToggleShowCategories={() => setShowCategories(v => !v)}- showHiddenCategories={showHiddenCategories}- onToggleShowHiddenCategories={() =>- setShowHiddenCategories(v => !v)- }- />+ <OptionsButton+ graphType={graphType}+ onToggleGraphType={() =>+ setGraphType(graphType === 'Line' ? 'Bar' : 'Line')+ }+ showBalance={showBalance}+ onToggleShowBalance={() => setShowBalance(v => !v)}+ showCategories={showCategories}+ onToggleShowCategories={() => setShowCategories(v => !v)}+ showHiddenCategories={showHiddenCategories}+ onToggleShowHiddenCategories={() => setShowHiddenCategories(v => !v)}+ />- <Tooltip content={t('Export as CSV')}>- <Button- variant="bare"- onPress={onExportCsv}- aria-label={t('Export as CSV')}- >- <SvgDownload style={{ width: 16, height: 16 }} />- </Button>- </Tooltip>-- {widget && (- <Button variant="primary" onPress={onSaveWidget}>- <Trans>Save widget</Trans>- </Button>- )}- </View>+ <Tooltip content={t('Export as CSV')}>+ <Button+ variant="bare"+ onPress={onExportCsv}+ aria-label={t('Export as CSV')}+ >+ <SvgDownload style={{ width: 16, height: 16 }} />+ </Button>+ </Tooltip>++ {widget && (+ <Button variant="primary" onPress={onSaveWidget}>+ <Trans>Save widget</Trans>+ </Button>+ )}</Header><Viewstyle={{diff --git a/packages/desktop-client/src/components/reports/reports/CashFlow.tsx b/packages/desktop-client/src/components/reports/reports/CashFlow.tsxindex cadf3dbc13..7f8dab39da 100644--- a/packages/desktop-client/src/components/reports/reports/CashFlow.tsx+++ b/packages/desktop-client/src/components/reports/reports/CashFlow.tsx@@ -41,9 +41,11 @@ import { addNotification } from '#notifications/notificationsSlice';import { useDispatch } from '#redux';import { useUpdateDashboardWidgetMutation } from '#reports/mutations';+// Month-shaped so the range means the whole current month (the query clamps+// to today); day-shaped values here would slide by days instead.export const defaultTimeFrame = {- start: monthUtils.dayFromDate(monthUtils.currentMonth()),- end: monthUtils.currentDay(),+ start: monthUtils.currentMonth(),+ end: monthUtils.currentMonth(),mode: 'sliding-window',} satisfies TimeFrame;@@ -283,6 +285,7 @@ function CashFlowInner({ widget }: CashFlowInnerProps) {earliestTransaction={earliestTransaction}latestTransaction={latestTransaction}firstDayOfWeekIdx={firstDayOfWeekIdx}+ granularities={['month', 'day']}mode={mode}show1MonthonChangeDates={onChangeDates}@@ -293,17 +296,15 @@ function CashFlowInner({ widget }: CashFlowInnerProps) {conditionsOp={conditionsOp}onConditionsOpChange={onConditionsOpChange}>- <View style={{ flexDirection: 'row', gap: 10 }}>- <Button onPress={() => setShowBalance(state => !state)}>- {showBalance ? t('Hide balance') : t('Show balance')}- </Button>+ <Button onPress={() => setShowBalance(state => !state)}>+ {showBalance ? t('Hide balance') : t('Show balance')}+ </Button>- {widget && (- <Button variant="primary" onPress={onSaveWidget}>- <Trans>Save widget</Trans>- </Button>- )}- </View>+ {widget && (+ <Button variant="primary" onPress={onSaveWidget}>+ <Trans>Save widget</Trans>+ </Button>+ )}</Header><Viewstyle={{diff --git a/packages/desktop-client/src/components/reports/reports/NetWorth.tsx b/packages/desktop-client/src/components/reports/reports/NetWorth.tsxindex 497037bedc..7a28cc1350 100644--- a/packages/desktop-client/src/components/reports/reports/NetWorth.tsx+++ b/packages/desktop-client/src/components/reports/reports/NetWorth.tsx@@ -322,6 +322,7 @@ function NetWorthInner({ widget }: NetWorthInnerProps) {earliestTransaction={earliestTransaction}latestTransaction={latestTransaction}firstDayOfWeekIdx={firstDayOfWeekIdx}+ granularities={['month', 'day']}mode={mode}onChangeDates={onChangeDates}filters={conditions}diff --git a/packages/desktop-client/src/components/reports/reports/Sankey.tsx b/packages/desktop-client/src/components/reports/reports/Sankey.tsxindex a69d036dab..ed0ca8f0b3 100644--- a/packages/desktop-client/src/components/reports/reports/Sankey.tsx+++ b/packages/desktop-client/src/components/reports/reports/Sankey.tsx@@ -12,6 +12,7 @@ import {SvgRefresh,} from '@actual-app/components/icons/v1';import { Menu } from '@actual-app/components/menu';+import { ModeButton } from '@actual-app/components/mode-button';import { Paragraph } from '@actual-app/components/paragraph';import { Popover } from '@actual-app/components/popover';import { SpaceBetween } from '@actual-app/components/space-between';@@ -36,7 +37,6 @@ import { MobilePageHeader, Page, PageHeader } from '#components/Page';import { SankeyGraph } from '#components/reports/graphs/SankeyGraph';import { Header } from '#components/reports/Header';import { LoadingIndicator } from '#components/reports/LoadingIndicator';-import { ModeButton } from '#components/reports/ModeButton';import { calculateTimeRange } from '#components/reports/reportRanges';import {buildSankeyData,@@ -827,8 +827,6 @@ function SankeyInner({ widget }: SankeyInnerProps) {width: 1,height: 28,backgroundColor: theme.pillBorderDark,- marginRight: 10,- marginLeft: 10,}}/><GraphModeSelector mode={graphMode} onChange={setGraphMode} />@@ -837,8 +835,6 @@ function SankeyInner({ widget }: SankeyInnerProps) {width: 1,height: 28,backgroundColor: theme.pillBorderDark,- marginRight: 10,- marginLeft: 10,}}/><TopNSelector value={topNcategories} onChange={settopNcategories} />diff --git a/packages/desktop-client/src/components/reports/reports/Spending.tsx b/packages/desktop-client/src/components/reports/reports/Spending.tsxindex 31a9609bbb..19b97e6809 100644--- a/packages/desktop-client/src/components/reports/reports/Spending.tsx+++ b/packages/desktop-client/src/components/reports/reports/Spending.tsx@@ -6,6 +6,7 @@ import { AlignedText } from '@actual-app/components/aligned-text';import { Block } from '@actual-app/components/block';import { Button } from '@actual-app/components/button';import { useResponsive } from '@actual-app/components/hooks/useResponsive';+import { ModeButton } from '@actual-app/components/mode-button';import { Paragraph } from '@actual-app/components/paragraph';import { Select } from '@actual-app/components/select';import { SpaceBetween } from '@actual-app/components/space-between';@@ -31,7 +32,6 @@ import { PrivacyFilter } from '#components/PrivacyFilter';import { SpendingGraph } from '#components/reports/graphs/SpendingGraph';import { LegendItem } from '#components/reports/LegendItem';import { LoadingIndicator } from '#components/reports/LoadingIndicator';-import { ModeButton } from '#components/reports/ModeButton';import { calculateSpendingReportTimeRange } from '#components/reports/reportRanges';import {getSpendingAverageRangeLabel,diff --git a/packages/desktop-client/src/components/reports/reports/Summary.tsx b/packages/desktop-client/src/components/reports/reports/Summary.tsxindex c43b4c02dd..65ceecc1f6 100644--- a/packages/desktop-client/src/components/reports/reports/Summary.tsx+++ b/packages/desktop-client/src/components/reports/reports/Summary.tsx@@ -78,7 +78,6 @@ function SummaryInner({ widget }: SummaryInnerProps) {);const [end, setEnd] = useState(monthUtils.currentDay());const [mode, setMode] = useState<TimeFrame['mode']>('full');-const dividendFilters: FilterObject = useRuleConditionFilters(widget?.meta?.conditions ?? [],widget?.meta?.conditionsOp ?? 'and',diff --git a/packages/desktop-client/src/components/reports/reports/balanceForecastChartData.test.ts b/packages/desktop-client/src/components/reports/reports/balanceForecastChartData.test.tsindex 6ce4b1e6d9..e4ccd0890d 100644--- a/packages/desktop-client/src/components/reports/reports/balanceForecastChartData.test.ts+++ b/packages/desktop-client/src/components/reports/reports/balanceForecastChartData.test.ts@@ -101,6 +101,82 @@ describe('buildBalanceForecastChartData', () => {expect(chartData).toHaveLength(61);});+ it('preserves exact day-shaped bounds for daily data instead of widening to full months', () => {+ const chartData = buildBalanceForecastChartData({+ forecastData: {+ dataPoints: [+ {+ date: '2024-03-10',+ balance: 1000,+ accountId: 'checking',+ accountName: 'Checking',+ transactions: [],+ },+ {+ date: '2024-03-20',+ balance: 900,+ accountId: 'checking',+ accountName: 'Checking',+ transactions: [],+ },+ ],+ lowestBalance: {+ date: '2024-03-20',+ balance: 900,+ accountId: '',+ accountName: '',+ },+ forecastStartDate: '2024-03-10',+ forecastEndDate: '2024-03-20',+ },+ start: '2024-03-10',+ end: '2024-03-20',+ granularity: 'Daily',+ });++ expect(chartData[0]).toEqual({ date: '2024-03-10', balance: 1000 });+ expect(chartData.at(-1)).toEqual({ date: '2024-03-20', balance: 900 });+ expect(chartData).toHaveLength(11);+ });++ it('carries the balance forward from points before a day-shaped start', () => {+ const chartData = buildBalanceForecastChartData({+ forecastData: {+ dataPoints: [+ {+ date: '2024-03-01',+ balance: 1000,+ accountId: 'checking',+ accountName: 'Checking',+ transactions: [],+ },+ {+ date: '2024-03-15',+ balance: 800,+ accountId: 'checking',+ accountName: 'Checking',+ transactions: [],+ },+ ],+ lowestBalance: {+ date: '2024-03-15',+ balance: 800,+ accountId: '',+ accountName: '',+ },+ forecastStartDate: '2024-03-01',+ forecastEndDate: '2024-03-31',+ },+ start: '2024-03-10',+ end: '2024-03-20',+ granularity: 'Daily',+ });++ expect(chartData[0]).toEqual({ date: '2024-03-10', balance: 1000 });+ expect(chartData.at(-1)).toEqual({ date: '2024-03-20', balance: 800 });+ expect(chartData).toHaveLength(11);+ });+it('uses the latest same-day balance for each account', () => {const chartData = buildBalanceForecastChartData({forecastData: {@@ -201,7 +277,7 @@ describe('buildBalanceForecastChartData', () => {describe('countForecastScheduledOccurrences', () => {it('counts a transfer schedule once across both account legs', () => {- const count = countForecastScheduledOccurrences({+ const forecastData = {dataPoints: [{date: '2024-03-20',@@ -254,10 +330,78 @@ describe('countForecastScheduledOccurrences', () => {},forecastStartDate: '2024-03-01',forecastEndDate: '2024-04-30',+ };++ const count = countForecastScheduledOccurrences({+ forecastData,+ start: '2024-03',+ end: '2024-04',+ granularity: 'Monthly',});expect(count).toBe(2);});++ it('ignores occurrences outside exact day-shaped bounds in daily mode', () => {+ const forecastData = {+ dataPoints: [+ {+ date: '2024-03-05',+ balance: 100,+ accountId: 'checking',+ accountName: 'Checking',+ transactions: [+ {+ amount: 100,+ payee: 'Early',+ scheduleId: 'schedule-early',+ scheduleName: 'Early',+ },+ ],+ },+ {+ date: '2024-03-15',+ balance: 200,+ accountId: 'checking',+ accountName: 'Checking',+ transactions: [+ {+ amount: 100,+ payee: 'In range',+ scheduleId: 'schedule-in-range',+ scheduleName: 'In range',+ },+ ],+ },+ ],+ lowestBalance: {+ date: '2024-03-05',+ balance: 100,+ accountId: '',+ accountName: '',+ },+ forecastStartDate: '2024-03-01',+ forecastEndDate: '2024-03-31',+ };++ expect(+ countForecastScheduledOccurrences({+ forecastData,+ start: '2024-03-10',+ end: '2024-03-20',+ granularity: 'Daily',+ }),+ ).toBe(1);++ expect(+ countForecastScheduledOccurrences({+ forecastData,+ start: '2024-03-10',+ end: '2024-03-20',+ granularity: 'Monthly',+ }),+ ).toBe(2);+ });});describe('getZeroCrossingGradientOffset', () => {diff --git a/packages/desktop-client/src/components/reports/reports/balanceForecastChartData.ts b/packages/desktop-client/src/components/reports/reports/balanceForecastChartData.tsindex baca7e2040..f0abcc27ca 100644--- a/packages/desktop-client/src/components/reports/reports/balanceForecastChartData.ts+++ b/packages/desktop-client/src/components/reports/reports/balanceForecastChartData.ts@@ -73,11 +73,27 @@ export function buildBalanceForecastChartData({if (granularity === 'Daily') {const result: ChartDataPoint[] = [];- let runningBalance = 0;const combinedBalanceByDate = getCombinedBalanceByDate(forecastData);- const startDate = monthUtils.parseDate(start + '-01');- const endDate = monthUtils.parseDate(monthUtils.lastDayOfMonth(end));+ // Expand month-shaped bounds to full months; keep day-shaped bounds exact.+ const startDay = monthUtils.isValidYearMonth(start)+ ? monthUtils.firstDayOfMonth(start)+ : start;+ const endDay = monthUtils.isValidYearMonth(end)+ ? monthUtils.lastDayOfMonth(end)+ : end;++ // Carry the balance forward from the latest point before the visible+ // range, so a day-shaped start doesn't begin the chart at zero.+ const priorDate = Object.keys(combinedBalanceByDate)+ .filter(date => date < startDay)+ .sort()+ .at(-1);+ let runningBalance =+ priorDate === undefined ? 0 : combinedBalanceByDate[priorDate];++ const startDate = monthUtils.parseDate(startDay);+ const endDate = monthUtils.parseDate(endDay);const current = new Date(startDate);while (current <= endDate) {@@ -96,9 +112,11 @@ export function buildBalanceForecastChartData({let runningBalance = 0;const combinedBalanceByMonth = getCombinedBalanceByMonth(forecastData);+ // Collapse day-level bounds to months so the month keys line up.+ const endMonth = monthUtils.getMonth(end);for (- let month = start;- month <= end;+ let month = monthUtils.getMonth(start);+ month <= endMonth;month = monthUtils.addMonths(month, 1)) {if (combinedBalanceByMonth[month] !== undefined) {@@ -111,16 +129,39 @@ export function buildBalanceForecastChartData({return result;}-export function countForecastScheduledOccurrences(- forecastData: ForecastResult | null | undefined,-): number {+export function countForecastScheduledOccurrences({+ forecastData,+ start,+ end,+ granularity,+}: {+ forecastData: ForecastResult | null | undefined;+ start: string;+ end: string;+ granularity: Granularity;+}): number {if (!forecastData?.dataPoints.length) {return 0;}+ // The forecast query always covers whole months; only count occurrences the+ // chart actually shows. Daily keeps day-shaped bounds exact, Monthly widens+ // to full months (mirrors buildBalanceForecastChartData).+ const startDay =+ granularity === 'Daily' && !monthUtils.isValidYearMonth(start)+ ? start+ : monthUtils.firstDayOfMonth(start);+ const endDay =+ granularity === 'Daily' && !monthUtils.isValidYearMonth(end)+ ? end+ : monthUtils.lastDayOfMonth(end);+const occurrenceKeys = new Set<string>();for (const dataPoint of forecastData.dataPoints) {+ if (dataPoint.date < startDay || dataPoint.date > endDay) {+ continue;+ }for (const transaction of dataPoint.transactions) {occurrenceKeys.add(`${dataPoint.date}:${transaction.scheduleId}`);}diff --git a/packages/desktop-client/src/components/select/DateSelect.left.png b/packages/desktop-client/src/components/select/DateSelect.left.pngdeleted file mode 100644index 379766fa61..0000000000Binary files a/packages/desktop-client/src/components/select/DateSelect.left.png and /dev/null differdiff --git a/packages/desktop-client/src/components/select/DateSelect.right.png b/packages/desktop-client/src/components/select/DateSelect.right.pngdeleted file mode 100644index fe86c516f0..0000000000Binary files a/packages/desktop-client/src/components/select/DateSelect.right.png and /dev/null differdiff --git a/packages/desktop-client/src/components/select/DateSelect.tsx b/packages/desktop-client/src/components/select/DateSelect.tsxindex 4ee71cc70c..0a3a5ae8bb 100644--- a/packages/desktop-client/src/components/select/DateSelect.tsx+++ b/packages/desktop-client/src/components/select/DateSelect.tsx@@ -3,7 +3,6 @@ import {useEffect,useEffectEvent,useImperativeHandle,- useLayoutEffect,useMemo,useRef,useState,@@ -15,8 +14,23 @@ import type {KeyboardEvent,Ref,} from 'react';+import {+ Calendar,+ CalendarCell,+ CalendarGrid,+ CalendarGridBody,+ CalendarGridHeader,+ CalendarHeaderCell,+ Heading,+ I18nProvider,+} from 'react-aria-components';+import { useTranslation } from 'react-i18next';import { useResponsive } from '@actual-app/components/hooks/useResponsive';+import {+ SvgCheveronLeft,+ SvgCheveronRight,+} from '@actual-app/components/icons/v1';import { Input } from '@actual-app/components/input';import { Popover } from '@actual-app/components/popover';import { styles } from '@actual-app/components/styles';@@ -31,100 +45,116 @@ import {getShortYearRegex,} from '@actual-app/core/shared/months';import { css } from '@emotion/css';+import { CalendarDate } from '@internationalized/date';import { addDays, format, isValid, parse, parseISO, subDays } from 'date-fns';-import type { Locale } from 'date-fns';-import Pikaday from 'pikaday';-import 'pikaday/css/pikaday.css';+import { InputField } from '#components/mobile/MobileForms';-import { useLocale } from '#hooks/useLocale';+import { useLanguage } from '#hooks/useLocale';import { useMergedRefs } from '#hooks/useMergedRefs';import { useSyncedPref } from '#hooks/useSyncedPref';-import DateSelectLeft from './DateSelect.left.png';-import DateSelectRight from './DateSelect.right.png';+const FIRST_DAY_OF_WEEK_NAMES = [+ 'sun',+ 'mon',+ 'tue',+ 'wed',+ 'thu',+ 'fri',+ 'sat',+] as const;++type FirstDayOfWeek = (typeof FIRST_DAY_OF_WEEK_NAMES)[number];++export function getFirstDayOfWeek(idx: string | undefined): FirstDayOfWeek {+ return FIRST_DAY_OF_WEEK_NAMES[parseInt(idx || '0', 10) || 0];+}++function toCalendarDate(date: Date): CalendarDate {+ return new CalendarDate(+ date.getFullYear(),+ date.getMonth() + 1,+ date.getDate(),+ );+}++function fromCalendarDate(date: CalendarDate): Date {+ return new Date(date.year, date.month - 1, date.day);+}const pickerStyles: CSSProperties = {- '& .pika-single.actual-date-picker': {+ '& .react-aria-Calendar': {color: theme.calendarText,background: theme.calendarBackground,- border: 'none',boxShadow: '0 0px 4px rgba(0, 0, 0, .25)',borderRadius: 4,+ padding: 10,},-- '& .actual-date-picker': {- '& .pika-lendar': {- float: 'none',- width: 'auto',- },- // month/year- '& .pika-label': {- backgroundColor: theme.calendarBackground,- },- // Back/forward buttons- '& .pika-prev': {- backgroundImage: `url(${DateSelectLeft})`,+ '& .calendar-header': {+ display: 'flex',+ flexDirection: 'row',+ alignItems: 'center',+ justifyContent: 'space-between',+ marginBottom: 6,+ '& button': {+ color: 'inherit',+ background: 'none',+ border: 'none',+ borderRadius: 4,+ padding: 5,+ cursor: 'pointer',+ display: 'flex',+ '&:hover': { backgroundColor: theme.calendarItemBackground },},- '& .pika-next': {- backgroundImage: `url(${DateSelectRight})`,- },- // Day of week- '& .pika-table th': {- color: theme.calendarItemText,- '& abbr': { textDecoration: 'none' },- },- // Numbered days- '& .pika-button': {- backgroundColor: theme.calendarItemBackground,- color: theme.calendarItemText,+ },+ '& .calendar-header-title': {+ fontWeight: 'bold',+ fontSize: 14,+ margin: 0,+ backgroundColor: theme.calendarBackground,+ },+ '& .react-aria-CalendarGrid': {+ borderCollapse: 'collapse',+ },+ '& .react-aria-CalendarHeaderCell': {+ color: theme.calendarItemText,+ fontWeight: 'normal',+ textAlign: 'center',+ padding: '2px 0',+ },+ '& .react-aria-CalendarCell': {+ width: 28,+ height: 28,+ lineHeight: '28px',+ textAlign: 'center',+ cursor: 'pointer',+ backgroundColor: theme.calendarItemBackground,+ color: theme.calendarItemText,++ '&[data-outside-month]': {+ opacity: 0.4,},- '& .is-today .pika-button': {+ '&[data-today]': {textDecoration: 'underline',},- '& .is-selected .pika-button': {+ '&[data-selected]': {backgroundColor: theme.calendarSelectedBackground,- boxShadow: 'none',+ borderRadius: 4,+ },+ '&[data-disabled]': {+ opacity: 0.4,+ cursor: 'default',+ },+ '&[data-focus-visible]': {+ outline: `2px solid ${theme.calendarSelectedBackground}`,},},};-type PikadayI18n = {- previousMonth: string;- nextMonth: string;- months: string[];- weekdays: string[];- weekdaysShort: string[];-};--function createPikadayLocale(dateFnsLocale: Locale): PikadayI18n {- const months = Array.from({ length: 12 }, (_, i) =>- format(new Date(2023, i, 1), 'MMMM', { locale: dateFnsLocale }),- );-- const weekdays = Array.from({ length: 7 }, (_, i) =>- format(new Date(2023, 0, i + 1), 'EEEE', { locale: dateFnsLocale }),- );-- const weekdaysShort = Array.from({ length: 7 }, (_, i) =>- format(new Date(2023, 0, i + 1), 'EEE', { locale: dateFnsLocale }).slice(- 0,- 3,- ),- );-- return {- previousMonth: 'Previous',- nextMonth: 'Next',- months,- weekdays,- weekdaysShort,- };-}-type DatePickerProps = {value: string;- firstDayOfWeekIdx: string;dateFormat: string;+ locale: string;+ firstDayOfWeek: FirstDayOfWeek;onUpdate: (selectedDate: Date) => void;onSelect: (selectedDate: Date) => void;};@@ -133,10 +163,23 @@ type DatePickerForwardedRef = {handleInputKeyDown: (e: KeyboardEvent<HTMLInputElement>) => void;};const DatePicker = forwardRef<DatePickerForwardedRef, DatePickerProps>(- ({ value, firstDayOfWeekIdx, dateFormat, onUpdate, onSelect }, ref) => {- const locale = useLocale();- const picker = useRef<Pikaday | null>(null);- const mountPoint = useRef<HTMLDivElement | null>(null);+ ({ value, dateFormat, locale, firstDayOfWeek, onUpdate, onSelect }, ref) => {+ const { t } = useTranslation();+ const parsedValue = value ? parse(value, dateFormat, currentDate()) : null;+ const focusedCalendarDate = toCalendarDate(+ parsedValue && isValid(parsedValue) ? parsedValue : currentDate(),+ );++ // Controlled so the header arrows can change the visible month without+ // involving focus: react-aria's own prev/next buttons steal focus from+ // the text input on press, whose blur closes the picker.+ const [focusedDate, setFocusedDate] = useState(focusedCalendarDate);+ const focusedKey = focusedCalendarDate.toString();+ const [prevFocusedKey, setPrevFocusedKey] = useState(focusedKey);+ if (prevFocusedKey !== focusedKey) {+ setPrevFocusedKey(focusedKey);+ setFocusedDate(focusedCalendarDate);+ }const onUpdateEffect = useEffectEvent(onUpdate);@@ -144,80 +187,83 @@ const DatePicker = forwardRef<DatePickerForwardedRef, DatePickerProps>(ref,() => ({handleInputKeyDown(e) {- const currentDate = picker.current?.getDate();- if (!currentDate) return;+ const jsDate = fromCalendarDate(focusedCalendarDate);let newDate = null;switch (e.key) {case 'ArrowLeft':e.preventDefault();- newDate = subDays(currentDate, 1);+ newDate = subDays(jsDate, 1);break;case 'ArrowUp':e.preventDefault();- newDate = subDays(currentDate, 7);+ newDate = subDays(jsDate, 7);break;case 'ArrowRight':e.preventDefault();- newDate = addDays(currentDate, 1);+ newDate = addDays(jsDate, 1);break;case 'ArrowDown':e.preventDefault();- newDate = addDays(currentDate, 7);+ newDate = addDays(jsDate, 7);break;default:}if (newDate) {- picker.current?.setDate(newDate, true);- onUpdateEffect?.(newDate);+ onUpdateEffect(newDate);}},}),- [],+ [focusedCalendarDate],);- const initPikaday = useEffectEvent(() => {- const pikadayLocale = createPikadayLocale(locale);- return new Pikaday({- theme: 'actual-date-picker',- keyboardInput: false,- firstDay: parseInt(firstDayOfWeekIdx),- defaultDate: value- ? parse(value, dateFormat, currentDate())- : currentDate(),- setDefaultDate: true,- toString(date) {- return format(date, dateFormat);- },- parse(dateString) {- return parse(dateString, dateFormat, new Date());- },- onSelect,- i18n: pikadayLocale,- });- });-- useLayoutEffect(() => {- picker.current = initPikaday();- mountPoint.current?.appendChild(picker.current.el);-- return () => {- picker.current?.destroy();- };- }, []);-- useEffect(() => {- if (value) {- picker.current?.setDate(parse(value, dateFormat, new Date()), true);- }- }, [value, dateFormat]);-return (<ViewclassName={css([pickerStyles, { flex: 1 }])}- innerRef={mountPoint}- />+ data-date-picker+ onMouseDown={e => e.preventDefault()}+ >+ <I18nProvider locale={locale}>+ <Calendar+ value={focusedCalendarDate}+ focusedValue={focusedDate}+ onFocusChange={setFocusedDate}+ firstDayOfWeek={firstDayOfWeek}+ onChange={date => onSelect(fromCalendarDate(date))}+ >+ <View className="calendar-header">+ <button+ type="button"+ tabIndex={-1}+ aria-label={t('Previous month')}+ onClick={() => setFocusedDate(d => d.subtract({ months: 1 }))}+ >+ <SvgCheveronLeft width={16} height={16} />+ </button>+ <Heading className="calendar-header-title" />+ <button+ type="button"+ tabIndex={-1}+ aria-label={t('Next month')}+ onClick={() => setFocusedDate(d => d.add({ months: 1 }))}+ >+ <SvgCheveronRight width={16} height={16} />+ </button>+ </View>+ <CalendarGrid>+ <CalendarGridHeader>+ {day => (+ <CalendarHeaderCell>{day.slice(0, 2)}</CalendarHeaderCell>+ )}+ </CalendarGridHeader>+ <CalendarGridBody>+ {date => <CalendarCell date={date} />}+ </CalendarGridBody>+ </CalendarGrid>+ </Calendar>+ </I18nProvider>+ </View>);},);@@ -278,7 +324,9 @@ function DateSelectDesktop({const [selectedValue, setSelectedValue] = useState(value);const [_firstDayOfWeekIdx] = useSyncedPref('firstDayOfWeekIdx');- const firstDayOfWeekIdx = _firstDayOfWeekIdx || '0';+ const firstDayOfWeek = getFirstDayOfWeek(_firstDayOfWeekIdx);++ const locale = useLanguage();useEffect(() => setValue(parsedDefaultValue), [parsedDefaultValue]);@@ -380,7 +428,7 @@ function DateSelectDesktop({isOpen={open}isNonModalonOpenChange={() => setOpen(false)}- style={{ ...styles.popover, minWidth: 225 }}+ style={styles.popover}data-testid="date-select-tooltip">{content}@@ -409,6 +457,16 @@ function DateSelectDesktop({inputProps?.onFocus?.(e);}}onBlur={e => {+ // react-aria moves focus into the calendar when it's clicked; keep+ // the picker open and pull focus back so keyboard entry still works+ // (with pikaday, focus never left the input).+ if (+ e.relatedTarget instanceof Element &&+ e.relatedTarget.closest('[data-date-picker]')+ ) {+ innerRef.current?.focus();+ return;+ }if (!embedded) {setOpen(false);}@@ -440,8 +498,9 @@ function DateSelectDesktop({<DatePickerref={picker}value={selectedValue}- firstDayOfWeekIdx={firstDayOfWeekIdx}dateFormat={dateFormat}+ locale={locale}+ firstDayOfWeek={firstDayOfWeek}onUpdate={date => {setSelectedValue(format(date, dateFormat));onUpdate?.(format(date, 'yyyy-MM-dd'));diff --git a/packages/desktop-client/src/hooks/useDaysOfWeek.ts b/packages/desktop-client/src/hooks/useDaysOfWeek.tsindex dcfd0b0fe5..86ebab39ef 100644--- a/packages/desktop-client/src/hooks/useDaysOfWeek.ts+++ b/packages/desktop-client/src/hooks/useDaysOfWeek.ts@@ -1,7 +1,6 @@import { useTranslation } from 'react-i18next';-// Follows Pikaday 'firstDay' numbering-// https://github.com/Pikaday/Pikaday+// 0 = Sunday, 1 = Monday, ... 6 = Saturdayexport function useDaysOfWeek() {const { t } = useTranslation();diff --git a/packages/desktop-client/src/hooks/useFormulaExecution.ts b/packages/desktop-client/src/hooks/useFormulaExecution.tsindex b85ab98164..feebf2aaae 100644--- a/packages/desktop-client/src/hooks/useFormulaExecution.ts+++ b/packages/desktop-client/src/hooks/useFormulaExecution.ts@@ -21,7 +21,10 @@ import {normalizeQueryTimeFrameEnd,normalizeQueryTimeFrameStart,} from '#components/formula/queryTimeFrame';-import { calculateTimeRange } from '#components/reports/reportRanges';+import {+ asMonthSlidingTimeFrame,+ calculateTimeRange,+} from '#components/reports/reportRanges';import { bootstrapHyperFormula } from '#util/bootstrapHyperFormula';import { useGlobalPref } from './useGlobalPref';@@ -329,7 +332,9 @@ export async function buildFilteredTransactionsQuery(// Add date range filter if providedif (timeFrame && timeFrame.mode) {- const [calculatedStart, calculatedEnd] = calculateTimeRange(timeFrame);+ const [calculatedStart, calculatedEnd] = calculateTimeRange(+ asMonthSlidingTimeFrame(timeFrame),+ );const startDate = normalizeQueryTimeFrameStart(calculatedStart);const endDate = normalizeQueryTimeFrameEnd(calculatedEnd);@@ -524,7 +529,9 @@ async function extractQueryTimeframeStart(return monthUtils.currentMonth();}- const [startMonth] = calculateTimeRange(queryConfig.timeFrame);+ const [startMonth] = calculateTimeRange(+ asMonthSlidingTimeFrame(queryConfig.timeFrame),+ );return startMonth;}@@ -541,7 +548,9 @@ async function extractQueryTimeframeEnd(return monthUtils.currentMonth();}- const [, endMonth] = calculateTimeRange(queryConfig.timeFrame);+ const [, endMonth] = calculateTimeRange(+ asMonthSlidingTimeFrame(queryConfig.timeFrame),+ );return endMonth;}diff --git a/packages/desktop-client/src/hooks/useLocale.ts b/packages/desktop-client/src/hooks/useLocale.tsindex b982abd0ef..5ceb46fdaf 100644--- a/packages/desktop-client/src/hooks/useLocale.ts+++ b/packages/desktop-client/src/hooks/useLocale.ts@@ -1,14 +1,13 @@-import { useMemo } from 'react';-import { getLocale } from '@actual-app/core/shared/locale';import { useGlobalPref } from './useGlobalPref';-export function useLocale() {+/** The user's language code (BCP 47), falling back to the browser's. */+export function useLanguage() {const [language] = useGlobalPref('language');- const locale = useMemo(- () => getLocale(language ? language : (navigator.language ?? 'en-US')),- [language],- );- return locale;+ return language || navigator.language || 'en-US';+}++export function useLocale() {+ return getLocale(useLanguage());}diff --git a/packages/loot-core/src/shared/months.test.ts b/packages/loot-core/src/shared/months.test.tsindex cdee7651aa..b79fac192a 100644--- a/packages/loot-core/src/shared/months.test.ts+++ b/packages/loot-core/src/shared/months.test.ts@@ -3,3 +3,14 @@ import * as monthUtils from './months';test('range returns a full range', () => {expect(monthUtils.range('2016-10', '2018-01')).toMatchSnapshot();});++test('isValidYearMonthDay validates the day against the month and year', () => {+ expect(monthUtils.isValidYearMonthDay('2024-02-29')).toBe(true);+ expect(monthUtils.isValidYearMonthDay('2023-02-29')).toBe(false);+ expect(monthUtils.isValidYearMonthDay('2024-04-31')).toBe(false);+ expect(monthUtils.isValidYearMonthDay('2024-12-31')).toBe(true);+ expect(monthUtils.isValidYearMonthDay('2024-00-10')).toBe(false);+ expect(monthUtils.isValidYearMonthDay('2024-13-10')).toBe(false);+ expect(monthUtils.isValidYearMonthDay('2024-02-00')).toBe(false);+ expect(monthUtils.isValidYearMonthDay('2024-02')).toBe(false);+});diff --git a/packages/loot-core/src/shared/months.ts b/packages/loot-core/src/shared/months.tsindex 993a0735bb..690b1d116e 100644--- a/packages/loot-core/src/shared/months.ts+++ b/packages/loot-core/src/shared/months.ts@@ -97,6 +97,18 @@ export function isValidYearMonth(value: string): boolean {return month >= 1 && month <= 12;}+// Whether a value is day-shaped (`yyyy-MM-dd`) rather than month-shaped+// (`yyyy-MM`).+export function isValidYearMonthDay(value: string): boolean {+ const match = /^(\d{4})-(\d{2})-(\d{2})$/.exec(value);+ if (!match) return false;+ const year = Number(match[1]);+ const month = Number(match[2]);+ const day = Number(match[3]);+ if (month < 1 || month > 12) return false;+ return day >= 1 && day <= d.getDaysInMonth(new Date(year, month - 1));+}+export function weekFromDate(date: DateLike,firstDayOfWeekIdx: SyncedPrefs['firstDayOfWeekIdx'],diff --git a/upcoming-release-notes/month-range-picker-a11y-labels.md b/upcoming-release-notes/month-range-picker-a11y-labels.mdnew file mode 100644index 0000000000..748257bce0--- /dev/null+++ b/upcoming-release-notes/month-range-picker-a11y-labels.md@@ -0,0 +1,6 @@+---+category: Enhancement+authors: [tabedzki, rznn7, MatissJanis]+---++Add day-level date range selection to reports: the new date range picker lets you switch between picking whole months or exact days, and works the same in every browserdiff --git a/yarn.lock b/yarn.lockindex e0b1dbf4f3..3210555ef0 100644--- a/yarn.lock+++ b/yarn.lock@@ -72,6 +72,7 @@ __metadata:dependencies:"@chromatic-com/storybook": "npm:^5.2.1""@emotion/css": "npm:^11.13.5"+ "@internationalized/date": "npm:^3.12.2""@rolldown/plugin-babel": "npm:~0.2.3""@storybook/addon-a11y": "npm:^10.4.4""@storybook/addon-docs": "npm:^10.4.4"@@ -232,6 +233,7 @@ __metadata:"@emotion/css": "npm:^11.13.5""@fontsource-variable/inter": "npm:^5.2.8""@fontsource/redacted-script": "npm:^5.2.8"+ "@internationalized/date": "npm:^3.12.2""@lezer/highlight": "npm:^1.2.3""@playwright/test": "npm:1.59.1""@react-aria/interactions": "npm:^3.28.1"@@ -243,7 +245,6 @@ __metadata:"@testing-library/jest-dom": "npm:^6.9.1""@testing-library/react": "npm:16.3.2""@testing-library/user-event": "npm:14.6.1"- "@types/pikaday": "npm:^1.7.10""@types/react": "npm:^19.2.17""@types/react-dom": "npm:^19.2.3""@typescript/native-preview": "npm:beta"@@ -268,7 +269,6 @@ __metadata:jsdom: "npm:^29.1.1"lru-cache: "npm:^11.5.1"mdast-util-newline-to-break: "npm:^2.0.0"- pikaday: "npm:1.8.2"plugins-service: "workspace:*"re-resizable: "npm:^6.11.2"react: "npm:19.2.7"@@ -9426,15 +9426,6 @@ __metadata:languageName: nodelinkType: hard-"@types/pikaday@npm:^1.7.10":- version: 1.7.10- resolution: "@types/pikaday@npm:1.7.10"- dependencies:- moment: "npm:>=2.29.2"- checksum: 10/638bc31725f4663c6266bb527d34d08740d8dc98c1c71efe53ef5bc63e177718e960f96f2719ee97f18ec7caf15e9f70d225e07f4d9ae1235384bb6da31a34a7- languageName: node- linkType: hard-"@types/plist@npm:^3.0.1":version: 3.0.5resolution: "@types/plist@npm:3.0.5"@@ -20966,13 +20957,6 @@ __metadata:languageName: nodelinkType: hard-"moment@npm:>=2.29.2":- version: 2.30.1- resolution: "moment@npm:2.30.1"- checksum: 10/ae42d876d4ec831ef66110bdc302c0657c664991e45cf2afffc4b0f6cd6d251dde11375c982a5c0564ccc0fa593fc564576ddceb8c8845e87c15f58aa6baca69- languageName: node- linkType: hard-"mrmime@npm:^2.0.0":version: 2.0.1resolution: "mrmime@npm:2.0.1"@@ -22653,13 +22637,6 @@ __metadata:languageName: nodelinkType: hard-"pikaday@npm:1.8.2":- version: 1.8.2- resolution: "pikaday@npm:1.8.2"- checksum: 10/88dbf7cd9ac61340910e845dc7310160b50ec86bc4cfb59a766820caad805de05584287ba6982ea047219f2a8a49ff8fa89934332dc559062c45d7c65782d2ef- languageName: node- linkType: hard-"pkg-dir@npm:^5.0.0":version: 5.0.0resolution: "pkg-dir@npm:5.0.0"