fix(settings): let every date follow a date format of the user's choice

Every date in TREK was written in the interface language's format, and
English is en-US, so an English interface always showed and read
mm/dd/yyyy with no way to change it. A few native date inputs followed
the browser instead, so one screen could mix two formats.

date_format is now a user setting with an admin default, next to the
time format: automatic (the language's format, as before), YYYY-MM-DD,
YYYY/MM/DD, DD.MM.YYYY, DD/MM/YYYY or MM/DD/YYYY. The date picker shows,
pre-fills, hints and reads typed dates in it, and every date written in
numbers across the app (lists, cards, admin panels, CSV and PDF exports)
goes through one formatter. Dates written with a month name keep the
language's wording. The remaining native date inputs are the shared
picker now. The display settings MCP tool reads and writes the key.

Closes #2971
This commit is contained in:
Maurice
2026-11-03 21:19:38 +01:00
parent 45690ecd14
commit 44c6fbf372
109 changed files with 1225 additions and 292 deletions
@@ -1,6 +1,7 @@
import { type ReactNode } from 'react'
import { Key, Trash2, User, Loader2, Shield, KeyRound, Bot } from 'lucide-react'
import { useTranslation } from '../../i18n'
import { useFormatDate } from '../../hooks/useDateFormat'
import ConfirmDialog from '../shared/ConfirmDialog'
import { Tooltip } from '../shared/Tooltip'
import { fs } from '../shared/DialogShell'
@@ -64,9 +65,10 @@ export default function AdminMcpTokensPanel() {
sessions, sessionsLoading, tokens, tokensLoading, expandedScopes, toggleScopes,
revokeConfirmId, setRevokeConfirmId, deleteConfirmId, setDeleteConfirmId, handleRevoke, handleDelete,
} = useMcpTokensAdmin()
const { t, locale } = useTranslation()
const { t } = useTranslation()
const { formatDate } = useFormatDate()
const date = (iso: string) => new Date(iso).toLocaleDateString(locale)
const date = (iso: string) => formatDate(new Date(iso))
return (
<div>
@@ -11,6 +11,7 @@ import { type RangeWarning } from './useRangeBypass'
import { deriveCaps } from './pluginCaps'
import PluginPoiCategoryList from './PluginPoiCategoryList'
import { useTranslation } from '../../i18n'
import { useFormatDate } from '../../hooks/useDateFormat'
import ConfirmDialog from '../shared/ConfirmDialog'
import ToggleSwitch from '../Settings/ToggleSwitch'
import CustomSelect from '../shared/CustomSelect'
@@ -303,7 +304,7 @@ export default function AdminPluginsPanel() {
{versionPicker && (
<VersionPickerDialog plugin={versionPicker.plugin} versions={versionPicker.versions} failed={versionPicker.failed}
busy={busy} t={t} locale={locale} onPick={pickVersion} onClose={() => setVersionPicker(null)} />
busy={busy} t={t} onPick={pickVersion} onClose={() => setVersionPicker(null)} />
)}
<ConfirmDialog
@@ -745,6 +746,7 @@ function PluginDetailModal({ item, installed, busy, onInstall, onClose, t, local
onInstall: (id: string, version?: string, warn?: RangeWarning) => void; onClose: () => void; t: T; locale: string
}) {
const { detail, failed } = usePluginDetail(item.id)
const { formatDate } = useFormatDate()
const manifest = detail?.manifest ?? null
const permissions = manifest?.permissions ?? []
@@ -910,7 +912,7 @@ function PluginDetailModal({ item, installed, busy, onInstall, onClose, t, local
{(item.trek || item.minTrekVersion) && (
<Meta k={t('admin.plugins.metaRequires')} v={item.trek ? `TREK ${item.trek}` : `TREK ${item.minTrekVersion}+`} />
)}
{item.reviewedAt && <Meta k={t('admin.plugins.metaReviewed')} v={new Date(item.reviewedAt).toLocaleDateString(locale)} />}
{item.reviewedAt && <Meta k={t('admin.plugins.metaReviewed')} v={formatDate(new Date(item.reviewedAt))} />}
{typeof item.downloadCount === 'number' && item.downloadCount > 0 && (
<Meta k={t('admin.plugins.downloads')} v={item.downloadCount.toLocaleString(locale)} />
)}
@@ -934,7 +936,7 @@ function PluginDetailModal({ item, installed, busy, onInstall, onClose, t, local
) : (
<span className="text-content-faint" style={fs(11.5)}>{t('admin.plugins.versionNeedsTrek', { range: v.trek ?? '' })}</span>
)}>
<VersionLine v={v} locale={locale} />
<VersionLine v={v} />
</DialogListItem>
))}
</DialogList>
@@ -945,11 +947,12 @@ function PluginDetailModal({ item, installed, busy, onInstall, onClose, t, local
}
/** A version number with its date and, when the author signed it, a quiet tick. */
function VersionLine({ v, locale }: { v: VersionInfo; locale: string }) {
function VersionLine({ v }: { v: VersionInfo }) {
const { formatDate } = useFormatDate()
return (
<span className="flex flex-wrap items-center gap-x-2.5 gap-y-0.5">
<span className={`font-geist font-semibold tabular-nums ${v.compatible ? 'text-content' : 'text-content-faint'}`} style={fs(12.5)}>v{v.version}</span>
{v.publishedAt && <span className="text-content-faint" style={fs(11.5)}>{new Date(v.publishedAt).toLocaleDateString(locale)}</span>}
{v.publishedAt && <span className="text-content-faint" style={fs(11.5)}>{formatDate(new Date(v.publishedAt))}</span>}
{v.signed && <ShieldCheck size={13} className="flex-none text-success" />}
</span>
)
@@ -970,9 +973,9 @@ function Meta({ k, v }: { k: string; v: string }) {
* caller routes a DOWNGRADE through the data-risk confirm), an incompatible one is
* explained and never offered.
*/
function VersionPickerDialog({ plugin, versions, failed, busy, t, locale, onPick, onClose }: {
function VersionPickerDialog({ plugin, versions, failed, busy, t, onPick, onClose }: {
plugin: PluginRow; versions: VersionInfo[] | null; failed: boolean; busy: string | null
t: T; locale: string; onPick: (version: string) => void; onClose: () => void
t: T; onPick: (version: string) => void; onClose: () => void
}) {
return (
<DialogShell
@@ -994,7 +997,7 @@ function VersionPickerDialog({ plugin, versions, failed, busy, t, locale, onPick
const current = v.version === plugin.version
return (
<div key={v.version} data-testid={`version-row-${v.version}`} className="flex items-center gap-3 px-3.5 py-2.5">
<div className="min-w-0 flex-1"><VersionLine v={v} locale={locale} /></div>
<div className="min-w-0 flex-1"><VersionLine v={v} /></div>
{current ? (
<StatusPill tone="success" icon={<Check size={11} />}>{t('admin.plugins.installed')}</StatusPill>
) : v.compatible ? (
@@ -1,4 +1,4 @@
// FE-ADMIN-DUS-001 to FE-ADMIN-DUS-029
// FE-ADMIN-DUS-001 to FE-ADMIN-DUS-031
import { render, screen, waitFor, within, fireEvent } from '../../../tests/helpers/render';
import userEvent from '@testing-library/user-event';
import { http, HttpResponse } from 'msw';
@@ -70,7 +70,7 @@ function cartoInput(): HTMLInputElement {
}
/** Opens a CustomSelect by its trigger label and picks an option from the portal. */
async function pickFromSelect(user: ReturnType<typeof userEvent.setup>, trigger: string, option: string) {
async function pickFromSelect(user: ReturnType<typeof userEvent.setup>, trigger: string, option: string | RegExp) {
await user.click(screen.getByRole('button', { name: trigger }));
const choices = await screen.findAllByRole('button', { name: option });
await user.click(choices[choices.length - 1]);
@@ -481,3 +481,34 @@ describe('DefaultUserSettingsTab week start (#2029)', () => {
await waitFor(() => expect(puts).toEqual([{ week_start: 'sunday' }, { week_start: null }]));
});
});
describe('DefaultUserSettingsTab date format (#2971)', () => {
beforeEach(() => {
resetAllStores();
seedStore(useAuthStore, { isAuthenticated: true, user: buildAdmin() });
});
it('FE-ADMIN-DUS-030: the date-format default saves its own key', async () => {
const user = userEvent.setup();
const { puts } = stubDefaults({ date_format: 'YYYY-MM-DD' });
render(<DefaultUserSettingsTab />);
await screen.findByText('Default User Settings');
// The choices are labelled by how they write 31 December.
await pickFromSelect(user, '2026-12-31', '31.12.2026');
await waitFor(() => expect(puts).toEqual([{ date_format: 'DD.MM.YYYY' }]));
await waitFor(() => expect(screen.getByRole('button', { name: '31.12.2026' })).toBeInTheDocument());
});
it('FE-ADMIN-DUS-031: auto is offered with the example of the interface language', async () => {
const user = userEvent.setup();
const { puts } = stubDefaults({ date_format: 'DD/MM/YYYY' });
render(<DefaultUserSettingsTab />);
await screen.findByText('Default User Settings');
await pickFromSelect(user, '31/12/2026', /\(12\/31\/2026\)/);
await waitFor(() => expect(puts).toEqual([{ date_format: 'auto' }]));
});
});
@@ -10,6 +10,7 @@ import { MapView } from '../Map/MapView'
import { SYMBOLS, currenciesWith } from '../Budget/BudgetPanel.constants'
import type { DistanceUnit, WeekStart } from '../../types'
import { weekStartOptions } from '../../utils/calendarWeek'
import { dateFormatOptions } from '../../utils/dateFormat'
import { withTileApiKey } from '../../utils/tileUrl'
import { defaultStyleForProvider } from '../Map/glProviders'
import type { MapProvider } from '../Settings/mapSettingsModel'
@@ -180,6 +181,17 @@ export default function DefaultUserSettingsTab(): React.ReactElement {
/>
</ChoiceRow>
{/* Date format: every date field and numeric date (#2971) */}
<ChoiceRow label={<>{t('settings.dateFormat')} <ResetButton field="date_format" /></>}>
<div className="w-[220px] max-w-full">
<CustomSelect
value={defaults.date_format ?? ''}
onChange={value => { if (value) void save({ date_format: String(value) as Defaults['date_format'] }) }}
options={dateFormatOptions(locale, t('settings.dateFormatAuto'))}
/>
</div>
</ChoiceRow>
{/* Default Currency */}
<ChoiceRow label={<>{t('settings.currency')} <ResetButton field="default_currency" /></>}>
<div className="w-[220px] max-w-full">
+3 -3
View File
@@ -1,7 +1,7 @@
import { useCallback, useEffect, useRef, useState } from 'react';
import { adminApi } from '../../api/client';
import { useTranslation } from '../../i18n';
import { useFormatDate } from '../../hooks/useDateFormat';
export interface AuditEntry {
id: number;
@@ -41,7 +41,7 @@ export function auditUserLabel(e: AuditEntry): string {
* cards render their own markup over it.
*/
export function useAuditLog(serverTimezone?: string) {
const { locale } = useTranslation();
const { formatDateTime } = useFormatDate();
const [entries, setEntries] = useState<AuditEntry[]>([]);
const [total, setTotal] = useState(0);
const [loading, setLoading] = useState(true);
@@ -92,7 +92,7 @@ export function useAuditLog(serverTimezone?: string) {
const fmtTime = (iso: string) => {
try {
return new Date(iso.endsWith('Z') ? iso : iso + 'Z').toLocaleString(locale, {
return formatDateTime(new Date(iso.endsWith('Z') ? iso : iso + 'Z'), {
dateStyle: 'short',
timeStyle: 'medium',
timeZone: serverTimezone || undefined,
@@ -2,6 +2,7 @@ import { type ChangeEvent, useEffect, useEffectEvent, useRef, useState } from 'r
import { backupApi } from '../../api/client';
import { useTranslation } from '../../i18n';
import { useFormatDate } from '../../hooks/useDateFormat';
import { useSettingsStore } from '../../store/settingsStore';
import { getApiErrorMessage } from '../../types';
import { useToast } from '../shared/Toast';
@@ -104,7 +105,8 @@ export function useBackupAdmin({ keepSettingsWhenMissing = false }: Options = {}
const [deleteTarget, setDeleteTarget] = useState<string | null>(null);
const fileInputRef = useRef<HTMLInputElement>(null);
const toast = useToast();
const { t, locale } = useTranslation();
const { t } = useTranslation();
const { formatDateTime } = useFormatDate();
const is12h = useSettingsStore((s) => s.settings.time_format) === '12h';
const loadBackups = async () => {
@@ -241,7 +243,7 @@ export function useBackupAdmin({ keepSettingsWhenMissing = false }: Options = {}
minute: '2-digit',
};
if (serverTimezone) opts.timeZone = serverTimezone;
return new Date(dateStr).toLocaleString(locale, opts);
return formatDateTime(new Date(dateStr), opts);
} catch {
return dateStr;
}
@@ -4,7 +4,7 @@ import { adminApi } from '../../api/client';
import { useTranslation } from '../../i18n';
import { useAuthStore } from '../../store/authStore';
import { useSettingsStore } from '../../store/settingsStore';
import type { DistanceUnit, Place, WeekStart } from '../../types';
import type { DateFormat, DistanceUnit, Place, WeekStart } from '../../types';
import { normalizeTileUrl } from '../../utils/tileUrl';
import {
defaultStyleForProvider,
@@ -28,6 +28,7 @@ export type Defaults = RoutingDefaults & {
dark_mode?: string | boolean;
time_format?: string;
week_start?: WeekStart;
date_format?: DateFormat;
default_currency?: string;
blur_booking_codes?: boolean;
map_tile_url?: string;
+4 -2
View File
@@ -1,7 +1,9 @@
import type { BudgetParticipantFinal, BudgetUnconverted, CostCategory } from '@trek/shared';
import { convertBooked, convertedLine, inDisplayCurrency, tripAmountOf } from '../../hooks/useExchangeRates';
import type { BudgetItem } from '../../types';
import { readDateFormat } from '../../hooks/useDateFormat';
import { currencyDecimals } from '../../utils/formatters';
import { formatDisplayDate } from '../../utils/dateFormat';
import { currenciesWith, SYMBOLS } from './BudgetPanel.constants';
import { paidByUser, readUserNote, settlementDate, splitEqualShares } from './CostsPanel.helpers';
import { catMeta, COST_CATEGORY_LIST } from './costsCategories';
@@ -378,12 +380,12 @@ export function buildCostsCsv(items: BudgetItem[], opts: CsvBuildOptions): { fil
const fmtDate = (iso: string) => {
if (!iso) return '';
try {
return new Date(iso + 'T00:00:00Z').toLocaleDateString(opts.locale, {
return formatDisplayDate(new Date(iso + 'T00:00:00Z'), opts.locale, {
day: '2-digit',
month: '2-digit',
year: 'numeric',
timeZone: 'UTC',
});
}, readDateFormat());
} catch {
return iso;
}
@@ -3,6 +3,7 @@ import { Gauge, Hourglass, CircleDashed, Star } from 'lucide-react'
import type { DawarichAccept, DawarichSuggestion, DawarichSuggestionTarget } from '@trek/shared'
import { DAWARICH_BUCKET_MATCH_MIN_MINUTES, DAWARICH_BUCKET_MATCH_RADIUS_M } from '@trek/shared'
import { useTranslation } from '../../i18n'
import { useFormatDate } from '../../hooks/useDateFormat'
import { DialogButton, DialogFooter, DialogHeader, DialogShell, FooterSpacer, NEUTRAL_TINT } from '../shared/DialogShell'
import MSheet from '../../mobile/components/MSheet'
import { FormSheetFooter, FormSheetHeader } from '../../mobile/screens/trip/sheets/PlSheetChrome'
@@ -64,6 +65,7 @@ export default function DawarichAcceptDialog({
onConfirm,
}: DawarichAcceptDialogProps): React.ReactElement | null {
const { t, locale } = useTranslation()
const { formatDateTime } = useFormatDate()
const phone = useIsPhone()
const labelId = useId()
@@ -140,7 +142,7 @@ export default function DawarichAcceptDialog({
</span>
<p className="min-w-0 flex-1 text-caption text-content">
{t('dawarich.accept.recorded', {
from: new Date(suggestion.startedAt).toLocaleString(locale),
from: formatDateTime(new Date(suggestion.startedAt)),
to: new Date(suggestion.endedAt).toLocaleTimeString(locale, { hour: '2-digit', minute: '2-digit' }),
})}
</p>
@@ -1,5 +1,7 @@
import { FileText, FileImage, File, FileVideo, Plane, Train, Car, Ship, Bus, Sailboat, CableCar, Bike, CarTaxiFront, Route } from 'lucide-react'
import { downloadFile } from '../../utils/fileDownload'
import { readDateFormat } from '../../hooks/useDateFormat'
import { formatDisplayDate } from '../../utils/dateFormat'
export function isImage(mimeType?: string | null) {
if (!mimeType) return false
@@ -57,10 +59,10 @@ export function triggerDownload(url: string, filename: string) {
downloadFile(url, filename).catch(() => {})
}
export function formatDateWithLocale(dateStr?: string | null, locale?: string) {
export function formatDateWithLocale(dateStr?: string | null, locale?: string, dateFormat: string = readDateFormat()) {
if (!dateStr) return ''
try {
return new Date(dateStr).toLocaleDateString(locale, { day: '2-digit', month: '2-digit', year: 'numeric' })
return formatDisplayDate(new Date(dateStr), locale, { day: '2-digit', month: '2-digit', year: 'numeric' }, dateFormat)
} catch { return '' }
}
@@ -1,5 +1,6 @@
import type { ReactNode } from 'react'
import { useTranslation } from '../../../i18n/TranslationContext'
import { useFormatDate } from '../../../hooks/useDateFormat'
import { relativeTime } from '../../../utils/relativeTime'
import { Tooltip } from '../../shared/Tooltip'
@@ -83,11 +84,12 @@ export function StateBadge({ state, compact }: { state: string; compact?: boolea
/** "2h ago", or "never" when a binding has not run yet. */
export function LastRun({ at }: { at: string | null }) {
const { t, language, locale } = useTranslation()
const { t, language } = useTranslation()
const { formatDateTime } = useFormatDate()
if (!at) return <span className="text-content-faint">{t('docsync.binding.neverRun')}</span>
const ms = Date.parse(at)
if (Number.isNaN(ms)) return null
return <Tooltip label={new Date(ms).toLocaleString(locale)}><span>{relativeTime(ms, language)}</span></Tooltip>
return <Tooltip label={formatDateTime(new Date(ms))}><span>{relativeTime(ms, language)}</span></Tooltip>
}
/**
@@ -9,6 +9,8 @@ import { airtrailApi } from '../../api/client'
import { useTripStore } from '../../store/tripStore'
import { isEffectivelyOffline } from '../../sync/networkMode'
import { parseReservationMetadata } from '../../utils/flightLegs'
import { useDateFormat } from '../../hooks/useDateFormat'
import { formatDisplayDate } from '../../utils/dateFormat'
interface AirTrailImportModalProps {
isOpen: boolean
@@ -52,15 +54,15 @@ export function detectConnections(flights: AirtrailFlight[]): AirtrailFlight[][]
}
/** Locale-aware date (e.g. de → 13.06.2026, en-US → 06/13/2026). */
function fmtDate(d: string | null, locale: string): string {
function fmtDate(d: string | null, locale: string, dateFormat: string): string {
if (!d) return ''
try {
return new Date(d + 'T00:00:00Z').toLocaleDateString(locale, {
return formatDisplayDate(new Date(d + 'T00:00:00Z'), locale, {
year: 'numeric',
month: '2-digit',
day: '2-digit',
timeZone: 'UTC',
})
}, dateFormat)
} catch {
return d
}
@@ -68,6 +70,7 @@ function fmtDate(d: string | null, locale: string): string {
export default function AirTrailImportModal({ isOpen, onClose, tripId, pushUndo }: AirTrailImportModalProps) {
const { t, locale } = useTranslation()
const dateFormat = useDateFormat()
const toast = useToast()
const trip = useTripStore(s => s.trip)
const reservations = useTripStore(s => s.reservations)
@@ -270,7 +273,7 @@ export default function AirTrailImportModal({ isOpen, onClose, tripId, pushUndo
<span style={{ flex: 1, minWidth: 0 }}>
<span style={{ display: 'block', fontSize: 'calc(13px * var(--fs-scale-body, 1))', fontWeight: 600, color: 'var(--text-primary)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{label}</span>
<span style={{ display: 'block', fontSize: 'calc(11px * var(--fs-scale-caption, 1))', color: 'var(--text-muted)' }}>
{f.fromCode ?? f.fromName ?? '?'} → {f.toCode ?? f.toName ?? '?'}{f.date ? ` · ${fmtDate(f.date, locale)}` : ''}
{f.fromCode ?? f.fromName ?? '?'} → {f.toCode ?? f.toName ?? '?'}{f.date ? ` · ${fmtDate(f.date, locale, dateFormat)}` : ''}
</span>
</span>
{already && (
@@ -1,12 +1,15 @@
import { createPortal } from 'react-dom'
import { CalendarDays, Pencil, Trash2, ChevronDown, Check, Eye } from 'lucide-react'
import type { SidebarState } from './usePlacesSidebar'
import { useDateFormat } from '../../hooks/useDateFormat'
import { formatDisplayDate } from '../../utils/dateFormat'
export function MobileDayPickerSheet(S: SidebarState) {
const {
dayPickerPlace, setDayPickerPlace, setMobileShowDays, onPlaceClick, canEditPlaces, onEditPlace,
t, days, mobileShowDays, onAssignToDay, assignments, onDeletePlace,
} = S
const dateFormat = useDateFormat()
return createPortal(
<div
role="presentation"
@@ -64,7 +67,7 @@ export function MobileDayPickerSheet(S: SidebarState) {
<div className="bg-surface-tertiary text-content" style={{ width: 28, height: 28, borderRadius: '50%', display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 'calc(12px * var(--fs-scale-body, 1))', fontWeight: 700, flexShrink: 0 }}>{i + 1}</div>
<div style={{ flex: 1, minWidth: 0 }}>
<div className="text-content" style={{ fontSize: 'calc(13px * var(--fs-scale-body, 1))', fontWeight: 500 }}>{day.title || t('dayplan.dayN', { n: i + 1 })}</div>
{day.date && <div className="text-content-faint" style={{ fontSize: 'calc(11px * var(--fs-scale-caption, 1))' }}>{new Date(day.date + 'T00:00:00Z').toLocaleDateString(undefined, { timeZone: 'UTC' })}</div>}
{day.date && <div className="text-content-faint" style={{ fontSize: 'calc(11px * var(--fs-scale-caption, 1))' }}>{formatDisplayDate(new Date(day.date + 'T00:00:00Z'), undefined, { timeZone: 'UTC' }, dateFormat)}</div>}
</div>
{(assignments[String(day.id)] || []).some(a => a.place?.id === dayPickerPlace.id) && <Check size={14} color="var(--text-faint)" />}
</button>
@@ -2,6 +2,7 @@ import { cheapestEnergy, type ChargingEnergyPrice, type ChargingInfo as Info } f
import { ChevronDown, Coins, PlugZap } from 'lucide-react';
import { useEffect, useState } from 'react';
import { useTranslation } from '../../i18n/TranslationContext';
import { useFormatDate } from '../../hooks/useDateFormat';
import { chargingRepo } from '../../repo/chargingRepo';
import { useTripStore } from '../../store/tripStore';
import { isEffectivelyOffline } from '../../sync/networkMode';
@@ -76,6 +77,7 @@ export default function ChargingInfo({
}: ChargingTarget & { compact?: boolean }) {
const tripId = useTripStore((s) => s.trip?.id);
const { t } = useTranslation();
const { formatDateTime } = useFormatDate();
const [info, setInfo] = useState<Info | null>(null);
const [loading, setLoading] = useState(true);
useEffect(() => {
@@ -133,7 +135,7 @@ export default function ChargingInfo({
const cheapest = info ? cheapestEnergy(info.tariffs) : null;
const price = (value: number, currency: string) =>
new Intl.NumberFormat(undefined, { style: 'currency', currency }).format(value);
const label = `${status}${info?.updatedAt ? ` (${new Date(info.updatedAt).toLocaleString()})` : ''}`;
const label = `${status}${info?.updatedAt ? ` (${formatDateTime(new Date(info.updatedAt))})` : ''}`;
if (compact)
return (
<ChargingBadges
@@ -211,7 +213,7 @@ export default function ChargingInfo({
</a>
<br />
{info.license}
{info.updatedAt && ` · ${new Date(info.updatedAt).toLocaleString()}`}
{info.updatedAt && ` · ${formatDateTime(new Date(info.updatedAt))}`}
</p>
)}
</div>
@@ -11,6 +11,8 @@ import { DialogButton, DialogFooter, DialogHeader, DialogShell, DialogTile, Foot
import { EditorField, GRID_2, INPUT, LABEL } from '../shared/dialogParts'
import { SETTINGS_BUTTON_PRIMARY, SETTINGS_ICON_BUTTON, SettingsHint, StatusPill } from './settingsKit'
import { useTranslation } from '../../i18n'
import { useDateFormat } from '../../hooks/useDateFormat'
import { formatDisplayDate } from '../../utils/dateFormat'
import { useToast } from '../shared/Toast'
import { authApi } from '../../api/client'
@@ -55,10 +57,10 @@ const SCOPE_ICONS: Record<PublicApiScope, LucideIcon> = {
}
/** SQLite hands out "YYYY-MM-DD HH:MM:SS" in UTC, which Safari will not parse as it stands. */
function formatStamp(ts: string, locale: string): string {
function formatStamp(ts: string, locale: string, dateFormat: string): string {
const iso = ts.includes('T') ? ts : ts.replace(' ', 'T')
const d = new Date(/(Z|[+-]\d{2}:?\d{2})$/.test(iso) ? iso : `${iso}Z`)
return Number.isNaN(d.getTime()) ? ts : d.toLocaleDateString(locale)
return Number.isNaN(d.getTime()) ? ts : formatDisplayDate(d, locale, {}, dateFormat)
}
/**
@@ -380,6 +382,7 @@ export default function ApiKeysSection(): React.ReactElement {
function ApiKeyRow({ apiKey, locale, onDelete }: { apiKey: ApiKey; locale: string; onDelete: () => void }): React.ReactElement {
const { t } = useTranslation()
const dateFormat = useDateFormat()
const scopes = apiKey.scope_mode === 'limited' ? apiKey.scopes : undefined
return (
<li className="flex items-start gap-3 px-3.5 py-3">
@@ -394,10 +397,10 @@ function ApiKeyRow({ apiKey, locale, onDelete }: { apiKey: ApiKey; locale: strin
</code>
</div>
<p className="m-0 mt-0.5 tabular-nums text-content-faint first-letter:uppercase" style={fs(11.5)}>
{t('settings.apiKeys.createdAt')} {formatStamp(apiKey.created_at, locale)}
{t('settings.apiKeys.createdAt')} {formatStamp(apiKey.created_at, locale, dateFormat)}
{', '}
{apiKey.last_used_at
? `${t('settings.apiKeys.usedAt')} ${formatStamp(apiKey.last_used_at, locale)}`
? `${t('settings.apiKeys.usedAt')} ${formatStamp(apiKey.last_used_at, locale, dateFormat)}`
: t('settings.apiKeys.neverUsed')}
</p>
{/* What the key may read. Shown on the row rather than behind a detail
@@ -1,6 +1,7 @@
import React from 'react'
import { Loader2, Save, Plug, RefreshCw, Unplug } from 'lucide-react'
import { useTranslation } from '../../i18n'
import { useFormatDate } from '../../hooks/useDateFormat'
import { useDawarichConnection } from '../../hooks/useDawarichConnection'
import DawarichIcon from '../shared/DawarichIcon'
import Section from './Section'
@@ -23,7 +24,7 @@ import { fs } from '../shared/DialogShell'
* no reason is the version of this card that generates support questions.
*/
export default function DawarichConnectionSection(): React.ReactElement {
const { t, locale } = useTranslation()
const { t } = useTranslation()
const S = useDawarichConnection()
return (
@@ -123,7 +124,7 @@ export default function DawarichConnectionSection(): React.ReactElement {
)}
</div>
<DawarichConnectionStatus state={S} locale={locale} />
<DawarichConnectionStatus state={S} />
</Section>
)
}
@@ -138,12 +139,11 @@ export default function DawarichConnectionSection(): React.ReactElement {
*/
function DawarichConnectionStatus({
state,
locale,
}: {
state: ReturnType<typeof useDawarichConnection>
locale: string
}): React.ReactElement | null {
const { t } = useTranslation()
const { formatDateTime } = useFormatDate()
if (!state.connected && !state.probeMessage) return null
const missing: string[] = []
@@ -161,7 +161,7 @@ function DawarichConnectionStatus({
{state.connected && (
<p className="m-0 text-content-secondary">
{state.lastSyncAt
? t('dawarich.lastSync', { when: new Date(state.lastSyncAt).toLocaleString(locale) })
? t('dawarich.lastSync', { when: formatDateTime(new Date(state.lastSyncAt)) })
: t('dawarich.neverSynced')}
{state.lastSyncState === 'partial' && `, ${t('dawarich.syncPartial')}`}
</p>
@@ -1,4 +1,4 @@
// FE-COMP-DISPLAY-001 to FE-COMP-DISPLAY-055
// FE-COMP-DISPLAY-001 to FE-COMP-DISPLAY-057
import { render, screen, within, fireEvent } from '../../../tests/helpers/render';
import userEvent from '@testing-library/user-event';
import { http, HttpResponse } from 'msw';
@@ -484,6 +484,35 @@ describe('DisplaySettingsTab week start (#2029)', () => {
});
});
// ── Date format (056, 057) ────────────────────────────────────────────────────
describe('DisplaySettingsTab date format (#2971)', () => {
it('FE-COMP-DISPLAY-056: shows the language format when unset and saves the format picked', async () => {
const user = userEvent.setup();
const updateSetting = vi.fn().mockResolvedValue(undefined);
seedStore(useSettingsStore, { settings: buildSettings({ date_format: undefined }), updateSetting });
render(<DisplaySettingsTab />);
// Each choice is labelled by how it writes 31 December; auto carries the language's own way.
await user.click(screen.getByRole('button', { name: /\(12\/31\/2026\)/ }));
await user.click(await screen.findByText('31.12.2026'));
expect(updateSetting).toHaveBeenCalledWith('date_format', 'DD.MM.YYYY');
});
it('FE-COMP-DISPLAY-057: a rejected change surfaces the error', async () => {
const user = userEvent.setup();
const updateSetting = vi.fn().mockRejectedValue(new Error('Save failed'));
seedStore(useSettingsStore, { settings: buildSettings({ date_format: 'YYYY-MM-DD' }), updateSetting });
render(<><ToastContainer /><DisplaySettingsTab /></>);
await user.click(screen.getByRole('button', { name: /2026-12-31/ }));
await user.click(await screen.findByText('31/12/2026'));
expect(await screen.findByText('Save failed')).toBeInTheDocument();
});
});
describe('DisplaySettingsTab – the demo account', () => {
it('FE-COMP-DISPLAY-DEMO-001: the shared demo account sees English under the demo lock', () => {
seedStore(useAuthStore, { user: buildUser({ email: 'demo@trek.app' }), isAuthenticated: true, demoMode: true });
@@ -16,8 +16,9 @@ import { useSettingSaver } from './useSettingSaver'
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 { DEFAULT_DATE_FORMAT, DEFAULT_WEEK_START } from '@trek/shared'
import { weekStartOptions } from '../../utils/calendarWeek'
import { dateFormatOptions } from '../../utils/dateFormat'
import DemoLock from '../Demo/DemoLock'
import { useDemoAccountLock } from '../Demo/useDemoLock'
@@ -265,6 +266,23 @@ export default function DisplaySettingsTab(): React.ReactElement {
</div>
}
/>
{/* Date format: every date field and every date written in numbers (#2971) */}
<SettingRow
label={t('settings.dateFormat')}
hint={t('settings.dateFormatHint')}
control={
<div className={SELECT_BOX}>
<CustomSelect
value={settings.date_format || DEFAULT_DATE_FORMAT}
onChange={async v => {
await save('date_format', String(v))
}}
options={dateFormatOptions(locale, t('settings.dateFormatAuto'))}
/>
</div>
}
/>
</SettingRows>
</Section>
@@ -1,6 +1,7 @@
import Section from './Section'
import React, { useId } from 'react'
import { useTranslation } from '../../i18n'
import { useFormatDate } from '../../hooks/useDateFormat'
import { useToast } from '../shared/Toast'
import { Trash2, Copy, Terminal, Plus, Check, Key, KeyRound, ChevronRight, RefreshCw, AlertTriangle, Link2 } from 'lucide-react'
import PhotoProvidersSection from './PhotoProvidersSection'
@@ -62,12 +63,13 @@ export default function IntegrationsTab(): React.ReactElement {
function useIntegrations() {
const { t, locale } = useTranslation()
const { formatDate } = useFormatDate()
const toast = useToast()
const { mcpEnabled, airtrailEnabled, llmEnabled, aiAssistantEnabled, aiConnectionEnabled, ownParsing, dawarichEnabled, wandererEnabled, managed } = useIntegrationGates({ reloadAddons: true })
const mcp = useMcpIntegration({ enabled: mcpEnabled, reloadClientsAfterWrite: false })
return { t, locale, toast, mcpEnabled, airtrailEnabled, llmEnabled, aiAssistantEnabled, aiConnectionEnabled, ownParsing, dawarichEnabled,
return { t, locale, formatDate, toast, mcpEnabled, airtrailEnabled, llmEnabled, aiAssistantEnabled, aiConnectionEnabled, ownParsing, dawarichEnabled,
wandererEnabled,
managed, ...mcp,
}
@@ -171,7 +173,7 @@ function ConfigBlock({ open, onToggle, json, hint, copied, onCopy, t }: {
/** One registered OAuth client: what it is, the scopes it may use, and its two actions. */
function OAuthClientRow({ client, S }: { client: OAuthClient; S: IntegrationsState }) {
const { t, locale, oauthScopesExpanded, setOauthScopesExpanded, setOauthRotateId, setOauthDeleteId } = S
const { t, formatDate, oauthScopesExpanded, setOauthScopesExpanded, setOauthRotateId, setOauthDeleteId } = S
const expanded = !!oauthScopesExpanded[client.id]
return (
<div className={`${ROW} items-start`}>
@@ -185,7 +187,7 @@ function OAuthClientRow({ client, S }: { client: OAuthClient; S: IntegrationsSta
</div>
<div className="mt-0.5 flex min-w-0 flex-wrap gap-x-3 text-content-faint" style={fs(11.5)}>
<span className="min-w-0 truncate font-geist">{t('settings.oauth.clientId')}: {client.client_id}</span>
<span className="tabular-nums">{t('settings.mcp.tokenCreatedAt')} {new Date(client.created_at).toLocaleDateString(locale)}</span>
<span className="tabular-nums">{t('settings.mcp.tokenCreatedAt')} {formatDate(new Date(client.created_at))}</span>
</div>
<div className="mt-2 flex flex-wrap gap-1" style={fs(10.5)}>
{(expanded ? client.allowed_scopes : client.allowed_scopes.slice(0, 5)).map(s => (
@@ -216,7 +218,7 @@ function OAuthClientRow({ client, S }: { client: OAuthClient; S: IntegrationsSta
/** The OAuth tab: the snippet, the registered clients and the sessions they hold. */
function OAuthTab({ S }: { S: IntegrationsState }) {
const {
t, locale, oauthClients, oauthSessions, setOauthCreateOpen, setOauthNewName, setOauthNewUris, setOauthNewScopes, setOauthCreatedClient, setOauthRevokeId, setOauthIsMachine, configOpenOAuth, setConfigOpenOAuth, copiedKey, mcpJsonConfigOAuth, handleCopy,
t, formatDate, oauthClients, oauthSessions, setOauthCreateOpen, setOauthNewName, setOauthNewUris, setOauthNewScopes, setOauthCreatedClient, setOauthRevokeId, setOauthIsMachine, configOpenOAuth, setConfigOpenOAuth, copiedKey, mcpJsonConfigOAuth, handleCopy,
} = S
return (
<>
@@ -260,7 +262,7 @@ function OAuthTab({ S }: { S: IntegrationsState }) {
<p className="m-0 truncate font-semibold text-content" style={fs(13, 'body')}>{session.client_name}</p>
<p className="m-0 mt-0.5 flex min-w-0 flex-wrap gap-x-3 text-content-faint" style={fs(11.5)}>
<span className="min-w-0 truncate">{t('settings.oauth.sessionScopes')}: {session.scopes.join(', ')}</span>
<span className="tabular-nums">{t('settings.oauth.sessionExpires')} {new Date(session.access_token_expires_at).toLocaleDateString(locale)}</span>
<span className="tabular-nums">{t('settings.oauth.sessionExpires')} {formatDate(new Date(session.access_token_expires_at))}</span>
</p>
</div>
<button type="button" onClick={() => setOauthRevokeId(session.id)}
@@ -278,7 +280,7 @@ function OAuthTab({ S }: { S: IntegrationsState }) {
/** The deprecated API tokens tab: the warning, the snippet and the tokens. */
function ApiTokensTab({ S }: { S: IntegrationsState }) {
const { t, locale, configOpenToken, setConfigOpenToken, mcpTokens, setMcpModalOpen, setMcpNewName, setMcpCreatedToken, setMcpDeleteId, copiedKey, mcpJsonConfig, handleCopy } = S
const { t, formatDate, configOpenToken, setConfigOpenToken, mcpTokens, setMcpModalOpen, setMcpNewName, setMcpCreatedToken, setMcpDeleteId, copiedKey, mcpJsonConfig, handleCopy } = S
return (
<>
<WarningNote>{t('settings.mcp.apiTokensDeprecated')}</WarningNote>
@@ -311,9 +313,9 @@ function ApiTokensTab({ S }: { S: IntegrationsState }) {
<p className="m-0 truncate font-semibold text-content" style={fs(13, 'body')}>{token.name}</p>
<p className="m-0 mt-0.5 flex min-w-0 flex-wrap gap-x-3 text-content-faint" style={fs(11.5)}>
<span className="font-geist">{token.token_prefix}...</span>
<span className="tabular-nums">{t('settings.mcp.tokenCreatedAt')} {new Date(token.created_at).toLocaleDateString(locale)}</span>
<span className="tabular-nums">{t('settings.mcp.tokenCreatedAt')} {formatDate(new Date(token.created_at))}</span>
{token.last_used_at && (
<span className="tabular-nums">{t('settings.mcp.tokenUsedAt')} {new Date(token.last_used_at).toLocaleDateString(locale)}</span>
<span className="tabular-nums">{t('settings.mcp.tokenUsedAt')} {formatDate(new Date(token.last_used_at))}</span>
)}
</p>
</div>
@@ -3,6 +3,8 @@ import React, { useEffect, useRef, useState } from 'react';
import { useNavigate, useSearchParams } from 'react-router';
import { adminApi, authApi } from '../../api/client';
import { useTranslation } from '../../i18n';
import { useDateFormat } from '../../hooks/useDateFormat';
import { formatDisplayDateTime } from '../../utils/dateFormat';
import { useAuthStore } from '../../store/authStore';
import { getApiErrorMessage, type UserWithOidc } from '../../types';
import { passwordErrorKey } from '../../utils/passwordError';
@@ -35,6 +37,7 @@ export function useAccountSettings({ avatarRemoveErrorKey, ignoreEmptyBackupCode
const [searchParams] = useSearchParams();
const navigate = useNavigate();
const { t } = useTranslation();
const dateFormat = useDateFormat();
const toast = useToast();
const avatarInputRef = useRef<HTMLInputElement>(null);
@@ -126,7 +129,7 @@ export function useAccountSettings({ avatarRemoveErrorKey, ignoreEmptyBackupCode
if (skipBackupCodes) return;
const html = `<!doctype html><html><head><meta charset="utf-8"/><title>TREK MFA Backup Codes</title>
<style>body{font-family:Arial,sans-serif;padding:32px}h1{font-size:20px}pre{font-size:16px;line-height:1.6}</style>
</head><body><h1>TREK MFA Backup Codes</h1><p>${escapeHtml(new Date().toLocaleString())}</p><pre>${escapeHtml(backupCodesText)}</pre></body></html>`;
</head><body><h1>TREK MFA Backup Codes</h1><p>${escapeHtml(formatDisplayDateTime(new Date(), undefined, {}, dateFormat))}</p><pre>${escapeHtml(backupCodesText)}</pre></body></html>`;
const w = window.open('', '_blank', 'width=900,height=700');
if (!w) return;
w.document.open();
@@ -4,13 +4,15 @@ import { authApi, type PasskeyCredential } from '../../api/client';
import { useTranslation } from '../../i18n';
import { getApiErrorMessage } from '../../types';
import { useToast } from '../shared/Toast';
import { readDateFormat } from '../../hooks/useDateFormat';
import { formatDisplayDate } from '../../utils/dateFormat';
/** Parse a SQLite UTC timestamp ("YYYY-MM-DD HH:MM:SS") into a local date string. */
export function fmtDate(ts: string | null): string | null {
if (!ts) return null;
const iso = ts.includes('T') ? ts : ts.replace(' ', 'T');
const d = new Date(iso.endsWith('Z') ? iso : iso + 'Z');
return Number.isNaN(d.getTime()) ? null : d.toLocaleDateString();
return Number.isNaN(d.getTime()) ? null : formatDisplayDate(d, undefined, {}, readDateFormat());
}
/** True when the browser cancellation / no-matching-credential DOMExceptions fire. */
@@ -1,6 +1,8 @@
import { useEffect, useState } from 'react';
import { pluginsApi } from '../../api/client';
import { useTranslation } from '../../i18n';
import { useDateFormat } from '../../hooks/useDateFormat';
import { formatDisplayDateTime } from '../../utils/dateFormat';
export interface ActivityRow {
ts: string;
@@ -18,6 +20,7 @@ export interface ActivityRow {
*/
export function usePluginActivity() {
const { locale } = useTranslation();
const dateFormat = useDateFormat();
const [rows, setRows] = useState<ActivityRow[]>([]);
const [loading, setLoading] = useState(true);
@@ -36,7 +39,7 @@ export function usePluginActivity() {
const fmtWhen = (ts: string): string => {
const d = new Date(ts);
return Number.isNaN(d.getTime()) ? ts : d.toLocaleString(locale);
return Number.isNaN(d.getTime()) ? ts : formatDisplayDateTime(d, locale, {}, dateFormat);
};
return { rows, loading, load, fmtWhen };
@@ -19,7 +19,9 @@ import {
import type { ReactNode } from 'react';
import { Link } from 'react-router';
import { useTranslation } from '../../../i18n';
import { useDateFormat } from '../../../hooks/useDateFormat';
import { useSettingsStore } from '../../../store/settingsStore';
import { formatDisplayDate } from '../../../utils/dateFormat';
import { formatDistance, formatElevation } from '../../../utils/units';
import { BarButton, WhiteBadge } from '../../Planner/planParts';
import { DialogButton, NEUTRAL_TINT, fs } from '../../shared/DialogShell';
@@ -428,12 +430,13 @@ function SnapshotNotice({
onOpen: (placeId: number) => void;
}) {
const { t } = useTranslation();
const dateFormat = useDateFormat();
const snapshot = preview.snapshot;
if (preview.state === 'new' || !snapshot) {
return <TourNotice>{t('wanderer.preview.newHint')}</TourNotice>;
}
const when = snapshot.importedAt
? new Date(`${snapshot.importedAt.replace(' ', 'T')}Z`).toLocaleDateString(locale)
? formatDisplayDate(new Date(`${snapshot.importedAt.replace(' ', 'T')}Z`), locale, {}, dateFormat)
: '';
const open = (
<button
@@ -3,6 +3,7 @@ import { type LucideIcon, CalendarOff, AlertCircle, Building2, Unlink, ArrowRigh
import { useVacayStore } from '../../store/vacayStore'
import { useTranslation } from '../../i18n'
import CustomSelect from '../shared/CustomSelect'
import { CustomDatePicker } from '../shared/CustomDateTimePicker'
import ConfirmDialog from '../shared/ConfirmDialog'
import { useSchoolHolidayCountries } from './useSchoolHolidayCountries'
import type { VacayHolidayCalendar } from '../../types'
@@ -355,12 +356,11 @@ function YearTypePicker() {
{type === 'anniversary' && (
<div style={{ paddingInlineStart: 36, marginTop: 8 }}>
<input
type="date"
<CustomDatePicker
value={yearSettings.hire_date || ''}
onChange={e => save({ hire_date: e.target.value || null })}
aria-label={t('vacay.hireDate')}
style={{ width: '100%', fontSize: 'calc(13px * var(--fs-scale-body, 1))', fontWeight: 500, padding: '8px 14px', borderRadius: 10, background: 'var(--bg-input)', border: '1px solid var(--border-primary)', color: 'var(--text-primary)', fontFamily: 'inherit', outline: 'none' }}
onChange={v => save({ hire_date: v || null })}
placeholder={t('vacay.hireDate')}
style={{ width: '100%' }}
/>
{!yearSettings.hire_date && (
<p className="text-[11px] mt-1 text-content-faint">{t('vacay.hireDateHint')}</p>
@@ -819,3 +819,82 @@ describe('CustomDatePicker week start (#2029)', () => {
expect(await openMarch2026('saturday')).toEqual({ header: 'SSMTWTF', blanks: 1 });
});
});
// ─── Date format (#2971) ──────────────────────────────────────────────────────
describe('CustomDatePicker date format (#2971)', () => {
const onChange = vi.fn();
const original = useSettingsStore.getState().settings;
beforeEach(() => vi.clearAllMocks());
afterEach(() => useSettingsStore.setState({ settings: original }));
const seed = (dateFormat: 'auto' | 'YYYY-MM-DD' | 'DD.MM.YYYY') =>
useSettingsStore.setState({ settings: { ...original, date_format: dateFormat } });
function typeDate(value: string) {
fireEvent.click(screen.getByRole('button', { name: /enter date manually/i }));
const input = screen.getByRole('textbox', { name: 'Enter date manually' });
fireEvent.change(input, { target: { value } });
fireEvent.keyDown(input, { key: 'Enter' });
}
it('FE-COMP-DATEPICKER-036: the trigger writes the date in the chosen format', () => {
seed('YYYY-MM-DD');
render(<CustomDatePicker value="2026-11-03" onChange={onChange} />);
expect(screen.getAllByRole('button')[0].textContent).toContain('2026-11-03');
});
it('FE-COMP-DATEPICKER-037: compact mode writes the chosen format with the whole year', () => {
seed('DD.MM.YYYY');
render(<CustomDatePicker value="2026-11-03" onChange={onChange} compact />);
expect(screen.getByText('03.11.2026')).toBeInTheDocument();
});
it('FE-COMP-DATEPICKER-038: the manual entry is hinted and pre-filled in the chosen format', () => {
seed('YYYY-MM-DD');
render(<CustomDatePicker value="2026-11-03" onChange={onChange} />);
fireEvent.click(screen.getByRole('button', { name: /enter date manually/i }));
const input = screen.getByRole('textbox', { name: 'Enter date manually' });
expect(input).toHaveProperty('placeholder', 'YYYY-MM-DD');
expect(input).toHaveProperty('value', '2026-11-03');
});
it('FE-COMP-DATEPICKER-039: a typed date is read in the order of the chosen format', () => {
seed('YYYY-MM-DD');
render(<CustomDatePicker value="" onChange={onChange} />);
typeDate('2026/11/04');
expect(onChange).toHaveBeenCalledWith('2026-11-04');
});
it('FE-COMP-DATEPICKER-040: day first under DD.MM.YYYY, even with an English interface', () => {
seed('DD.MM.YYYY');
render(<CustomDatePicker value="" onChange={onChange} />);
typeDate('04.11.2026');
expect(onChange).toHaveBeenCalledWith('2026-11-04');
});
it('FE-COMP-DATEPICKER-043: a four-digit year written first is read as year, month, day in any format', () => {
seed('DD.MM.YYYY');
render(<CustomDatePicker value="" onChange={onChange} />);
typeDate('2026/11/04');
expect(onChange).toHaveBeenCalledWith('2026-11-04');
});
it('FE-COMP-DATEPICKER-041: auto keeps the short month of the language on the trigger', () => {
seed('auto');
render(<CustomDatePicker value="2026-11-03" onChange={onChange} />);
expect(screen.getAllByRole('button')[0].textContent).toMatch(/Nov/);
});
it('FE-COMP-DATEPICKER-042: auto keeps the language for typing: month first in English', () => {
seed('auto');
render(<CustomDatePicker value="" onChange={onChange} />);
fireEvent.click(screen.getByRole('button', { name: /enter date manually/i }));
const input = screen.getByRole('textbox', { name: 'Enter date manually' });
expect(input).toHaveProperty('placeholder', 'MM/DD/YYYY');
fireEvent.change(input, { target: { value: '04.11.2026' } });
fireEvent.keyDown(input, { key: 'Enter' });
expect(onChange).toHaveBeenCalledWith('2026-04-11');
});
});
@@ -4,6 +4,8 @@ import React, { useEffect, useRef, useState } from 'react';
import { createPortal } from 'react-dom';
import { useTranslation } from '../../i18n';
import { dateInputPattern } from '../../utils/dateInputPattern';
import { type DateField, dateFieldOrder, dateLayout, formatDisplayDate } from '../../utils/dateFormat';
import { useDateFormat } from '../../hooks/useDateFormat';
import { useRemeasureSignal } from '../../hooks/useAnchoredPosition';
import { useWeekStartDay } from '../../hooks/useWeekStartDay';
import { leadingBlanks, weekdayLabels } from '../../utils/calendarWeek';
@@ -42,6 +44,7 @@ export function CustomDatePicker({
}: CustomDatePickerProps) {
const { locale, t } = useTranslation();
const weekStart = useWeekStartDay();
const dateFormat = useDateFormat();
const [open, setOpen] = useState(false);
const [view, setView] = useState<CalendarView>('days');
const [yearPageStart, setYearPageStart] = useState(0);
@@ -149,22 +152,17 @@ export function CustomDatePicker({
);
const years = Array.from({ length: YEAR_PAGE_SIZE }, (_, i) => yearPageStart + i);
const displayValue = parsed
? parsed.toLocaleDateString(
locale,
compact
? { day: '2-digit', month: '2-digit', year: '2-digit', timeZone: 'UTC' }
: { day: 'numeric', month: 'short', year: 'numeric', timeZone: 'UTC' }
)
: null;
// A chosen date format (#2971) writes the field in numbers, the whole year
// included; 'auto' keeps the language's short month as before.
const fieldOptions: Intl.DateTimeFormatOptions = dateLayout(dateFormat)
? { day: '2-digit', month: '2-digit', year: 'numeric', timeZone: 'UTC' }
: compact
? { day: '2-digit', month: '2-digit', year: '2-digit', timeZone: 'UTC' }
: { day: 'numeric', month: 'short', year: 'numeric', timeZone: 'UTC' };
const displayValue = parsed ? formatDisplayDate(parsed, locale, fieldOptions, dateFormat) : null;
const inputValue = parsed
? parsed.toLocaleDateString(locale, {
day: '2-digit',
month: '2-digit',
year: 'numeric',
timeZone: 'UTC',
})
? formatDisplayDate(parsed, locale, { day: '2-digit', month: '2-digit', year: 'numeric', timeZone: 'UTC' }, dateFormat)
: '';
// Inclusive range check on ISO (YYYY-MM-DD) strings — lexicographic order
@@ -212,13 +210,11 @@ export function CustomDatePicker({
return;
}
// Determine field order for active locale via Intl
const parts = new Intl.DateTimeFormat(locale, { day: 'numeric', month: 'numeric', year: 'numeric' }).formatToParts(
new Date(2001, 5, 15)
); // known date: June 15, 2001
const order = parts
.filter((p) => ['day', 'month', 'year'].includes(p.type))
.map((p) => p.type as 'day' | 'month' | 'year');
// The order of the chosen date format (#2971), or the active locale's. A
// four-digit first number is a year in every format, so 2026/11/04 or
// 2026.11.04 reads as year, month, day whichever format is set.
const yearFirst = /^\D*\d{4}\D/.test(input);
const order: readonly DateField[] = yearFirst ? ['year', 'month', 'day'] : dateFieldOrder(locale, dateFormat);
// Strip non-numeric chars (handles RTL marks, dots, slashes, spaces)
const nums = input
@@ -277,7 +273,7 @@ export function CustomDatePicker({
if (e.key === 'Escape') setIsTyping(false);
}}
onBlur={handleTextSubmit}
placeholder={dateInputPattern(locale)}
placeholder={dateInputPattern(locale, dateFormat)}
aria-label={t('common.datepicker.enterManually')}
style={{
width: '100%',
@@ -700,9 +696,12 @@ interface CustomDateTimePickerProps {
onChange: (value: string) => void;
placeholder?: string;
style?: React.CSSProperties;
/** Earliest and latest day (YYYY-MM-DD), as CustomDatePicker takes them. */
min?: string;
max?: string;
}
export function CustomDateTimePicker({ value, onChange, placeholder, style = {} }: CustomDateTimePickerProps) {
export function CustomDateTimePicker({ value, onChange, placeholder, style = {}, min, max }: CustomDateTimePickerProps) {
const { locale } = useTranslation();
const [datePart, timePart] = (value || '').split('T');
@@ -716,7 +715,13 @@ export function CustomDateTimePicker({ value, onChange, placeholder, style = {}
return (
<div style={{ display: 'flex', gap: 8, ...style }}>
<CustomDatePicker value={datePart || ''} onChange={handleDateChange} style={{ flex: 1, minWidth: 0 }} />
<CustomDatePicker
value={datePart || ''}
onChange={handleDateChange}
style={{ flex: 1, minWidth: 0 }}
min={min}
max={max}
/>
<div style={{ width: 110, flexShrink: 0 }}>
<CustomTimePicker value={timePart || ''} onChange={handleTimeChange} />
</div>
+33
View File
@@ -0,0 +1,33 @@
import { DEFAULT_DATE_FORMAT, type DateFormat } from '@trek/shared'
import { useCallback } from 'react'
import { useTranslation } from '../i18n'
import { useSettingsStore } from '../store/settingsStore'
import { formatDisplayDate, formatDisplayDateTime } from '../utils/dateFormat'
/** The current user's date format (#2971); 'auto' follows the interface language. */
export function useDateFormat(): DateFormat {
return useSettingsStore((s) => s.settings.date_format) ?? DEFAULT_DATE_FORMAT
}
/** The same value outside React (stores, exports, plain helpers), read when called. */
export function readDateFormat(): DateFormat {
return useSettingsStore.getState().settings.date_format ?? DEFAULT_DATE_FORMAT
}
/**
* `toLocaleDateString` and `toLocaleString` bound to the interface language and
* the user's date format, for components that write dates.
*/
export function useFormatDate() {
const { locale } = useTranslation()
const format = useDateFormat()
const date = useCallback(
(value: Date, opts?: Intl.DateTimeFormatOptions) => formatDisplayDate(value, locale, opts, format),
[locale, format]
)
const dateTime = useCallback(
(value: Date, opts?: Intl.DateTimeFormatOptions) => formatDisplayDateTime(value, locale, opts, format),
[locale, format]
)
return { formatDate: date, formatDateTime: dateTime, locale, dateFormat: format }
}
@@ -5,6 +5,7 @@ import { MapView } from '../../../components/Map/MapView'
import { SYMBOLS, currenciesWith } from '../../../components/Budget/BudgetPanel.constants'
import { getApiErrorMessage, type DistanceUnit, type WeekStart } from '../../../types'
import { weekStartOptions } from '../../../utils/calendarWeek'
import { dateFormatOptions } from '../../../utils/dateFormat'
import { withTileApiKey } from '../../../utils/tileUrl'
import { defaultStyleForProvider } from '../../../components/Map/glProviders'
import type { MapProvider } from '../../../components/Settings/mapSettingsModel'
@@ -27,6 +28,7 @@ export default function MAdminDefaultUserSettings(): React.ReactElement {
saveMapProvider, pickTilePreset, pickStylePreset, commitStyle,
} = useDefaultUserSettings({ errorMessage: getApiErrorMessage, previewCreatedAt: () => new Date().toISOString() })
const [currencyOpen, setCurrencyOpen] = useState(false)
const [dateFormatOpen, setDateFormatOpen] = useState(false)
const [presetOpen, setPresetOpen] = useState(false)
const [styleOpen, setStyleOpen] = useState(false)
@@ -90,6 +92,7 @@ export default function MAdminDefaultUserSettings(): React.ReactElement {
const tilePresetLabel = presets.find((p) => p.url === mapTileUrl)?.name || t('settings.mapTemplatePlaceholder.select')
const stylePresetLabel = glStylePresets.find((p) => p.url === mapboxStyle)?.name || t('admin.defaultSettings.mapboxStylePlaceholder')
const chevron = <ChevronDown size={13} strokeWidth={2} className="flex-none text-m-faint" />
const dateFormats = dateFormatOptions(locale, t('settings.dateFormatAuto'))
return (
<div className="space-y-3">
@@ -123,6 +126,15 @@ export default function MAdminDefaultUserSettings(): React.ReactElement {
<MSegmented value={defaults.week_start || ''} onChange={(v) => save({ week_start: v as WeekStart })} options={weekStartOptions(locale)} />
</MAdminField>
{/* Date format (#2971) */}
<MAdminField label={<>{t('settings.dateFormat')} <ResetButton field="date_format" /></>}>
<MSetSelectRow
label={dateFormats.find((o) => o.value === defaults.date_format)?.label ?? t('settings.dateFormat')}
trailing={chevron}
onClick={() => setDateFormatOpen(true)}
/>
</MAdminField>
{/* Default Currency */}
<MAdminField
label={<>{t('settings.currency')} <ResetButton field="default_currency" /></>}
@@ -287,6 +299,15 @@ export default function MAdminDefaultUserSettings(): React.ReactElement {
</MAdminCard>
{/* Pickers */}
<MSetPickerSheet
open={dateFormatOpen}
onClose={() => setDateFormatOpen(false)}
title={t('settings.dateFormat')}
value={defaults.date_format || ''}
onSelect={(value) => { if (value) void save({ date_format: value as Defaults['date_format'] }) }}
options={dateFormats}
/>
<MSetPickerSheet
open={currencyOpen}
onClose={() => setCurrencyOpen(false)}
@@ -1,6 +1,7 @@
import { Key, Trash2, User, Loader2, Shield } from 'lucide-react'
import { SCOPES_PREVIEW, useMcpTokensAdmin } from '../../../components/Admin/useMcpTokensAdmin'
import { useTranslation } from '../../../i18n'
import { useFormatDate } from '../../../hooks/useDateFormat'
import { MAdminCard } from './MAdminUi'
import MConfirmSheet from '../settings/MConfirmSheet'
@@ -13,7 +14,8 @@ export default function MAdminMcpTokensPanel() {
sessions, sessionsLoading, tokens, tokensLoading, expandedScopes, toggleScopes,
revokeConfirmId, setRevokeConfirmId, deleteConfirmId, setDeleteConfirmId, handleRevoke, handleDelete,
} = useMcpTokensAdmin()
const { t, locale } = useTranslation()
const { t } = useTranslation()
const { formatDate } = useFormatDate()
return (
<div className="space-y-3">
@@ -58,7 +60,7 @@ export default function MAdminMcpTokensPanel() {
{session.username}
</span>
<span className="text-m-faint">·</span>
<span>{new Date(session.created_at).toLocaleDateString(locale)}</span>
<span>{formatDate(new Date(session.created_at))}</span>
</div>
<div className="mt-[6px] flex flex-wrap gap-1">
{visible.map(scope => (
@@ -135,11 +137,11 @@ export default function MAdminMcpTokensPanel() {
{token.username}
</span>
<span className="text-m-faint">·</span>
<span>{new Date(token.created_at).toLocaleDateString(locale)}</span>
<span>{formatDate(new Date(token.created_at))}</span>
<span className="text-m-faint">·</span>
<span>
{token.last_used_at
? new Date(token.last_used_at).toLocaleDateString(locale)
? formatDate(new Date(token.last_used_at))
: t('admin.mcpTokens.never')}
</span>
</div>
@@ -1,4 +1,6 @@
import { useState } from 'react'
import { useDateFormat } from '../../../hooks/useDateFormat'
import { formatDisplayDate } from '../../../utils/dateFormat'
import {
Blocks, AlertTriangle, PackageOpen, RefreshCw, Trash2, Download, Bug, X, ShieldCheck, UploadCloud,
ArrowUpCircle, Github, ExternalLink, ChevronDown, Check, Lock, Search, Link2, KeyRound, ShieldAlert,
@@ -810,6 +812,7 @@ function VersionPickerSheet({ plugin, versions, failed, busy, t, locale, onPick,
plugin: PluginRow; versions: VersionInfo[] | null; failed: boolean; busy: string | null
t: T; locale: string; onPick: (version: string) => void; onClose: () => void
}) {
const dateFormat = useDateFormat()
return (
<MSheet open onClose={onClose} variant="bottom" material="opaque" ariaLabel={t('admin.plugins.versionPickerTitle', { name: plugin.name })}>
<MAdminSheetFrame title={t('admin.plugins.versionPickerTitle', { name: plugin.name })} onClose={onClose}>
@@ -823,7 +826,7 @@ function VersionPickerSheet({ plugin, versions, failed, busy, t, locale, onPick,
<div key={v.version} data-testid={`version-row-${v.version}`}
className="flex items-center gap-2.5 rounded-xl px-2.5 py-2.5">
<span className={`text-[13px] font-semibold tabular-nums ${v.compatible ? 'text-m-ink' : 'text-m-faint'}`}>v{v.version}</span>
{v.publishedAt && <span className="text-[11.5px] text-m-faint">{new Date(v.publishedAt).toLocaleDateString(locale)}</span>}
{v.publishedAt && <span className="text-[11.5px] text-m-faint">{formatDisplayDate(new Date(v.publishedAt), locale, {}, dateFormat)}</span>}
{v.signed && <ShieldCheck size={13} className="shrink-0 text-[color:var(--m-st-confirmed)]" />}
<span className="ms-auto" />
{current ? (
@@ -956,6 +959,7 @@ function PluginDetailSheet({ item, installed, busy, onInstall, onClose, t, local
item: RegistryItem; installed: boolean; busy: string | null; ignoreTrekRange: boolean
onInstall: (id: string, version?: string, warn?: RangeWarning) => void; onClose: () => void; t: T; locale: string
}) {
const dateFormat = useDateFormat()
const { detail, failed } = usePluginDetail<MRegistryDetail>(item.id)
const manifest = detail?.manifest ?? null
@@ -1109,7 +1113,7 @@ function PluginDetailSheet({ item, installed, busy, onInstall, onClose, t, local
{(item.trek || item.minTrekVersion) && (
<Meta k={t('admin.plugins.metaRequires')} v={item.trek ? `TREK ${item.trek}` : `TREK ${item.minTrekVersion}+`} />
)}
{item.reviewedAt && <Meta k={t('admin.plugins.metaReviewed')} v={new Date(item.reviewedAt).toLocaleDateString(locale)} />}
{item.reviewedAt && <Meta k={t('admin.plugins.metaReviewed')} v={formatDisplayDate(new Date(item.reviewedAt), locale, {}, dateFormat)} />}
{typeof item.downloadCount === 'number' && item.downloadCount > 0 && (
<Meta k={t('admin.plugins.downloads')} v={item.downloadCount.toLocaleString(locale)} />
)}
@@ -1125,7 +1129,7 @@ function PluginDetailSheet({ item, installed, busy, onInstall, onClose, t, local
{detail!.versions!.map(v => (
<div key={v.version} className="flex items-center gap-2.5 py-1">
<span className={`text-[12.5px] font-medium tabular-nums ${v.compatible ? 'text-m-ink' : 'text-m-faint'}`}>v{v.version}</span>
{v.publishedAt && <span className="text-[11.5px] text-m-faint">{new Date(v.publishedAt).toLocaleDateString(locale)}</span>}
{v.publishedAt && <span className="text-[11.5px] text-m-faint">{formatDisplayDate(new Date(v.publishedAt), locale, {}, dateFormat)}</span>}
{v.signed && <ShieldCheck size={13} className="shrink-0 text-[color:var(--m-st-confirmed)]" />}
<span className="ms-auto" />
{v.compatible ? (
@@ -1,6 +1,7 @@
import React from 'react'
import { Plug, Save, RefreshCw, Unplug } from 'lucide-react'
import { useTranslation } from '../../../i18n'
import { useFormatDate } from '../../../hooks/useDateFormat'
import { useDawarichConnection } from '../../../hooks/useDawarichConnection'
import { MSetCard, MSetRow, MSetInput, MSetButton, MSetHint } from './MSettingsUi'
import MToggle from '../../components/MToggle'
@@ -14,7 +15,8 @@ import MToggle from '../../components/MToggle'
* sync logic would spend the whole budget on its own.
*/
export default function MDawarichConnectionSection(): React.ReactElement {
const { t, locale } = useTranslation()
const { t } = useTranslation()
const { formatDateTime } = useFormatDate()
const S = useDawarichConnection()
return (
@@ -92,7 +94,7 @@ export default function MDawarichConnectionSection(): React.ReactElement {
{S.connected && (
<p className="font-geist text-[0.625rem] leading-relaxed text-m-muted">
{S.lastSyncAt
? t('dawarich.lastSync', { when: new Date(S.lastSyncAt).toLocaleString(locale) })
? t('dawarich.lastSync', { when: formatDateTime(new Date(S.lastSyncAt)) })
: t('dawarich.neverSynced')}
</p>
)}
@@ -6,8 +6,9 @@ import { SYMBOLS, currenciesWith } from '../../../components/Budget/BudgetPanel.
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, WeekStart } from '../../../types'
import { DEFAULT_WEEK_START } from '@trek/shared'
import { DEFAULT_DATE_FORMAT, DEFAULT_WEEK_START } from '@trek/shared'
import { weekStartOptions } from '../../../utils/calendarWeek'
import { dateFormatOptions } from '../../../utils/dateFormat'
import { MSetCard, MSetEyebrow, MSetHint, MSetSelectRow, MSetSegments, MSetRow } from './MSettingsUi'
import MToggle from '../../components/MToggle'
import MSetPickerSheet from './MSetPickerSheet'
@@ -27,6 +28,7 @@ export default function MSettingsGeneral() {
const [langOpen, setLangOpen] = useState(false)
const [startTabOpen, setStartTabOpen] = useState(false)
const [navAppOpen, setNavAppOpen] = useState(false)
const [dateFormatOpen, setDateFormatOpen] = useState(false)
const navAppOptions = preferredNavAppOptions(t)
const navAppValue = settings.preferred_nav_app || ''
@@ -37,6 +39,7 @@ export default function MSettingsGeneral() {
const language = SUPPORTED_LANGUAGES.find((l) => l.value === settings.language) || SUPPORTED_LANGUAGES[0]
const chevron = <ChevronDown size={13} strokeWidth={2} className="flex-none text-m-faint" />
const dateFormats = dateFormatOptions(locale, t('settings.dateFormatAuto'))
const travelRows: {
key: keyof Settings
@@ -166,6 +169,15 @@ export default function MSettingsGeneral() {
onChange={(v) => save('week_start', v)}
options={weekStartOptions(locale)}
/>
{/* Date format (#2971) */}
<MSetEyebrow className="mb-[6px] mt-[14px]">{t('settings.dateFormat')}</MSetEyebrow>
<MSetSelectRow
label={dateFormats.find((o) => o.value === (settings.date_format || DEFAULT_DATE_FORMAT))?.label ?? ''}
trailing={chevron}
onClick={() => setDateFormatOpen(true)}
/>
<MSetHint>{t('settings.dateFormatHint')}</MSetHint>
</MSetCard>
<MSetCard title={t('settings.general.travelMap')} icon={Map} className="mt-3">
@@ -206,6 +218,15 @@ export default function MSettingsGeneral() {
]}
/>
<MSetPickerSheet
open={dateFormatOpen}
onClose={() => setDateFormatOpen(false)}
title={t('settings.dateFormat')}
value={settings.date_format || DEFAULT_DATE_FORMAT}
onSelect={(v) => save('date_format', v)}
options={dateFormats}
/>
<MSetPickerSheet
open={langOpen}
onClose={() => setLangOpen(false)}
@@ -1,5 +1,6 @@
import { Check, ChevronDown, ChevronRight, Copy, KeyRound, Plus, RefreshCw, Terminal, Trash2 } from 'lucide-react'
import { useTranslation } from '../../../i18n'
import { useFormatDate } from '../../../hooks/useDateFormat'
import { OAUTH_PRESETS, useMcpIntegration } from '../../../components/Settings/useMcpIntegration'
import MScopeGroupPicker from './MScopeGroupPicker'
import MSheet from '../../components/MSheet'
@@ -38,7 +39,8 @@ function CodeBlock({ children }: { children: string }) {
* tokens, with the desktop modals as floating sheets.
*/
export default function MSettingsMcp() {
const { t, locale } = useTranslation()
const { t } = useTranslation()
const { formatDate } = useFormatDate()
const demoLocked = useDemoAccountLock()
const {
activeMcpTab: activeTab,
@@ -190,7 +192,7 @@ export default function MSettingsMcp() {
{t('settings.oauth.clientId')}: {client.client_id}
</p>
<p className="mt-[2px] font-geist text-[0.625rem] text-m-faint">
{t('settings.mcp.tokenCreatedAt')} {new Date(client.created_at).toLocaleDateString(locale)}
{t('settings.mcp.tokenCreatedAt')} {formatDate(new Date(client.created_at))}
</p>
<div className="mt-[6px] flex flex-wrap gap-1">
{(scopesExpanded[client.id] ? client.allowed_scopes : client.allowed_scopes.slice(0, 5)).map((s) => (
@@ -226,7 +228,7 @@ export default function MSettingsMcp() {
{t('settings.oauth.sessionScopes')}: {session.scopes.join(', ')}
</p>
<p className="font-geist text-[0.625rem] text-m-faint">
{t('settings.oauth.sessionExpires')} {new Date(session.access_token_expires_at).toLocaleDateString(locale)}
{t('settings.oauth.sessionExpires')} {formatDate(new Date(session.access_token_expires_at))}
</p>
</div>
<MSetButton variant="danger" onClick={() => setRevokeId(session.id)}>
@@ -272,11 +274,11 @@ export default function MSettingsMcp() {
<p className="mt-[2px] font-mono text-[0.625rem] text-m-faint">
{token.token_prefix}...
<span className="ms-2 font-geist">
{t('settings.mcp.tokenCreatedAt')} {new Date(token.created_at).toLocaleDateString(locale)}
{t('settings.mcp.tokenCreatedAt')} {formatDate(new Date(token.created_at))}
</span>
{token.last_used_at && (
<span className="font-geist">
, {t('settings.mcp.tokenUsedAt')} {new Date(token.last_used_at).toLocaleDateString(locale)}
, {t('settings.mcp.tokenUsedAt')} {formatDate(new Date(token.last_used_at))}
</span>
)}
</p>
@@ -8,8 +8,10 @@ import MDancingTrek from '../../../components/MDancingTrek'
import { useCollabPolls } from '../../../../components/Collab/useCollabPolls'
import { useAuthStore } from '../../../../store/authStore'
import ToggleSwitch from '../../../../components/Settings/ToggleSwitch'
import { CustomDateTimePicker } from '../../../../components/shared/CustomDateTimePicker'
import { localIsoDate } from '../../../../utils/localDate'
import MSheet from '../../../components/MSheet'
import { Eyebrow, FIELD_AREA_CLS, FIELD_CLS, FormSheetFooter, FormSheetHeader } from '../sheets/PlSheetChrome'
import { Eyebrow, FIELD_AREA_CLS, FormSheetFooter, FormSheetHeader } from '../sheets/PlSheetChrome'
import MConfirmSheet from '../../settings/MConfirmSheet'
import type { TripPlanner } from '../MTripShell'
import { SectionHeader, TabScroller } from './tabChrome'
@@ -338,8 +340,6 @@ function PollFormSheet({ open, onClose, onSubmit, t }: {
}
}
const minDeadline = new Date(Date.now() - new Date().getTimezoneOffset() * 60000).toISOString().slice(0, 16)
return (
<MSheet open={open} onClose={onClose} ariaLabel={t('collab.polls.new')}>
<FormSheetHeader icon={BarChart3} title={t('collab.polls.new')} onClose={onClose} closeLabel={t('common.close')} />
@@ -396,12 +396,11 @@ function PollFormSheet({ open, onClose, onSubmit, t }: {
<Eyebrow className="mb-[5px] mt-3 uppercase">{t('collab.polls.deadline')}</Eyebrow>
<div className="flex items-center gap-[6px]">
<input
type="datetime-local"
<CustomDateTimePicker
value={deadline}
min={minDeadline}
onChange={e => setDeadline(e.target.value)}
className={`${FIELD_CLS} flex-1`}
onChange={setDeadline}
min={localIsoDate()}
style={{ flex: 1, minWidth: 0 }}
/>
{deadline && (
<button
@@ -3,6 +3,7 @@ import { ArrowRightLeft, Building2, Calendar, CalendarRange, CalendarX, ChevronD
import MSheet from '../../components/MSheet'
import MIconBtn from '../../components/MIconBtn'
import MToggle from '../../components/MToggle'
import { CustomDatePicker } from '../../../components/shared/CustomDateTimePicker'
import ConfirmDialog from '../../../components/shared/ConfirmDialog'
import { useVacayStore } from '../../../store/vacayStore'
import { useTranslation } from '../../../i18n'
@@ -338,13 +339,13 @@ function YearTypeRows() {
{type === 'anniversary' && (
<div className="ms-7">
<input
type="date"
value={yearSettings.hire_date || ''}
onChange={e => save({ hire_date: e.target.value || null })}
aria-label={t('vacay.hireDate')}
className="mt-[7px] w-full rounded-[10px] border border-[color:var(--m-rowbr)] bg-[color:var(--m-sheetop)] px-[11px] py-[9px] font-[inherit] text-[0.78125rem] font-semibold text-m-ink outline-none"
/>
<div className="mt-[7px]" aria-label={t('vacay.hireDate')}>
<CustomDatePicker
value={yearSettings.hire_date || ''}
onChange={v => save({ hire_date: v || null })}
placeholder={t('vacay.hireDate')}
/>
</div>
</div>
)}
+4 -2
View File
@@ -20,6 +20,7 @@ import HelpAnchor from '../components/Help/HelpAnchor'
import AtlasCountryPlaces from '../components/Atlas/AtlasCountryPlaces'
import { AtlasTourActivityPane } from '../components/Atlas/tourActivity/AtlasTourActivityPane'
import { useAddonStore } from '../store/addonStore'
import { useFormatDate } from '../hooks/useDateFormat'
import { getIntlLanguage } from '@trek/shared'
// Fixed ids rather than useId: the page body stays free of hooks, and there is only one atlas.
@@ -448,6 +449,7 @@ interface SidebarContentProps {
function SidebarContent({ data, stats, regionsVisited, countryRegions, onOpenPlaces, countries, selectedCountry, countryDetail, resolveName, onTripClick, onUnmarkCountry, bucketList, bucketTab, setBucketTab, showBucketAdd, setShowBucketAdd, bucketForm, setBucketForm, onAddBucket, onDeleteBucket, onClearBucketVisit, onSearchBucket, onSelectBucketPoi, bucketSearchResults, setBucketSearchResults, bucketPoiMonth, setBucketPoiMonth, bucketPoiYear, setBucketPoiYear, bucketSearching, bucketSearch, setBucketSearch, t, dark }: SidebarContentProps): React.ReactElement {
const { language } = useTranslation()
const { formatDate } = useFormatDate()
const toursEnabled = useAddonStore(s => s.isEnabled('tours'))
const statsContentRef = useRef<HTMLDivElement>(null)
const bucketSearchRowRef = useRef<HTMLDivElement>(null)
@@ -548,7 +550,7 @@ ${t('dawarich.bucket.clearVisit')}`
style={{ fontSize: 'calc(9px * var(--fs-scale-caption, 1))', background: 'none', border: 'none', padding: 0, cursor: 'pointer', fontFamily: 'inherit' }}
>
<Check size={9} />
{new Date(item.visited_at).toLocaleDateString(getIntlLanguage(language))}
{formatDate(new Date(item.visited_at))}
</button>
) : (
<span
@@ -556,7 +558,7 @@ ${t('dawarich.bucket.clearVisit')}`
style={{ fontSize: 'calc(9px * var(--fs-scale-caption, 1))' }}
>
<Check size={9} />
{new Date(item.visited_at).toLocaleDateString(getIntlLanguage(language))}
{formatDate(new Date(item.visited_at))}
</span>
)}
</Tooltip>
+4 -1
View File
@@ -10,6 +10,8 @@ import { SettingsCard, SettingRows, SettingsHint, StatusPill, SETTINGS_BUTTON, S
import type { TranslationFn } from '../../types'
import type { useAdmin } from './useAdmin'
import { formatLastActive, inviteMeta, inviteStatus } from './adminModel'
import { useDateFormat } from '../../hooks/useDateFormat'
import { formatDisplayDate } from '../../utils/dateFormat'
interface AdminUsersTabProps {
admin: ReturnType<typeof useAdmin>
@@ -36,6 +38,7 @@ function RowIconButton({ label, onClick, disabled, danger, children }: { label:
// "Users" admin tab: user table, invite links, permissions panel + the
// create-invite modal. Pure layout around the useAdmin hook — no logic of its own.
export default function AdminUsersTab({ admin, t, locale }: AdminUsersTabProps): React.ReactElement {
const dateFormat = useDateFormat()
const {
hour12, currentUser,
users, isLoading,
@@ -112,7 +115,7 @@ export default function AdminUsersTab({ admin, t, locale }: AdminUsersTabProps):
: <StatusPill>{t('settings.roleUser')}</StatusPill>}
</td>
<td className={`${TD} whitespace-nowrap font-geist tabular-nums text-content-muted`} style={fs(12)}>
{new Date(u.created_at).toLocaleDateString(locale)}
{formatDisplayDate(new Date(u.created_at), locale, {}, dateFormat)}
</td>
<td className={`${TD} whitespace-nowrap font-geist tabular-nums text-content-muted`} style={fs(12)}>
{/* Activity, not only sign-ins: a renewing cookie keeps people signed in for weeks. */}
+3 -1
View File
@@ -1,4 +1,6 @@
/** Shared types and pure helpers for the admin page + its data hook. No React, no side effects. */
import { readDateFormat } from '../../hooks/useDateFormat'
import { formatDisplayDate } from '../../utils/dateFormat'
export interface AdminUser {
id: number
@@ -87,7 +89,7 @@ export function inviteMeta(
locale: string,
): string {
const parts = [`${invite.used_count}/${invite.max_uses === 0 ? '∞' : invite.max_uses} ${t('admin.invite.uses')}`]
if (invite.expires_at) parts.push(`${t('admin.invite.expiresAt')} ${new Date(invite.expires_at).toLocaleDateString(locale)}`)
if (invite.expires_at) parts.push(`${t('admin.invite.expiresAt')} ${formatDisplayDate(new Date(invite.expires_at), locale, {}, readDateFormat())}`)
if (invite.trip_title) parts.push(t('admin.invite.boundTo', { trip: invite.trip_title }))
parts.push(`${t('admin.invite.createdBy')} ${invite.created_by_name ?? ''}`)
return parts.join(', ')
+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, DEFAULT_WEEK_START } from '@trek/shared'
import { DEFAULT_APPEARANCE, DEFAULT_DATE_FORMAT, DEFAULT_WEEK_START } from '@trek/shared'
import { getApiErrorMessage } from '../types'
import { SUPPORTED_LANGUAGE_CODES } from '../i18n/supportedLanguages'
import { detectBrowserLanguage } from '../i18n/detectBrowserLanguage'
@@ -88,6 +88,7 @@ export const DEFAULT_SETTINGS: Settings = {
distance_unit: 'metric',
time_format: '24h',
week_start: DEFAULT_WEEK_START,
date_format: DEFAULT_DATE_FORMAT,
show_place_description: false,
optimize_from_accommodation: true,
map_provider: 'leaflet',
+4
View File
@@ -32,6 +32,7 @@ import type {
AppearanceConfig,
ValhallaProvider,
WeekStart,
DateFormat,
} from '@trek/shared'
export type {
@@ -57,6 +58,7 @@ export type {
Category,
AppearanceConfig,
WeekStart,
DateFormat,
}
export interface User {
@@ -143,6 +145,8 @@ export interface Settings {
time_format: string
/** First column of every date picker (#2029); missing means Monday. */
week_start?: WeekStart
/** How dates are written in numbers (#2971); missing means the language's own format. */
date_format?: DateFormat
show_place_description: boolean
blur_booking_codes?: boolean
/** Day headings lead with the calendar date and name the trip day second (#1953). */
+195
View File
@@ -0,0 +1,195 @@
// FE-UTIL-DATEFMT-001 to FE-UTIL-DATEFMT-020
import { describe, it, expect } from 'vitest'
import {
dateFieldOrder,
dateFormatOptions,
dateLayout,
displayDateFormatter,
formatDisplayDate,
formatDisplayDateTime,
isNumericDate,
} from './dateFormat'
// 31 December 2026, 15:04 UTC: no day of it reads as a month, so every layout is unambiguous.
const NYE = new Date(Date.UTC(2026, 11, 31, 15, 4))
const UTC = { timeZone: 'UTC' } as const
const NUMERIC: Intl.DateTimeFormatOptions = { day: '2-digit', month: '2-digit', year: 'numeric', timeZone: 'UTC' }
describe('dateFormat (#2971)', () => {
describe('formatDisplayDate', () => {
it('FE-UTIL-DATEFMT-001: auto, an unknown value or none is exactly toLocaleDateString', () => {
const cases: [string, Intl.DateTimeFormatOptions | undefined][] = [
['en-US', undefined],
['en-US', NUMERIC],
['de-DE', NUMERIC],
['ko-KR', { day: 'numeric', month: 'short', year: 'numeric', timeZone: 'UTC' }],
['en-GB', { day: '2-digit', month: '2-digit', year: '2-digit', timeZone: 'UTC' }],
]
for (const [locale, opts] of cases) {
const expected = NYE.toLocaleDateString(locale, opts)
expect(formatDisplayDate(NYE, locale, opts, 'auto')).toBe(expected)
expect(formatDisplayDate(NYE, locale, opts, 'DD-MM-YY')).toBe(expected)
expect(formatDisplayDate(NYE, locale, opts, null)).toBe(expected)
expect(formatDisplayDate(NYE, locale, opts)).toBe(expected)
}
})
it('FE-UTIL-DATEFMT-002: each format writes 31 December 2026 in its own layout', () => {
expect(formatDisplayDate(NYE, 'en-US', UTC, 'YYYY-MM-DD')).toBe('2026-12-31')
expect(formatDisplayDate(NYE, 'en-US', UTC, 'YYYY/MM/DD')).toBe('2026/12/31')
expect(formatDisplayDate(NYE, 'en-US', UTC, 'DD.MM.YYYY')).toBe('31.12.2026')
expect(formatDisplayDate(NYE, 'en-US', UTC, 'DD/MM/YYYY')).toBe('31/12/2026')
expect(formatDisplayDate(NYE, 'de-DE', UTC, 'MM/DD/YYYY')).toBe('12/31/2026')
})
it('FE-UTIL-DATEFMT-003: the language does not change a chosen format', () => {
for (const locale of ['en-US', 'de-DE', 'ko-KR', 'ar', 'fr-FR']) {
expect(formatDisplayDate(NYE, locale, NUMERIC, 'YYYY-MM-DD')).toBe('2026-12-31')
}
})
it('FE-UTIL-DATEFMT-004: single-digit days and months are padded', () => {
const march = new Date(Date.UTC(2026, 2, 5))
expect(formatDisplayDate(march, 'en-US', { day: 'numeric', month: 'numeric', year: 'numeric', timeZone: 'UTC' }, 'DD.MM.YYYY')).toBe('05.03.2026')
})
it('FE-UTIL-DATEFMT-005: year 2-digit keeps two digits of the year', () => {
const opts: Intl.DateTimeFormatOptions = { day: '2-digit', month: '2-digit', year: '2-digit', timeZone: 'UTC' }
expect(formatDisplayDate(NYE, 'en-US', opts, 'DD.MM.YYYY')).toBe('31.12.26')
expect(formatDisplayDate(NYE, 'en-US', opts, 'YYYY-MM-DD')).toBe('26-12-31')
})
it('FE-UTIL-DATEFMT-006: day and month without a year write only those two, in layout order', () => {
const opts: Intl.DateTimeFormatOptions = { day: 'numeric', month: 'numeric', timeZone: 'UTC' }
expect(formatDisplayDate(NYE, 'en-US', opts, 'DD.MM.YYYY')).toBe('31.12')
expect(formatDisplayDate(NYE, 'en-US', opts, 'YYYY-MM-DD')).toBe('12-31')
expect(formatDisplayDate(NYE, 'en-US', opts, 'MM/DD/YYYY')).toBe('12/31')
})
it('FE-UTIL-DATEFMT-007: a month name or a long dateStyle is left to Intl', () => {
const named: Intl.DateTimeFormatOptions[] = [
{ weekday: 'short', day: 'numeric', month: 'short', timeZone: 'UTC' },
{ day: 'numeric', month: 'short', year: 'numeric', timeZone: 'UTC' },
{ month: 'long', year: 'numeric', timeZone: 'UTC' },
{ dateStyle: 'medium', timeZone: 'UTC' },
]
for (const opts of named) {
expect(formatDisplayDate(NYE, 'de-DE', opts, 'YYYY-MM-DD')).toBe(NYE.toLocaleDateString('de-DE', opts))
}
})
it('FE-UTIL-DATEFMT-021: a weekday beside a numeric date keeps the language, the date takes the format', () => {
const opts: Intl.DateTimeFormatOptions = { weekday: 'short', day: '2-digit', month: '2-digit', year: 'numeric', timeZone: 'UTC' }
expect(formatDisplayDate(NYE, 'de-DE', opts, 'YYYY-MM-DD')).toBe(`${NYE.toLocaleDateString('de-DE', { weekday: 'short', timeZone: 'UTC' })}, 2026-12-31`)
expect(formatDisplayDate(NYE, 'de-DE', opts, 'auto')).toBe(NYE.toLocaleDateString('de-DE', opts))
})
it('FE-UTIL-DATEFMT-008: dateStyle short counts as numeric', () => {
expect(formatDisplayDate(NYE, 'en-US', { dateStyle: 'short', timeZone: 'UTC' }, 'DD/MM/YYYY')).toBe('31/12/2026')
})
it('FE-UTIL-DATEFMT-009: an invalid date falls back to toLocaleDateString', () => {
const invalid = new Date('nope')
expect(formatDisplayDate(invalid, 'en-US', NUMERIC, 'YYYY-MM-DD')).toBe(invalid.toLocaleDateString('en-US', NUMERIC))
})
})
describe('formatDisplayDateTime', () => {
it('FE-UTIL-DATEFMT-010: auto, an unknown value or none is exactly toLocaleString', () => {
const opts: Intl.DateTimeFormatOptions = { ...NUMERIC, hour: '2-digit', minute: '2-digit' }
for (const locale of ['en-US', 'de-DE']) {
expect(formatDisplayDateTime(NYE, locale, opts, 'auto')).toBe(NYE.toLocaleString(locale, opts))
expect(formatDisplayDateTime(NYE, locale, opts, 'nope')).toBe(NYE.toLocaleString(locale, opts))
expect(formatDisplayDateTime(NYE, locale, UTC)).toBe(NYE.toLocaleString(locale, UTC))
}
})
it('FE-UTIL-DATEFMT-011: the date follows the format, the time of day stays Intl', () => {
const opts: Intl.DateTimeFormatOptions = { ...NUMERIC, hour: '2-digit', minute: '2-digit' }
const time = NYE.toLocaleTimeString('en-US', { hour: '2-digit', minute: '2-digit', timeZone: 'UTC' })
expect(formatDisplayDateTime(NYE, 'en-US', opts, 'YYYY-MM-DD')).toBe(`2026-12-31 ${time}`)
const hour12 = { ...opts, hour12: false }
const time24 = NYE.toLocaleTimeString('en-US', { hour: '2-digit', minute: '2-digit', hour12: false, timeZone: 'UTC' })
expect(formatDisplayDateTime(NYE, 'en-US', hour12, 'DD.MM.YYYY')).toBe(`31.12.2026 ${time24}`)
})
it('FE-UTIL-DATEFMT-012: without options it writes the date and the default time', () => {
expect(formatDisplayDateTime(NYE, 'en-US', UTC, 'DD/MM/YYYY')).toBe(
`31/12/2026 ${NYE.toLocaleTimeString('en-US', UTC)}`
)
})
it('FE-UTIL-DATEFMT-013: time-only options are passed through untouched', () => {
const opts: Intl.DateTimeFormatOptions = { hour: '2-digit', minute: '2-digit', timeZone: 'UTC' }
expect(formatDisplayDateTime(NYE, 'de-DE', opts, 'YYYY-MM-DD')).toBe(NYE.toLocaleString('de-DE', opts))
})
it('FE-UTIL-DATEFMT-014: date-only options give just the date, named dates stay Intl', () => {
expect(formatDisplayDateTime(NYE, 'en-US', NUMERIC, 'YYYY/MM/DD')).toBe('2026/12/31')
const named: Intl.DateTimeFormatOptions = { weekday: 'short', day: 'numeric', month: 'short', hour: '2-digit', timeZone: 'UTC' }
expect(formatDisplayDateTime(NYE, 'en-US', named, 'YYYY-MM-DD')).toBe(NYE.toLocaleString('en-US', named))
})
})
describe('displayDateFormatter', () => {
it('FE-UTIL-DATEFMT-015: auto behaves like Intl.DateTimeFormat', () => {
const intl = new Intl.DateTimeFormat('en-US', NUMERIC)
expect(displayDateFormatter('en-US', NUMERIC, 'auto').format(NYE)).toBe(intl.format(NYE))
expect(displayDateFormatter('en-US', NUMERIC).format(NYE.getTime())).toBe(intl.format(NYE))
})
it('FE-UTIL-DATEFMT-016: numeric dates follow the format, for Date and timestamp alike', () => {
const f = displayDateFormatter('en-US', NUMERIC, 'DD.MM.YYYY')
expect(f.format(NYE)).toBe('31.12.2026')
expect(f.format(NYE.getTime())).toBe('31.12.2026')
const withTime = displayDateFormatter('en-US', { ...NUMERIC, hour: '2-digit', minute: '2-digit' }, 'YYYY-MM-DD')
expect(withTime.format(NYE)).toBe(
`2026-12-31 ${NYE.toLocaleTimeString('en-US', { hour: '2-digit', minute: '2-digit', timeZone: 'UTC' })}`
)
})
it('FE-UTIL-DATEFMT-017: a named month is left to Intl', () => {
const opts: Intl.DateTimeFormatOptions = { day: 'numeric', month: 'long', timeZone: 'UTC' }
expect(displayDateFormatter('de-DE', opts, 'YYYY-MM-DD').format(NYE)).toBe(new Intl.DateTimeFormat('de-DE', opts).format(NYE))
})
})
describe('dateFieldOrder, dateLayout and isNumericDate', () => {
it('FE-UTIL-DATEFMT-018: a chosen format sets the order, auto asks the language', () => {
expect(dateFieldOrder('en-US', 'DD.MM.YYYY')).toEqual(['day', 'month', 'year'])
expect(dateFieldOrder('de-DE', 'MM/DD/YYYY')).toEqual(['month', 'day', 'year'])
expect(dateFieldOrder('en-US', 'YYYY/MM/DD')).toEqual(['year', 'month', 'day'])
expect(dateFieldOrder('de-DE', 'auto')).toEqual(['day', 'month', 'year'])
expect(dateFieldOrder('en-US')).toEqual(['month', 'day', 'year'])
expect(dateFieldOrder('ko-KR', null)).toEqual(['year', 'month', 'day'])
})
it('FE-UTIL-DATEFMT-019: dateLayout knows the five formats only, isNumericDate spots names', () => {
expect(dateLayout('DD/MM/YYYY')).toEqual({ order: ['day', 'month', 'year'], separator: '/' })
expect(dateLayout('auto')).toBeNull()
expect(dateLayout('nope')).toBeNull()
expect(dateLayout(undefined)).toBeNull()
expect(isNumericDate()).toBe(true)
expect(isNumericDate({ month: '2-digit' })).toBe(true)
expect(isNumericDate({ month: 'short' })).toBe(false)
expect(isNumericDate({ weekday: 'long' })).toBe(false)
expect(isNumericDate({ era: 'short' })).toBe(false)
expect(isNumericDate({ dateStyle: 'short' })).toBe(true)
expect(isNumericDate({ dateStyle: 'long' })).toBe(false)
})
})
describe('dateFormatOptions', () => {
it('FE-UTIL-DATEFMT-020: every choice is labelled by how it writes 31 December, auto with its example', () => {
expect(dateFormatOptions('en-US', 'Automatic')).toEqual([
{ value: 'auto', label: 'Automatic (12/31/2026)' },
{ value: 'YYYY-MM-DD', label: '2026-12-31' },
{ value: 'YYYY/MM/DD', label: '2026/12/31' },
{ value: 'DD.MM.YYYY', label: '31.12.2026' },
{ value: 'DD/MM/YYYY', label: '31/12/2026' },
{ value: 'MM/DD/YYYY', label: '12/31/2026' },
])
expect(dateFormatOptions('de-DE', 'Automatisch')[0]).toEqual({ value: 'auto', label: 'Automatisch (31.12.2026)' })
})
})
})
+179
View File
@@ -0,0 +1,179 @@
import { DATE_FORMAT_VALUES, type DateFormat } from '@trek/shared'
/**
* The user's date format (#2971), applied wherever a date is written in numbers.
*
* Every function here takes the format as an argument and stays pure; the
* current user's value comes from `useDateFormat()` (or `readDateFormat()`
* outside React) in hooks/useDateFormat.ts. 'auto', an unknown value or none
* at all leaves everything to `Intl` and the interface language, exactly as
* TREK wrote dates before the setting existed.
*
* Only the numeric part follows the setting. A date written with a weekday or
* a month name ("Tue, 3 Nov") keeps the language's own wording and order: the
* setting answers "how do I read 03/11", not "what is November called".
*/
export type DateField = 'day' | 'month' | 'year'
interface DateLayout {
order: DateField[]
separator: string
}
const LAYOUTS: Record<Exclude<DateFormat, 'auto'>, DateLayout> = {
'YYYY-MM-DD': { order: ['year', 'month', 'day'], separator: '-' },
'YYYY/MM/DD': { order: ['year', 'month', 'day'], separator: '/' },
'DD.MM.YYYY': { order: ['day', 'month', 'year'], separator: '.' },
'DD/MM/YYYY': { order: ['day', 'month', 'year'], separator: '/' },
'MM/DD/YYYY': { order: ['month', 'day', 'year'], separator: '/' },
}
/** The order and separator of a chosen format; null for 'auto' or anything unknown. */
export function dateLayout(format: string | null | undefined): DateLayout | null {
if (!format || format === 'auto') return null
return LAYOUTS[format as keyof typeof LAYOUTS] ?? null
}
const DATE_KEYS = ['day', 'month', 'year'] as const
const TIME_KEYS = ['hour', 'minute', 'second', 'dayPeriod', 'fractionalSecondDigits'] as const
/**
* Whether these options write the date in numbers only: no weekday, no month
* name, no era. `dateStyle: 'short'` is numeric in every language; the longer
* styles name the month.
*/
export function isNumericDate(opts: Intl.DateTimeFormatOptions = {}): boolean {
if (opts.weekday || opts.era) return false
if (opts.dateStyle) return opts.dateStyle === 'short'
return !opts.month || opts.month === 'numeric' || opts.month === '2-digit'
}
const hasAny = (opts: Intl.DateTimeFormatOptions, keys: readonly string[]) =>
keys.some((key) => (opts as Record<string, unknown>)[key] !== undefined)
/** The date in the layout's order, each field the options ask for (all three when they name none). */
function numericDate(date: Date, opts: Intl.DateTimeFormatOptions, layout: DateLayout): string {
const named = opts.dateStyle ? DATE_KEYS : DATE_KEYS.filter((key) => opts[key] !== undefined)
const fields = named.length > 0 ? named : DATE_KEYS
const parts = new Intl.DateTimeFormat('en-US', {
timeZone: opts.timeZone,
year: 'numeric',
month: '2-digit',
day: '2-digit',
numberingSystem: 'latn',
}).formatToParts(date)
const value = (type: DateField) => parts.find((part) => part.type === type)?.value ?? ''
const shortYear = opts.year === '2-digit'
return layout.order
.filter((field) => (fields as readonly string[]).includes(field))
.map((field) => (field === 'year' && shortYear ? value('year').slice(-2) : value(field)))
.join(layout.separator)
}
/** Only the time-of-day options, for the clock part beside a numeric date. */
function timeOptions(opts: Intl.DateTimeFormatOptions): Intl.DateTimeFormatOptions {
const time: Intl.DateTimeFormatOptions = {}
for (const key of [...TIME_KEYS, 'hour12', 'hourCycle', 'timeZone', 'timeZoneName'] as const) {
const value = (opts as Record<string, unknown>)[key]
if (value !== undefined) (time as Record<string, unknown>)[key] = value
}
if (opts.timeStyle) time.timeStyle = opts.timeStyle
return time
}
/**
* `date.toLocaleDateString(locale, opts)`, with a numeric date written in the
* chosen format. Anything with a weekday or a month name is left to `Intl`.
*/
export function formatDisplayDate(
date: Date,
locale: string | undefined,
opts: Intl.DateTimeFormatOptions = {},
format?: string | null
): string {
const layout = dateLayout(format)
if (!layout || Number.isNaN(date.getTime())) return date.toLocaleDateString(locale, opts)
if (opts.weekday && isNumericWithWeekday(opts)) {
const weekday = date.toLocaleDateString(locale, { weekday: opts.weekday, timeZone: opts.timeZone })
return `${weekday}, ${numericDate(date, opts, layout)}`
}
if (!isNumericDate(opts)) return date.toLocaleDateString(locale, opts)
return numericDate(date, opts, layout)
}
/** A weekday beside a date that is otherwise all numbers ("Tue, 03.11.2026"). */
function isNumericWithWeekday(opts: Intl.DateTimeFormatOptions): boolean {
if (opts.era || opts.dateStyle) return false
return (opts.month === 'numeric' || opts.month === '2-digit') && opts.day !== undefined
}
/**
* `date.toLocaleString(locale, opts)`, with a numeric date part written in the
* chosen format and the time of day left to `Intl` (12h/24h stays the
* caller's option). Options naming only a time are passed through untouched.
*/
export function formatDisplayDateTime(
date: Date,
locale: string | undefined,
opts: Intl.DateTimeFormatOptions = {},
format?: string | null
): string {
const layout = dateLayout(format)
const named = hasAny(opts, DATE_KEYS) || !!opts.dateStyle
const timed = hasAny(opts, TIME_KEYS) || !!opts.timeStyle
if (!layout || !isNumericDate(opts) || Number.isNaN(date.getTime())) return date.toLocaleString(locale, opts)
if (!named && timed) return date.toLocaleString(locale, opts)
const day = numericDate(date, opts, layout)
if (named && !timed) return day
const time = date.toLocaleTimeString(locale, timed ? timeOptions(opts) : { timeZone: opts.timeZone })
return `${day} ${time}`
}
/**
* A drop-in for `new Intl.DateTimeFormat(locale, opts)` where only `.format()`
* is used: numeric dates in the chosen format, the rest by `Intl`.
*/
export function displayDateFormatter(
locale: string | undefined,
opts: Intl.DateTimeFormatOptions = {},
format?: string | null
): { format: (date: Date | number) => string } {
const intl = new Intl.DateTimeFormat(locale, opts)
const layout = dateLayout(format)
if (!layout || !isNumericDate(opts)) return { format: (date) => intl.format(date) }
return {
format: (date) => {
const value = typeof date === 'number' ? new Date(date) : date
return hasAny(opts, TIME_KEYS) || opts.timeStyle
? formatDisplayDateTime(value, locale, opts, format)
: formatDisplayDate(value, locale, opts, format)
},
}
}
/** The order the fields of a typed date are read in: the chosen format's, or the language's. */
export function dateFieldOrder(locale: string | undefined, format?: string | null): DateField[] {
const layout = dateLayout(format)
if (layout) return layout.order
return new Intl.DateTimeFormat(locale, { day: 'numeric', month: 'numeric', year: 'numeric' })
.formatToParts(new Date(2001, 5, 15))
.filter((part) => part.type === 'day' || part.type === 'month' || part.type === 'year')
.map((part) => part.type as DateField)
}
/** 31 December: no day of it reads as a month, so every option's example is unambiguous. */
const SAMPLE = new Date(Date.UTC(2026, 11, 31))
/**
* The choices of the setting, each labelled by how it writes 31 December, and
* 'auto' by `autoLabel` with the language's own way in brackets.
*/
export function dateFormatOptions(locale: string | undefined, autoLabel: string): { value: DateFormat; label: string }[] {
const example = (format: DateFormat) =>
formatDisplayDate(SAMPLE, locale, { day: '2-digit', month: '2-digit', year: 'numeric', timeZone: 'UTC' }, format)
return DATE_FORMAT_VALUES.map((value) => ({
value,
label: value === 'auto' ? `${autoLabel} (${example(value)})` : example(value),
}))
}
+14
View File
@@ -15,4 +15,18 @@ describe('dateInputPattern', () => {
expect(dateInputPattern('ar')).not.toMatch(/[٠-٩\d]/);
expect(dateInputPattern('ar')).toContain('YYYY');
});
it('writes a chosen date format (#2971) as its own pattern, whatever the language', () => {
expect(dateInputPattern('en-US', 'YYYY-MM-DD')).toBe('YYYY-MM-DD');
expect(dateInputPattern('en-US', 'DD.MM.YYYY')).toBe('DD.MM.YYYY');
expect(dateInputPattern('de-DE', 'MM/DD/YYYY')).toBe('MM/DD/YYYY');
expect(dateInputPattern('ko-KR', 'YYYY/MM/DD')).toBe('YYYY/MM/DD');
});
it('keeps the locale pattern for auto, an unknown value or none', () => {
expect(dateInputPattern('de-DE', 'auto')).toBe('DD.MM.YYYY');
expect(dateInputPattern('en-US', 'auto')).toBe('MM/DD/YYYY');
expect(dateInputPattern('en-GB', 'DD-MM-YY')).toBe('DD/MM/YYYY');
expect(dateInputPattern('en-GB', null)).toBe('DD/MM/YYYY');
});
});
+6 -2
View File
@@ -1,3 +1,5 @@
import { dateLayout } from './dateFormat';
const LETTERS: Record<string, string> = { day: 'DD', month: 'MM', year: 'YYYY' };
/**
@@ -5,9 +7,11 @@ const LETTERS: Record<string, string> = { day: 'DD', month: 'MM', year: 'YYYY' }
* locale's own separators. It is the hint of the manual date field, which is
* pre-filled and read back in this same order, so a Korean user sees
* "YYYY. MM. DD." rather than a German "DD.MM.YYYY". Direction marks are dropped:
* the hint shows the shape, the field itself carries the script.
* the hint shows the shape, the field itself carries the script. A chosen date
* format (#2971) is its own pattern.
*/
export function dateInputPattern(locale: string): string {
export function dateInputPattern(locale: string, format?: string | null): string {
if (dateLayout(format)) return String(format);
return new Intl.DateTimeFormat(locale, { day: '2-digit', month: '2-digit', year: 'numeric', timeZone: 'UTC' })
.formatToParts(new Date(Date.UTC(2001, 5, 15)))
.map((part) => LETTERS[part.type] ?? part.value.replace(/[؜‎‏]/g, ''))