feat(settings): every date picker starts its week on the day you pick

Settings > General > Language & region gets "Week starts on" (Monday,
Sunday or Saturday), and Admin > User Defaults a default for everyone who
has not picked one. Monday stays the built-in value, so nothing changes
for anyone who leaves it alone.

Both calendar implementations follow it: CustomDatePicker, used by trip
dates, bookings, costs, to-dos and the admin school holidays on desktop
and phone, and the journey date picker, whose weekday headers were
hardcoded English and now speak the app language. The grid math and the
header row live in one helper (utils/calendarWeek.ts). The day names on
the options come from Intl, so only the label and a hint needed
translating. Vacay keeps its own per-plan week start.

The value is validated like the other regional settings: VALID_VALUES for
admin defaults, the display-settings MCP tool, and the managed key list.

Addresses discussion #2029.
This commit is contained in:
Maurice
2026-09-24 21:56:10 +02:00
parent 196dc12762
commit 7ce31756a3
84 changed files with 511 additions and 106 deletions
@@ -1,4 +1,4 @@
// FE-ADMIN-DUS-001 to FE-ADMIN-DUS-027
// FE-ADMIN-DUS-001 to FE-ADMIN-DUS-028
import { render, screen, waitFor, within, fireEvent } from '../../../tests/helpers/render';
import userEvent from '@testing-library/user-event';
import { http, HttpResponse } from 'msw';
@@ -453,3 +453,18 @@ describe('DefaultUserSettingsTab', () => {
expect(screen.queryByText('Shared CARTO key')).not.toBeInTheDocument();
});
});
describe('DefaultUserSettingsTab week start (#2029)', () => {
it('FE-ADMIN-DUS-028: the week-start default saves its own key and can be reset', async () => {
const user = userEvent.setup();
const { puts } = stubDefaults();
render(<DefaultUserSettingsTab />);
await screen.findByText('Default User Settings');
await user.click(screen.getByRole('button', { name: 'Sunday' }));
await waitFor(() => expect(resetLink('Week starts on')).toBeInTheDocument());
await user.click(resetLink('Week starts on'));
await waitFor(() => expect(puts).toEqual([{ week_start: 'sunday' }, { week_start: null }]));
});
});
@@ -7,7 +7,8 @@ import Section from '../Settings/Section'
import CustomSelect from '../shared/CustomSelect'
import { MapView } from '../Map/MapView'
import { SYMBOLS, currenciesWith } from '../Budget/BudgetPanel.constants'
import type { DistanceUnit, Place } from '../../types'
import type { DistanceUnit, Place, WeekStart } from '../../types'
import { weekStartOptions } from '../../utils/calendarWeek'
import { normalizeTileUrl, withTileApiKey } from '../../utils/tileUrl'
import {
MAPBOX_DEFAULT_STYLE,
@@ -40,6 +41,7 @@ type Defaults = RoutingDefaults & {
distance_unit?: DistanceUnit
dark_mode?: string | boolean
time_format?: string
week_start?: WeekStart
default_currency?: string
blur_booking_codes?: boolean
map_tile_url?: string
@@ -112,7 +114,7 @@ function OptionButton({
}
export default function DefaultUserSettingsTab(): React.ReactElement {
const { t } = useTranslation()
const { t, locale } = useTranslation()
const toast = useToast()
const [defaults, setDefaults] = useState<Defaults>({})
const [loaded, setLoaded] = useState(false)
@@ -302,6 +304,15 @@ export default function DefaultUserSettingsTab(): React.ReactElement {
))}
</OptionRow>
{/* Week start: the first column of every date picker (#2029) */}
<OptionRow label={<>{t('settings.weekStart')} <ResetButton field="week_start" /></>}>
{weekStartOptions(locale).map(opt => (
<OptionButton key={opt.value} active={defaults.week_start === opt.value} onClick={() => save({ week_start: opt.value })}>
{opt.label}
</OptionButton>
))}
</OptionRow>
{/* Default Currency */}
<div>
<label className="block text-sm font-medium mb-1.5 text-content-secondary">
@@ -1,9 +1,10 @@
// FE-COMP-JOURNEYDATEPICKER-001 to FE-COMP-JOURNEYDATEPICKER-006
// FE-COMP-JOURNEYDATEPICKER-001 to FE-COMP-JOURNEYDATEPICKER-007
import React from 'react'
import { describe, it, expect, vi } from 'vitest'
import { render, screen } from '../../../tests/helpers/render'
import userEvent from '@testing-library/user-event'
import { DatePicker } from './JourneyDetailPageDatePicker'
import { useSettingsStore } from '../../store/settingsStore'
function open(value = '2026-09-11') {
const onChange = vi.fn()
@@ -19,7 +20,7 @@ describe('DatePicker year navigation (#2318)', () => {
const user = userEvent.setup()
open()
await user.click(screen.getByText(/Sep 11, 2026/))
expect(screen.getByText('Mo')).toBeInTheDocument()
expect(screen.getByText('Mon')).toBeInTheDocument()
expect(screen.getByRole('button', { name: 'Select month' })).toHaveTextContent('September 2026')
})
@@ -29,7 +30,7 @@ describe('DatePicker year navigation (#2318)', () => {
await user.click(screen.getByText(/Sep 11, 2026/))
await user.click(screen.getByRole('button', { name: 'Select month' }))
expect(screen.queryByText('Mo')).not.toBeInTheDocument()
expect(screen.queryByText('Mon')).not.toBeInTheDocument()
expect(screen.getByRole('button', { name: 'Jan' })).toBeInTheDocument()
expect(screen.getByRole('button', { name: 'Select year' })).toHaveTextContent('2026')
@@ -51,7 +52,7 @@ describe('DatePicker year navigation (#2318)', () => {
expect(screen.getByRole('button', { name: 'Select year' })).toHaveTextContent('2023')
await user.click(screen.getByRole('button', { name: 'Mar' }))
expect(screen.getByRole('button', { name: 'Select month' })).toHaveTextContent('March 2023')
expect(screen.getByText('Mo')).toBeInTheDocument()
expect(screen.getByText('Mon')).toBeInTheDocument()
})
it('FE-COMP-JOURNEYDATEPICKER-004: the arrows step the level they are on', async () => {
@@ -83,7 +84,7 @@ describe('DatePicker year navigation (#2318)', () => {
await user.click(screen.getByRole('button', { name: 'Mar' }))
await user.click(screen.getByRole('button', { name: '15' }))
expect(onChange).toHaveBeenCalledWith('2023-03-15')
expect(screen.queryByText('Mo')).not.toBeInTheDocument()
expect(screen.queryByText('Mon')).not.toBeInTheDocument()
})
it('FE-COMP-JOURNEYDATEPICKER-006: reopening starts on the days again', async () => {
@@ -96,6 +97,25 @@ describe('DatePicker year navigation (#2318)', () => {
await user.click(trigger)
expect(screen.queryByRole('button', { name: '2023' })).not.toBeInTheDocument()
await user.click(trigger)
expect(screen.getByText('Mo')).toBeInTheDocument()
expect(screen.getByText('Mon')).toBeInTheDocument()
})
})
describe('DatePicker week start (#2029)', () => {
it('FE-COMP-JOURNEYDATEPICKER-007: follows the first weekday the user picked, like the other date pickers', async () => {
const original = useSettingsStore.getState().settings
useSettingsStore.setState({ settings: { ...original, week_start: 'sunday' } })
try {
const user = userEvent.setup()
render(<DatePicker value="2026-03-15" onChange={vi.fn()} />)
await user.click(screen.getByText(/Mar 15, 2026/))
const header = screen.getByText('Sun').parentElement!
expect(Array.from(header.children).map(c => c.textContent)).toEqual(['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'])
// 1 March 2026 is a Sunday, so it opens the first row without a blank before it.
const day1 = screen.getByRole('button', { name: '1' })
expect(Array.from(day1.parentElement!.children).indexOf(day1)).toBe(0)
} finally {
useSettingsStore.setState({ settings: original })
}
})
})
@@ -2,6 +2,8 @@ import { useState } from 'react'
import { localIsoDate } from '../../utils/localDate'
import { ArrowLeft, ChevronRight, Calendar } from 'lucide-react'
import { useTranslation } from '../../i18n'
import { useWeekStartDay } from '../../hooks/useWeekStartDay'
import { leadingBlanks, weekdayLabels } from '../../utils/calendarWeek'
/**
* The header steps up a level on each click, days → months → years, and a
@@ -18,7 +20,8 @@ export function DatePicker({ value, onChange, tripDates }: {
onChange: (date: string) => void
tripDates?: Set<string>
}) {
const { t } = useTranslation()
const { t, locale } = useTranslation()
const weekStart = useWeekStartDay()
const [open, setOpen] = useState(false)
const [view, setView] = useState<CalendarView>('days')
const [yearPageStart, setYearPageStart] = useState(0)
@@ -28,9 +31,9 @@ export function DatePicker({ value, onChange, tripDates }: {
})
const daysInMonth = new Date(viewMonth.year, viewMonth.month + 1, 0).getDate()
// Monday-first, matching CustomDateTimePicker / VacayCalendar (getDay() is Sunday=0).
const firstDow = (new Date(viewMonth.year, viewMonth.month, 1).getDay() + 6) % 7
const monthName = new Date(viewMonth.year, viewMonth.month).toLocaleDateString(undefined, { month: 'long', year: 'numeric' })
// Rows open on the user's week_start, like CustomDateTimePicker (#2029).
const firstDow = leadingBlanks(viewMonth.year, viewMonth.month, weekStart)
const monthName = new Date(viewMonth.year, viewMonth.month).toLocaleDateString(locale, { month: 'long', year: 'numeric' })
const prevMonth = () => {
setViewMonth(p => p.month === 0 ? { year: p.year - 1, month: 11 } : { ...p, month: p.month - 1 })
@@ -89,10 +92,10 @@ export function DatePicker({ value, onChange, tripDates }: {
for (let d = 1; d <= daysInMonth; d++) cells.push(d)
const monthNames = Array.from({ length: 12 }, (_, i) =>
new Date(viewMonth.year, i).toLocaleDateString(undefined, { month: 'short' }))
new Date(viewMonth.year, i).toLocaleDateString(locale, { month: 'short' }))
const years = Array.from({ length: YEAR_PAGE_SIZE }, (_, i) => yearPageStart + i)
const formatted = value ? new Date(value + 'T00:00:00').toLocaleDateString(undefined, { month: 'short', day: 'numeric', year: 'numeric' }) : null
const formatted = value ? new Date(value + 'T00:00:00').toLocaleDateString(locale, { month: 'short', day: 'numeric', year: 'numeric' }) : null
const navButton = 'w-7 h-7 rounded-lg hover:bg-zinc-100 dark:hover:bg-zinc-700 flex items-center justify-center text-zinc-500'
const gridCell = (selected: boolean) => `h-9 rounded-lg text-[12px] font-medium flex items-center justify-center transition-colors ${
@@ -168,7 +171,7 @@ export function DatePicker({ value, onChange, tripDates }: {
<>
{/* Weekday headers */}
<div className="grid grid-cols-7 mb-1">
{['Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa', 'Su'].map((d, i) => (
{weekdayLabels(locale, weekStart, 'short').map((d, i) => (
<div key={i} className="text-center text-[10px] font-medium text-zinc-400 py-1">{d}</div>
))}
</div>
@@ -1,4 +1,4 @@
// FE-COMP-DISPLAY-001 to FE-COMP-DISPLAY-052
// FE-COMP-DISPLAY-001 to FE-COMP-DISPLAY-054
import { render, screen, within, fireEvent } from '../../../tests/helpers/render';
import userEvent from '@testing-library/user-event';
import { http, HttpResponse } from 'msw';
@@ -444,3 +444,32 @@ describe('DisplaySettingsTab – startup destination', () => {
expect(await screen.findByText('Start locked')).toBeInTheDocument();
});
});
// ── Week start (053, 054) ─────────────────────────────────────────────────────
describe('DisplaySettingsTab week start (#2029)', () => {
it('FE-COMP-DISPLAY-053: shows Monday when unset and saves the day picked', async () => {
const user = userEvent.setup();
const updateSetting = vi.fn().mockResolvedValue(undefined);
seedStore(useSettingsStore, { settings: buildSettings({ week_start: undefined }), updateSetting });
render(<DisplaySettingsTab />);
expect(screen.getByText('Week starts on')).toBeInTheDocument();
await user.click(screen.getByRole('button', { name: /Monday/ }));
await user.click(await screen.findByText('Sunday'));
expect(updateSetting).toHaveBeenCalledWith('week_start', 'sunday');
});
it('FE-COMP-DISPLAY-054: a rejected change surfaces the error', async () => {
const user = userEvent.setup();
const updateSetting = vi.fn().mockRejectedValue(new Error('Save failed'));
seedStore(useSettingsStore, { settings: buildSettings({ week_start: 'sunday' }), updateSetting });
render(<><ToastContainer /><DisplaySettingsTab /></>);
await user.click(screen.getByRole('button', { name: /Sunday/ }));
await user.click(await screen.findByText('Saturday'));
expect(await screen.findByText('Save failed')).toBeInTheDocument();
});
});
@@ -9,10 +9,12 @@ import Section from './Section'
import { TRIP_TAB_IDS, TRIP_TAB_LABEL_KEYS } from '../../constants/tripTabs'
import { DEFAULT_START_PAGE, DEFAULT_START_TRIP_TAB } from '../../utils/startDestination'
import type { DistanceUnit } from '../../types'
import { DEFAULT_WEEK_START } from '@trek/shared'
import { weekStartOptions } from '../../utils/calendarWeek'
export default function DisplaySettingsTab(): React.ReactElement {
const { settings, updateSetting } = useSettingsStore()
const { t } = useTranslation()
const { t, locale } = useTranslation()
const toast = useToast()
const [tempUnit, setTempUnit] = useState<string>(settings.temperature_unit || DEFAULT_SETTINGS.temperature_unit)
const [distanceUnit, setDistanceUnit] = useState<DistanceUnit>(settings.distance_unit || DEFAULT_SETTINGS.distance_unit)
@@ -285,6 +287,20 @@ export default function DisplaySettingsTab(): React.ReactElement {
))}
</div>
</div>
{/* Week start: the first column of every date picker (#2029) */}
<div>
<label className="block text-sm font-medium mb-2 text-content-secondary">{t('settings.weekStart')}</label>
<CustomSelect
value={settings.week_start || DEFAULT_WEEK_START}
onChange={async v => {
try { await updateSetting('week_start', String(v)) }
catch (e: unknown) { toast.error(e instanceof Error ? e.message : t('common.error')) }
}}
options={weekStartOptions(locale)}
/>
<p className="text-xs text-content-faint mt-2">{t('settings.weekStartHint')}</p>
</div>
</Section>
<Section title={t('settings.general.travelMap')} icon={Map}>
@@ -787,3 +787,35 @@ describe('CustomDateTimePicker branches', () => {
expect(onChange).toHaveBeenCalledWith('2026-03-15');
});
});
// ─── Week start (#2029) ───────────────────────────────────────────────────────
describe('CustomDatePicker week start (#2029)', () => {
const onChange = vi.fn();
const original = useSettingsStore.getState().settings;
afterEach(() => useSettingsStore.setState({ settings: original }));
/** The weekday header row and how many blanks precede the 1st, read off the open calendar. */
async function openMarch2026(weekStart?: 'monday' | 'sunday' | 'saturday') {
useSettingsStore.setState({ settings: { ...original, week_start: weekStart } });
const user = userEvent.setup();
render(<CustomDatePicker value="2026-03-15" onChange={onChange} />);
await user.click(screen.getAllByRole('button')[0]);
const day1 = screen.getAllByRole('button').find((b) => b.textContent?.trim() === '1')!;
const grid = day1.parentElement!;
return { header: grid.previousElementSibling!.textContent, blanks: Array.from(grid.children).indexOf(day1) };
}
it('FE-COMP-DATEPICKER-033: rows start on Monday when nothing is set', async () => {
// 1 March 2026 is a Sunday: the last column of a Monday-first row.
expect(await openMarch2026(undefined)).toEqual({ header: 'MTWTFSS', blanks: 6 });
});
it('FE-COMP-DATEPICKER-034: rows start on the day the user picked', async () => {
expect(await openMarch2026('sunday')).toEqual({ header: 'SMTWTFS', blanks: 0 });
});
it('FE-COMP-DATEPICKER-035: a Saturday start puts the Sunday 1st in the second column', async () => {
expect(await openMarch2026('saturday')).toEqual({ header: 'SSMTWTF', blanks: 1 });
});
});
@@ -4,13 +4,12 @@ import React, { useEffect, useRef, useState } from 'react';
import { createPortal } from 'react-dom';
import { useTranslation } from '../../i18n';
import { useRemeasureSignal } from '../../hooks/useAnchoredPosition';
import { useWeekStartDay } from '../../hooks/useWeekStartDay';
import { leadingBlanks, weekdayLabels } from '../../utils/calendarWeek';
function daysInMonth(year: number, month: number): number {
return new Date(year, month + 1, 0).getDate();
}
function getWeekday(year: number, month: number, day: number): number {
return new Date(year, month, day).getDay();
}
const YEAR_PAGE_SIZE = 12;
type CalendarView = 'days' | 'months' | 'years';
@@ -41,6 +40,7 @@ export function CustomDatePicker({
max,
}: CustomDatePickerProps) {
const { locale, t } = useTranslation();
const weekStart = useWeekStartDay();
const [open, setOpen] = useState(false);
const [view, setView] = useState<CalendarView>('days');
const [yearPageStart, setYearPageStart] = useState(0);
@@ -140,10 +140,8 @@ export function CustomDatePicker({
};
const days = daysInMonth(viewYear, viewMonth);
const startDay = (getWeekday(viewYear, viewMonth, 1) + 6) % 7;
const weekdays = Array.from({ length: 7 }, (_, i) =>
new Date(2024, 0, i + 1).toLocaleDateString(locale, { weekday: 'narrow' })
);
const startDay = leadingBlanks(viewYear, viewMonth, weekStart);
const weekdays = weekdayLabels(locale, weekStart);
const monthNames = Array.from({ length: 12 }, (_, i) =>
new Date(viewYear, i).toLocaleDateString(locale, { month: 'short' })
+7
View File
@@ -0,0 +1,7 @@
import { useSettingsStore } from '../store/settingsStore'
import { weekStartDay } from '../utils/calendarWeek'
/** The current user's first weekday as a Date#getDay() number (#2029). */
export function useWeekStartDay(): number {
return weekStartDay(useSettingsStore(s => s.settings.week_start))
}
@@ -5,7 +5,8 @@ import { useTranslation } from '../../../i18n'
import { useToast } from '../../../components/shared/Toast'
import { MapView } from '../../../components/Map/MapView'
import { SYMBOLS, currenciesWith } from '../../../components/Budget/BudgetPanel.constants'
import { getApiErrorMessage, type DistanceUnit, type Place } from '../../../types'
import { getApiErrorMessage, type DistanceUnit, type Place, type WeekStart } from '../../../types'
import { weekStartOptions } from '../../../utils/calendarWeek'
import { normalizeTileUrl, withTileApiKey } from '../../../utils/tileUrl'
import {
MAPBOX_DEFAULT_STYLE,
@@ -43,6 +44,7 @@ type Defaults = RoutingDefaults & {
distance_unit?: DistanceUnit
dark_mode?: string | boolean
time_format?: string
week_start?: WeekStart
default_currency?: string
blur_booking_codes?: boolean
map_tile_url?: string
@@ -71,7 +73,7 @@ function styleForProvider(provider: MapProvider, style?: string | null): string
// layer (adminApi defaults, per-change auto-save, reset-to-built-in) — only the
// presentation is relaid on the admin mobile design system.
export default function MAdminDefaultUserSettings(): React.ReactElement {
const { t } = useTranslation()
const { t, locale } = useTranslation()
const toast = useToast()
const [defaults, setDefaults] = useState<Defaults>({})
const [loaded, setLoaded] = useState(false)
@@ -253,6 +255,11 @@ export default function MAdminDefaultUserSettings(): React.ReactElement {
<MSegmented value={defaults.time_format || ''} onChange={(v) => save({ time_format: v })} options={timeOptions} />
</MAdminField>
{/* Week start (#2029) */}
<MAdminField label={<>{t('settings.weekStart')} <ResetButton field="week_start" /></>}>
<MSegmented value={defaults.week_start || ''} onChange={(v) => save({ week_start: v as WeekStart })} options={weekStartOptions(locale)} />
</MAdminField>
{/* Default Currency */}
<MAdminField
label={<>{t('settings.currency')} <ResetButton field="default_currency" /></>}
@@ -6,7 +6,9 @@ import { useToast } from '../../../components/shared/Toast'
import { SYMBOLS, currenciesWith } from '../../../components/Budget/BudgetPanel.constants'
import { TRIP_TAB_IDS, TRIP_TAB_LABEL_KEYS, isTripTabId } from '../../../constants/tripTabs'
import { DEFAULT_START_PAGE, DEFAULT_START_TRIP_TAB, type StartPage } from '../../../utils/startDestination'
import type { Settings, DistanceUnit } from '../../../types'
import type { Settings, DistanceUnit, WeekStart } from '../../../types'
import { DEFAULT_WEEK_START } from '@trek/shared'
import { weekStartOptions } from '../../../utils/calendarWeek'
import { MSetCard, MSetEyebrow, MSetSelectRow, MSetSegments, MSetRow } from './MSettingsUi'
import MToggle from '../../components/MToggle'
import MSetPickerSheet from './MSetPickerSheet'
@@ -16,7 +18,7 @@ import MSetPickerSheet from './MSetPickerSheet'
* cards, wired to the real user preferences (DisplaySettingsTab parity).
*/
export default function MSettingsGeneral() {
const { t } = useTranslation()
const { t, locale } = useTranslation()
const toast = useToast()
const { settings, updateSetting } = useSettingsStore()
const [currencyOpen, setCurrencyOpen] = useState(false)
@@ -143,6 +145,13 @@ export default function MSettingsGeneral() {
{ value: '12h', label: '12h' },
]}
/>
<MSetEyebrow className="mb-[6px] mt-[14px]">{t('settings.weekStart')}</MSetEyebrow>
<MSetSegments<WeekStart>
value={settings.week_start || DEFAULT_WEEK_START}
onChange={(v) => save('week_start', v)}
options={weekStartOptions(locale)}
/>
</MSetCard>
<MSetCard title={t('settings.general.travelMap')} icon={Map} className="mt-3">
+13 -13
View File
@@ -2284,13 +2284,13 @@ describe('JourneyDetailPage', () => {
// Calendar dropdown should show weekday headers
await waitFor(() => {
expect(screen.getByText('Su')).toBeInTheDocument();
expect(screen.getByText('Mo')).toBeInTheDocument();
expect(screen.getByText('Tu')).toBeInTheDocument();
expect(screen.getByText('We')).toBeInTheDocument();
expect(screen.getByText('Th')).toBeInTheDocument();
expect(screen.getByText('Fr')).toBeInTheDocument();
expect(screen.getByText('Sa')).toBeInTheDocument();
expect(screen.getByText('Sun')).toBeInTheDocument();
expect(screen.getByText('Mon')).toBeInTheDocument();
expect(screen.getByText('Tue')).toBeInTheDocument();
expect(screen.getByText('Wed')).toBeInTheDocument();
expect(screen.getByText('Thu')).toBeInTheDocument();
expect(screen.getByText('Fri')).toBeInTheDocument();
expect(screen.getByText('Sat')).toBeInTheDocument();
});
});
});
@@ -2309,12 +2309,12 @@ describe('JourneyDetailPage', () => {
// The calendar should have the month name and two navigation buttons
await waitFor(() => {
expect(screen.getByText('Su')).toBeInTheDocument();
expect(screen.getByText('Sun')).toBeInTheDocument();
});
// The calendar header has prev/next buttons. They are type="button" within the calendar dropdown.
// There should be navigation buttons around the month name
const calendarDropdown = screen.getByText('Su').closest('[class*="rounded-xl"]')!;
const calendarDropdown = screen.getByText('Sun').closest('[class*="rounded-xl"]')!;
const navButtons = calendarDropdown.querySelectorAll('button[type="button"]');
// At minimum: 2 nav buttons + day cells
expect(navButtons.length).toBeGreaterThanOrEqual(2);
@@ -2823,7 +2823,7 @@ describe('JourneyDetailPage', () => {
// Wait for calendar to open
await waitFor(() => {
expect(screen.getByText('Su')).toBeInTheDocument();
expect(screen.getByText('Sun')).toBeInTheDocument();
});
// Click day 15 (should be a button in the grid)
@@ -2835,7 +2835,7 @@ describe('JourneyDetailPage', () => {
// Calendar should close after selection
await waitFor(() => {
expect(screen.queryByText('Su')).not.toBeInTheDocument();
expect(screen.queryByText('Sun')).not.toBeInTheDocument();
});
});
});
@@ -2853,11 +2853,11 @@ describe('JourneyDetailPage', () => {
await user.click(dateBtn as HTMLElement);
await waitFor(() => {
expect(screen.getByText('Su')).toBeInTheDocument();
expect(screen.getByText('Sun')).toBeInTheDocument();
});
// Get current month name
const calendarDropdown = screen.getByText('Su').closest('[class*="rounded-xl"]')!;
const calendarDropdown = screen.getByText('Sun').closest('[class*="rounded-xl"]')!;
const monthText = calendarDropdown.querySelector('[class*="font-semibold"][class*="text-\\[13px\\]"]');
const currentMonth = monthText?.textContent || '';
+2 -1
View File
@@ -1,7 +1,7 @@
import { create } from 'zustand'
import { settingsApi } from '../api/client'
import type { Settings } from '../types'
import { DEFAULT_APPEARANCE } from '@trek/shared'
import { DEFAULT_APPEARANCE, DEFAULT_WEEK_START } from '@trek/shared'
import { getApiErrorMessage } from '../types'
import { SUPPORTED_LANGUAGE_CODES } from '../i18n/supportedLanguages'
import { normalizeTileUrl, stripTileApiKey } from '../utils/tileUrl'
@@ -84,6 +84,7 @@ export const DEFAULT_SETTINGS: Settings = {
temperature_unit: 'celsius',
distance_unit: 'metric',
time_format: '24h',
week_start: DEFAULT_WEEK_START,
show_place_description: false,
optimize_from_accommodation: true,
map_provider: 'leaflet',
+4
View File
@@ -29,6 +29,7 @@ import type {
Tag,
Category,
AppearanceConfig,
WeekStart,
} from '@trek/shared'
export type {
@@ -53,6 +54,7 @@ export type {
Tag,
Category,
AppearanceConfig,
WeekStart,
}
export interface User {
@@ -128,6 +130,8 @@ export interface Settings {
temperature_unit: string
distance_unit?: DistanceUnit
time_format: string
/** First column of every date picker (#2029); missing means Monday. */
week_start?: WeekStart
show_place_description: boolean
blur_booking_codes?: boolean
map_booking_labels?: boolean
+47
View File
@@ -0,0 +1,47 @@
// FE-UTIL-CALWEEK-001 to FE-UTIL-CALWEEK-005
import { describe, it, expect } from 'vitest'
import { leadingBlanks, weekdayLabels, weekStartDay, weekStartOptions } from './calendarWeek'
describe('calendarWeek (#2029)', () => {
it('FE-UTIL-CALWEEK-001: maps the setting to getDay() and falls back to Monday', () => {
expect(weekStartDay('monday')).toBe(1)
expect(weekStartDay('sunday')).toBe(0)
expect(weekStartDay('saturday')).toBe(6)
// Missing, unknown and the Vacay-style number all read as Monday, what every picker showed before.
expect(weekStartDay(undefined)).toBe(1)
expect(weekStartDay('friday')).toBe(1)
expect(weekStartDay(0)).toBe(1)
})
it('FE-UTIL-CALWEEK-002: counts the blanks before the 1st for each first weekday', () => {
// 1 March 2026 is a Sunday.
expect(leadingBlanks(2026, 2, 1)).toBe(6)
expect(leadingBlanks(2026, 2, 0)).toBe(0)
expect(leadingBlanks(2026, 2, 6)).toBe(1)
// 1 January 2024 is a Monday.
expect(leadingBlanks(2024, 0, 1)).toBe(0)
expect(leadingBlanks(2024, 0, 0)).toBe(1)
expect(leadingBlanks(2024, 0, 6)).toBe(2)
})
it('FE-UTIL-CALWEEK-003: rotates the header row to the first weekday', () => {
expect(weekdayLabels('en-US', 1, 'short')).toEqual(['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'])
expect(weekdayLabels('en-US', 0, 'short')).toEqual(['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'])
expect(weekdayLabels('en-US', 6, 'short')).toEqual(['Sat', 'Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri'])
expect(weekdayLabels('en-US', 0).join('')).toBe('SMTWTFS')
})
it('FE-UTIL-CALWEEK-004: speaks the app locale, not the browser one', () => {
expect(weekdayLabels('de-DE', 1, 'short')[0]).toBe('Mo')
})
it('FE-UTIL-CALWEEK-005: labels the choices with capitalised day names in the app language', () => {
expect(weekStartOptions('en-US')).toEqual([
{ value: 'monday', label: 'Monday' },
{ value: 'sunday', label: 'Sunday' },
{ value: 'saturday', label: 'Saturday' },
])
// French writes weekday names lower-case; standing alone on a button they start upper-case.
expect(weekStartOptions('fr-FR').map(o => o.label)).toEqual(['Lundi', 'Dimanche', 'Samedi'])
})
})
+42
View File
@@ -0,0 +1,42 @@
import { DEFAULT_WEEK_START, WEEK_START_DAY, WEEK_START_VALUES, type WeekStart } from '@trek/shared'
/**
* The calendar-grid half of the week_start setting (#2029): the one place a
* date picker asks which weekday opens a row, how many blanks go before the
* 1st, and what the header row says. Both pickers (CustomDatePicker and the
* journey DatePicker) read it, so they cannot drift apart again.
*/
/** Date#getDay() of the first weekday; a missing or unknown value is Monday, what every picker did before the setting. */
export function weekStartDay(value: unknown): number {
const known = (WEEK_START_VALUES as readonly unknown[]).includes(value)
return WEEK_START_DAY[known ? value as WeekStart : DEFAULT_WEEK_START]
}
/** Blank cells before the 1st of the month when rows begin on `weekStart`. */
export function leadingBlanks(year: number, month: number, weekStart: number): number {
return (new Date(year, month, 1).getDay() - weekStart + 7) % 7
}
// 7 January 2024 is a Sunday, so the 7th plus a getDay() number is that weekday.
function sampleDay(day: number): Date {
return new Date(2024, 0, 7 + day)
}
/** The header row of a month grid, starting on `weekStart`, in the app's locale. */
export function weekdayLabels(locale: string, weekStart: number, weekday: 'narrow' | 'short' = 'narrow'): string[] {
return Array.from({ length: 7 }, (_, i) => sampleDay((weekStart + i) % 7).toLocaleDateString(locale, { weekday }))
}
/**
* The choices for the setting, labelled with the day's own name in the app's
* language, so no locale file has to spell out seven weekdays. Capitalised
* because several languages write weekday names lower-case and these stand
* alone on a button.
*/
export function weekStartOptions(locale: string): { value: WeekStart; label: string }[] {
return WEEK_START_VALUES.map(value => {
const name = sampleDay(WEEK_START_DAY[value]).toLocaleDateString(locale, { weekday: 'long' })
return { value, label: name.charAt(0).toLocaleUpperCase(locale) + name.slice(1) }
})
}