diff --git a/client/src/components/Admin/paddle/PaddleAutoLoadParts.tsx b/client/src/components/Admin/paddle/PaddleAutoLoadParts.tsx index 729bc318f..dc434a5a2 100644 --- a/client/src/components/Admin/paddle/PaddleAutoLoadParts.tsx +++ b/client/src/components/Admin/paddle/PaddleAutoLoadParts.tsx @@ -1,6 +1,8 @@ import type { PaddleRegionAutoMode, PaddleRegionPending } from '@trek/shared'; import { Ban, CloudDownload, Hand, Loader2, Power, Sparkles } from 'lucide-react'; +import { useDateFormat } from '../../../hooks/useDateFormat'; import { useTranslation } from '../../../i18n'; +import { formatDisplayDate } from '../../../utils/dateFormat'; import { ChoiceChips, SettingRows, SETTINGS_BUTTON, SettingsHint, StatusPill } from '../../Settings/settingsKit'; import { LABEL, Segmented } from '../../shared/dialogParts'; import { fs } from '../../shared/DialogShell'; @@ -71,8 +73,9 @@ export function AutoLoadSettings({ admin }: { admin: Admin }) { function RequestRow({ request, admin }: { request: PaddleRegionPending; admin: Admin }) { const { t, language } = useTranslation(); const megabytes = useMegabytes(); + const dateFormat = useDateFormat(); const busy = admin.busyId === request.id; - const date = new Date(request.requested_at).toLocaleDateString(language, { dateStyle: 'medium' }); + const date = formatDisplayDate(new Date(request.requested_at), language, { dateStyle: 'medium' }, dateFormat); return (
diff --git a/client/src/components/Roadtrip/RoadtripSidebarHeaders.test.tsx b/client/src/components/Roadtrip/RoadtripSidebarHeaders.test.tsx index f925c4d4a..dcfc2d35a 100644 --- a/client/src/components/Roadtrip/RoadtripSidebarHeaders.test.tsx +++ b/client/src/components/Roadtrip/RoadtripSidebarHeaders.test.tsx @@ -104,6 +104,24 @@ describe('DayHeader', () => { expect(container.querySelector('time')).toHaveTextContent('6/2') }) + it('FE-ROADTRIP-HEADERS-003c: a chosen date format sets the order and separator on the tile, whatever the clock', () => { + const tileDate = (time_format: string, date_format: string): string | null => { + useSettingsStore.setState({ settings: { distance_unit: 'metric', time_format, date_format } as never }) + const { container, unmount } = wrap() + const text = container.querySelector('time')!.textContent + unmount() + return text + } + // 5 October: a 12-hour reader who writes the day first no longer sees "10/5". + expect(tileDate('12h', 'DD/MM/YYYY')).toBe('5/10') + expect(tileDate('24h', 'YYYY-MM-DD')).toBe('10-5') + expect(tileDate('12h', 'DD.MM.YYYY')).toBe('5.10.') + expect(tileDate('24h', 'MM/DD/YYYY')).toBe('10/5') + // On auto the clock still decides, as before the format existed. + expect(tileDate('12h', 'auto')).toBe('10/5') + expect(tileDate('24h', 'auto')).toBe('5.10.') + }) + it('FE-ROADTRIP-HEADERS-004: the pills never wrap but give way in steps as the row narrows, and a day of only its night has no drive and no count', () => { // Room for everything: the drive with its time, the count with its word. The old // narrow flag no longer decides it; the row measures its own room. diff --git a/client/src/components/Roadtrip/RoadtripSidebarHeaders.tsx b/client/src/components/Roadtrip/RoadtripSidebarHeaders.tsx index 0a1432438..3db7565b9 100644 --- a/client/src/components/Roadtrip/RoadtripSidebarHeaders.tsx +++ b/client/src/components/Roadtrip/RoadtripSidebarHeaders.tsx @@ -6,6 +6,8 @@ import { useTranslation } from '../../i18n/TranslationContext' import { Tooltip } from '../shared/Tooltip' import { NEUTRAL_TINT, fs } from '../shared/DialogShell' import { useSettingsStore } from '../../store/settingsStore' +import { useDateFormat } from '../../hooks/useDateFormat' +import { dateLayout } from '../../utils/dateFormat' import { formatDistance } from '../../utils/units' import { formatDate } from '../../utils/formatters' import { formatDurationShort } from './roadtripModel' @@ -89,13 +91,22 @@ export function TripSummary({ routes, narrow }: { routes: RoadtripRoutes; narrow } /** - * A date short enough for the day tile, in the order the reader's clock setting implies: - * month first with the 12-hour clock ("10/5"), day first with the 24-hour one ("5.10."). + * A date short enough for the day tile: day and month, unpadded, in the order and with + * the separator of the reader's date format ("5/10", "10-5", "5.10."). With the format + * on 'auto' the clock setting still decides, as it did before the format existed: month + * first with the 12-hour clock ("10/5"), day first with the 24-hour one ("5.10."). */ -function shortDate(iso: string, is12h: boolean): string { +function shortDate(iso: string, is12h: boolean, format?: string | null): string { const [, m, d] = iso.split("-").map(Number) if (!m || !d) return iso - return is12h ? `${m}/${d}` : `${d}.${m}.` + const layout = dateLayout(format) + if (!layout) return is12h ? `${m}/${d}` : `${d}.${m}.` + const text = layout.order + .filter(field => field !== 'year') + .map(field => (field === 'day' ? d : m)) + .join(layout.separator) + // The dotted layout closes on a dot the way it is written in full ("5.10.2026"). + return layout.separator === '.' ? `${text}.` : text } @@ -139,6 +150,7 @@ function flagTexts(day: RoadtripDay, followable: boolean, t: ReturnType s.settings.time_format) === "12h" + const dateFormat = useDateFormat() return ( ) : null} diff --git a/client/src/components/Tours/paddle/ObstacleDecisionPanel.tsx b/client/src/components/Tours/paddle/ObstacleDecisionPanel.tsx index 96195e51a..a62995592 100644 --- a/client/src/components/Tours/paddle/ObstacleDecisionPanel.tsx +++ b/client/src/components/Tours/paddle/ObstacleDecisionPanel.tsx @@ -19,6 +19,7 @@ import { X, } from 'lucide-react'; import { useEffect, useLayoutEffect, useRef, useState, type KeyboardEvent, type ReactNode } from 'react'; +import { useDateFormat } from '../../../hooks/useDateFormat'; import { useTranslation } from '../../../i18n'; import { fs } from '../../shared/DialogShell'; import { Tooltip } from '../../shared/Tooltip'; @@ -306,9 +307,10 @@ function decidedLine( decision: ObstacleDecisionRecord, memberName: (id: number | null) => string | null, t: Translate, - locale: string + locale: string, + dateFormat: string ): string { - const date = formatCheckDate(decision.decided_at, locale); + const date = formatCheckDate(decision.decided_at, locale, dateFormat); const name = memberName(decision.decided_by); return name ? t('tours.paddle.check.decidedBy', { date, name }) : t('tours.paddle.check.decidedAt', { date }); } @@ -330,10 +332,11 @@ function MetaLine({ onNext: (() => void) | null; }) { const { t, locale } = useTranslation(); + const dateFormat = useDateFormat(); if (!decision && !onNext) return null; return (
- {decision && {decidedLine(decision, memberName, t, locale)}} + {decision && {decidedLine(decision, memberName, t, locale, dateFormat)}} {decision && clearable && (
{entry.decision && } diff --git a/client/src/components/Tours/paddle/PaddleCheckBadges.tsx b/client/src/components/Tours/paddle/PaddleCheckBadges.tsx index ba70b9c51..b13696507 100644 --- a/client/src/components/Tours/paddle/PaddleCheckBadges.tsx +++ b/client/src/components/Tours/paddle/PaddleCheckBadges.tsx @@ -7,6 +7,7 @@ import type { TourObstacleEntry, } from '@trek/shared'; import { RotateCcw } from 'lucide-react'; +import { useDateFormat } from '../../../hooks/useDateFormat'; import { useTranslation } from '../../../i18n'; import { TourDayRowPill } from '../TourDayRowFacts'; import { FigureBadge } from './FigureBadge'; @@ -77,8 +78,9 @@ export function PaddleCheckPill({ check }: { check: PaddleCheck }) { */ export function PaddleCheckDataLine({ check }: { check: PaddleCheck }) { const { t, locale } = useTranslation(); + const dateFormat = useDateFormat(); const word = checkDataWord(check.data, t); - const asOf = check.data_as_of ? formatCheckDate(check.data_as_of, locale) : null; + const asOf = check.data_as_of ? formatCheckDate(check.data_as_of, locale, dateFormat) : null; const coverage = check.data === 'covered' ? null : COVERAGE_INFO[check.data](t, asOf ?? t('tours.paddle.obstacles.dateUnknown')); return ( @@ -103,7 +105,7 @@ export function PaddleCheckDataLine({ check }: { check: PaddleCheck }) { ) : null}
diff --git a/client/src/components/Tours/paddle/PaddleCheckCard.tsx b/client/src/components/Tours/paddle/PaddleCheckCard.tsx index d3394f6f2..502e4a3c7 100644 --- a/client/src/components/Tours/paddle/PaddleCheckCard.tsx +++ b/client/src/components/Tours/paddle/PaddleCheckCard.tsx @@ -8,6 +8,7 @@ import type { } from '@trek/shared'; import { AlertTriangle, CloudOff, LifeBuoy, ListChecks, Loader2, PencilLine, Save, WifiOff } from 'lucide-react'; import { useEffect, useId, useMemo, useRef, useState, type ReactNode } from 'react'; +import { useDateFormat } from '../../../hooks/useDateFormat'; import { useTranslation } from '../../../i18n'; import { useSettingsStore } from '../../../store/settingsStore'; import { formatDistance } from '../../../utils/units'; @@ -81,8 +82,9 @@ function rowKey(row: ChecklistRow, index: number): string { /** The sentence the checklist's state calls for. */ function CheckNoticeLine({ notice, evaluatedAt }: { notice: CheckNotice; evaluatedAt: string | null }) { const { t, locale } = useTranslation(); + const dateFormat = useDateFormat(); const { textKey, icon, role } = NOTICES[notice]; - const time = evaluatedAt ? formatCheckDate(evaluatedAt, locale) : ''; + const time = evaluatedAt ? formatCheckDate(evaluatedAt, locale, dateFormat) : ''; return ( {t(textKey, { time })} @@ -311,11 +313,12 @@ function EarlierDecisions({ /** A route without rows: nothing known where the data covers it, no data where there is none; else the data line speaks. */ function EmptyLine({ summary }: { summary: PaddleCheck | null }) { const { t, locale } = useTranslation(); + const dateFormat = useDateFormat(); let text: string | null = null; if (summary?.data === 'none') text = t('tours.paddle.obstacles.none'); else if (summary?.data === 'covered') { const date = summary.data_as_of - ? formatCheckDate(summary.data_as_of, locale) + ? formatCheckDate(summary.data_as_of, locale, dateFormat) : t('tours.paddle.obstacles.dateUnknown'); text = t('tours.paddle.obstacles.coveredEmpty', { date }); } diff --git a/client/src/components/Tours/paddle/PaddleObstacleCard.tsx b/client/src/components/Tours/paddle/PaddleObstacleCard.tsx index 569797808..4a4264bda 100644 --- a/client/src/components/Tours/paddle/PaddleObstacleCard.tsx +++ b/client/src/components/Tours/paddle/PaddleObstacleCard.tsx @@ -1,8 +1,10 @@ import { ExternalLink, X } from 'lucide-react'; import type { ReactNode } from 'react'; +import { useDateFormat } from '../../../hooks/useDateFormat'; import { useTranslation } from '../../../i18n'; import { useSettingsStore } from '../../../store/settingsStore'; import type { DistanceUnit } from '../../../types'; +import { formatDisplayDate } from '../../../utils/dateFormat'; import { formatDistance } from '../../../utils/units'; import { MAP_CARD_GLASS } from '../../Map/mapControlShadow'; import { SoftPill } from '../../Planner/planParts'; @@ -86,7 +88,10 @@ function AccessAndFacts({ detail, unit }: { detail: PaddleObstacleDetail; unit: /** The way to the source and how current it is; a record in the data is no check on site. */ function SourceLines({ detail }: { detail: PaddleObstacleDetail }) { const { t, language } = useTranslation(); - const date = detail.dataAsOf ? new Date(detail.dataAsOf).toLocaleDateString(language, { dateStyle: 'medium' }) : null; + const dateFormat = useDateFormat(); + const date = detail.dataAsOf + ? formatDisplayDate(new Date(detail.dataAsOf), language, { dateStyle: 'medium' }, dateFormat) + : null; return ( <> region.source_timestamp) .filter((time): time is string => !!time) .sort(compareCodeUnits); - return times[0] ? new Date(times[0]).toLocaleDateString(language, { dateStyle: 'medium' }) : null; + return times[0] ? formatDisplayDate(new Date(times[0]), language, { dateStyle: 'medium' }, dateFormat) : null; } /** @@ -23,6 +29,7 @@ function dataDate(regions: readonly { source_timestamp?: string | null }[], lang */ export function PaddleObstacleNotice() { const { t, language } = useTranslation(); + const dateFormat = useDateFormat(); const { status, coverage, related, regions, truncated } = usePaddleObstacleStore( useShallow((state) => ({ status: state.status, @@ -43,7 +50,7 @@ export function PaddleObstacleNotice() { if (status === 'offline') return }>{t('tours.paddle.obstacles.offline')}; if (status === 'error') return {t('tours.paddle.obstacles.error')}; - const date = dataDate(regions, language) ?? t('tours.paddle.obstacles.dateUnknown'); + const date = dataDate(regions, language, dateFormat) ?? t('tours.paddle.obstacles.dateUnknown'); if (coverage === 'none') return {t('tours.paddle.obstacles.none')}; if (coverage === 'partial') return {t('tours.paddle.obstacles.partial', { date })}; diff --git a/client/src/components/Tours/paddle/paddleCheckModel.test.ts b/client/src/components/Tours/paddle/paddleCheckModel.test.ts index 3065b218d..3f45a32df 100644 --- a/client/src/components/Tours/paddle/paddleCheckModel.test.ts +++ b/client/src/components/Tours/paddle/paddleCheckModel.test.ts @@ -1,4 +1,4 @@ -// PCM-001 to PCM-019: the check bench of a paddle tour in one pill, how the dates of the checklist read, where the +// PCM-001 to PCM-020: the check bench of a paddle tour in one pill, how the dates of the checklist read, where the // camera goes for an entry and the order the checklist lists its rows in (PAD-06, PAD-09). import { Ban, CircleDashed, ListChecks } from 'lucide-react'; import { describe, expect, it } from 'vitest'; @@ -146,6 +146,13 @@ describe('formatCheckDate', () => { expect(formatCheckDate('', 'en')).toBe(''); expect(formatCheckDate('2026-05', 'not a language')).toBe('2026-05'); }); + + it('PCM-020: a day takes the chosen date format where the language writes it in numbers, a month stays named', () => { + expect(formatCheckDate('2026-10-01', 'de', 'YYYY-MM-DD')).toBe('2026-10-01'); + expect(formatCheckDate('2026-10-01', 'de', 'auto')).toBe(formatCheckDate('2026-10-01', 'de')); + expect(formatCheckDate('2026-10-01', 'en', 'YYYY-MM-DD')).toMatch(/Oct.*1.*2026/); + expect(formatCheckDate('2026-05', 'de', 'YYYY-MM-DD')).toBe(formatCheckDate('2026-05', 'de')); + }); }); describe('focusPointsOf', () => { diff --git a/client/src/components/Tours/paddle/paddleCheckModel.ts b/client/src/components/Tours/paddle/paddleCheckModel.ts index 1c45b27ce..e1f48bfef 100644 --- a/client/src/components/Tours/paddle/paddleCheckModel.ts +++ b/client/src/components/Tours/paddle/paddleCheckModel.ts @@ -7,6 +7,7 @@ import { type TourOwnEntry, } from '@trek/shared'; import { Ban, CircleDashed, ListChecks, type LucideIcon } from 'lucide-react'; +import { formatDisplayDate } from '../../../utils/dateFormat'; type Translate = (key: string, params?: Record) => string; @@ -52,8 +53,11 @@ export function paddleCheckFact(check: PaddleCheck, t: Translate): { icon: Lucid const MONTH = /^(\d{4})-(\d{2})$/; -/** A date of the checklist in the user's locale: a bare `YYYY-MM` (an OSM check date) reads as month and year. */ -export function formatCheckDate(value: string, locale: string): string { +/** + * A date of the checklist in the user's locale: a bare `YYYY-MM` (an OSM check date) reads as month and year. + * `format` is the user's date format, which the day takes where the language writes it in numbers. + */ +export function formatCheckDate(value: string, locale: string, format?: string | null): string { const month = MONTH.exec(value); try { if (month) { @@ -64,7 +68,7 @@ export function formatCheckDate(value: string, locale: string): string { if (Number.isNaN(date.getTime())) return value; // A bare day is a calendar day, not an instant in the user's zone. const timeZone = /^\d{4}-\d{2}-\d{2}$/.test(value) ? 'UTC' : undefined; - return new Intl.DateTimeFormat(locale, { dateStyle: 'medium', timeZone }).format(date); + return formatDisplayDate(date, locale, { dateStyle: 'medium', timeZone }, format); } catch { return value; } diff --git a/client/src/mobile/screens/admin/MAdminPaddleRegionsPanel.tsx b/client/src/mobile/screens/admin/MAdminPaddleRegionsPanel.tsx index d42a5ed87..af0a35e1c 100644 --- a/client/src/mobile/screens/admin/MAdminPaddleRegionsPanel.tsx +++ b/client/src/mobile/screens/admin/MAdminPaddleRegionsPanel.tsx @@ -23,7 +23,9 @@ import { regionStatusTone, } from '../../../components/Admin/paddle/paddleRegionsModel'; import { usePaddleRegionsAdmin } from '../../../components/Admin/paddle/usePaddleRegionsAdmin'; +import { useDateFormat } from '../../../hooks/useDateFormat'; import { useTranslation } from '../../../i18n'; +import { formatDisplayDate } from '../../../utils/dateFormat'; import MBadge from '../../components/MBadge'; import MChip from '../../components/MChip'; import MConfirmSheet from '../settings/MConfirmSheet'; @@ -111,6 +113,7 @@ function AutoLoad({ admin }: { admin: Admin }) { function RequestRow({ request, admin }: { request: PaddleRegionPending; admin: Admin }) { const { t, language } = useTranslation(); + const dateFormat = useDateFormat(); const busy = admin.busyId === request.id; return (
@@ -134,7 +137,7 @@ function RequestRow({ request, admin }: { request: PaddleRegionPending; admin: A {t('admin.paddleRegions.requests.by', { user: request.requested_by })} )} - {new Date(request.requested_at).toLocaleDateString(language, { dateStyle: 'medium' })} + {formatDisplayDate(new Date(request.requested_at), language, { dateStyle: 'medium' }, dateFormat)}
@@ -269,13 +272,14 @@ function CatalogSearch({ admin }: { admin: Admin }) { /** What a region's read stands at: its status, where it came from, its objects, its date and its water. */ function RegionBadges({ region }: { region: PaddleRegion }) { const { t, language } = useTranslation(); + const dateFormat = useDateFormat(); const percent = progressPercent(region); const status = region.status === 'importing' && region.progress ? t(`admin.paddleRegions.phase.${region.progress.phase}`) : t(`admin.paddleRegions.status.${region.status}`); const date = region.source_timestamp - ? new Date(region.source_timestamp).toLocaleDateString(language, { dateStyle: 'medium' }) + ? formatDisplayDate(new Date(region.source_timestamp), language, { dateStyle: 'medium' }, dateFormat) : null; const km = region.network ? new Intl.NumberFormat(language, { maximumFractionDigits: 0 }).format(region.network.water_km) diff --git a/client/src/mobile/screens/trip/tabs/MCollabPolls.tsx b/client/src/mobile/screens/trip/tabs/MCollabPolls.tsx index a7e6604cc..a94949e84 100644 --- a/client/src/mobile/screens/trip/tabs/MCollabPolls.tsx +++ b/client/src/mobile/screens/trip/tabs/MCollabPolls.tsx @@ -299,6 +299,19 @@ function PollCardRow({ poll, canEdit, currentUserId, t, onVote, onClosePoll, onD ) } +const BARE_DAY = /^(\d{4})-(\d{2})-(\d{2})$/ + +/** + * The instant a deadline from the picker stands for. With its time cleared the picker + * hands back the day alone, and `new Date('2030-08-01')` reads that as UTC midnight, + * hours off the reader's own day; a day without a time runs to its end on their clock. + */ +function deadlineInstant(value: string): string { + const day = BARE_DAY.exec(value) + const date = day ? new Date(Number(day[1]), Number(day[2]) - 1, Number(day[3]), 23, 59) : new Date(value) + return date.toISOString() +} + function PollFormSheet({ open, onClose, onSubmit, t }: { open: boolean onClose: () => void @@ -330,7 +343,7 @@ function PollFormSheet({ open, onClose, onSubmit, t }: { question: question.trim(), options: trimmedOptions, multipleChoice, - deadline: deadline ? new Date(deadline).toISOString() : null, + deadline: deadline ? deadlineInstant(deadline) : null, }) onClose() } catch { diff --git a/client/src/utils/dateFormat.test.ts b/client/src/utils/dateFormat.test.ts index 881debc1a..d6b40fee7 100644 --- a/client/src/utils/dateFormat.test.ts +++ b/client/src/utils/dateFormat.test.ts @@ -1,10 +1,9 @@ -// FE-UTIL-DATEFMT-001 to FE-UTIL-DATEFMT-020 +// FE-UTIL-DATEFMT-001 to FE-UTIL-DATEFMT-023 import { describe, expect, it } from 'vitest'; import { dateFieldOrder, dateFormatOptions, dateLayout, - displayDateFormatter, formatDisplayDate, formatDisplayDateTime, isNumericDate, @@ -78,13 +77,27 @@ describe('dateFormat (#2971)', () => { { 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' }, + { dateStyle: 'long', timeZone: 'UTC' }, + { dateStyle: 'full', 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-022: dateStyle medium follows the format where the language writes it in numbers', () => { + const opts: Intl.DateTimeFormatOptions = { dateStyle: 'medium', timeZone: 'UTC' }; + // German "31.12.2026", Japanese "2026/12/31", Czech "31. 12. 2026", Korean "2026. 12. 31.". + for (const locale of ['de-DE', 'ja-JP', 'cs-CZ', 'ko-KR']) { + expect(formatDisplayDate(NYE, locale, opts, 'YYYY-MM-DD')).toBe('2026-12-31'); + } + // English and French name the month, Chinese writes words between the numbers. + for (const locale of ['en-US', 'fr-FR', 'zh-CN']) { + expect(formatDisplayDate(NYE, locale, opts, 'YYYY-MM-DD')).toBe(NYE.toLocaleDateString(locale, opts)); + } + expect(formatDisplayDate(NYE, 'de-DE', opts, 'auto')).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', @@ -157,30 +170,12 @@ describe('dateFormat (#2971)', () => { }; 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) - ); + it('FE-UTIL-DATEFMT-023: dateStyle medium with a time puts the numeric date in the format', () => { + const opts: Intl.DateTimeFormatOptions = { dateStyle: 'medium', timeStyle: 'short', timeZone: 'UTC' }; + const time = NYE.toLocaleTimeString('de-DE', { timeStyle: 'short', timeZone: 'UTC' }); + expect(formatDisplayDateTime(NYE, 'de-DE', opts, 'DD/MM/YYYY')).toBe(`31/12/2026 ${time}`); + expect(formatDisplayDateTime(NYE, 'en-US', opts, 'DD/MM/YYYY')).toBe(NYE.toLocaleString('en-US', opts)); }); }); @@ -206,6 +201,10 @@ describe('dateFormat (#2971)', () => { expect(isNumericDate({ era: 'short' })).toBe(false); expect(isNumericDate({ dateStyle: 'short' })).toBe(true); expect(isNumericDate({ dateStyle: 'long' })).toBe(false); + expect(isNumericDate({ dateStyle: 'medium' }, 'de-DE')).toBe(true); + expect(isNumericDate({ dateStyle: 'medium' }, 'ja-JP')).toBe(true); + expect(isNumericDate({ dateStyle: 'medium' }, 'en-US')).toBe(false); + expect(isNumericDate({ dateStyle: 'long' }, 'de-DE')).toBe(false); }); }); diff --git a/client/src/utils/dateFormat.ts b/client/src/utils/dateFormat.ts index ce562d38f..a803ba18d 100644 --- a/client/src/utils/dateFormat.ts +++ b/client/src/utils/dateFormat.ts @@ -35,20 +35,53 @@ export function dateLayout(format: string | null | undefined): DateLayout | null return LAYOUTS[format as keyof typeof LAYOUTS] ?? null; } +/** 31 December: no day of it reads as a month, so every example and probe of a layout is unambiguous. */ +const SAMPLE = new Date(Date.UTC(2026, 11, 31)); + 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. + * name, no era. `dateStyle: 'short'` is numeric in every language. The longer + * styles depend on the language: 'medium' names the month in English or French + * but is all numbers in German ("31.12.2026"), Czech or Japanese ("2026/12/31"), + * so those are asked of `Intl` for the given locale. */ -export function isNumericDate(opts: Intl.DateTimeFormatOptions = {}): boolean { +export function isNumericDate(opts: Intl.DateTimeFormatOptions = {}, locale?: string): boolean { if (opts.weekday || opts.era) return false; - if (opts.dateStyle) return opts.dateStyle === 'short'; + if (opts.dateStyle) return opts.dateStyle === 'short' || isNumericStyle(opts.dateStyle, locale); return !opts.month || opts.month === 'numeric' || opts.month === '2-digit'; } +const numericStyles = new Map(); + +/** + * Whether a language writes this dateStyle as digits and punctuation alone. A + * month name, a weekday or a word between the numbers ("2026年12月31日") keeps + * it with the language, the same as a month name in explicit options would. + */ +function isNumericStyle(dateStyle: NonNullable, locale?: string): boolean { + const key = `${locale ?? ''}|${dateStyle}`; + let numeric = numericStyles.get(key); + if (numeric === undefined) { + // Separators may carry the bidi marks Arabic puts around them (\p{Cf}). + try { + numeric = new Intl.DateTimeFormat(locale, { dateStyle, timeZone: 'UTC' }) + .formatToParts(SAMPLE) + .every((part) => + part.type === 'literal' + ? /^[\s\p{P}\p{Cf}]*$/u.test(part.value) + : (part.type === 'day' || part.type === 'month' || part.type === 'year') && /^\p{Nd}+$/u.test(part.value) + ); + } catch { + numeric = false; + } + numericStyles.set(key, numeric); + } + return numeric; +} + const hasAny = (opts: Intl.DateTimeFormatOptions, keys: readonly string[]) => keys.some((key) => (opts as Record)[key] !== undefined); @@ -98,7 +131,7 @@ export function formatDisplayDate( 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); + if (!isNumericDate(opts, locale)) return date.toLocaleDateString(locale, opts); return numericDate(date, opts, layout); } @@ -122,7 +155,7 @@ export function formatDisplayDateTime( 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 (!layout || !isNumericDate(opts, locale) || 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; @@ -130,28 +163,6 @@ export function formatDisplayDateTime( 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); @@ -162,9 +173,6 @@ export function dateFieldOrder(locale: string | undefined, format?: string | nul .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. diff --git a/client/tests/unit/mobile/trip/MCollabPolls.test.tsx b/client/tests/unit/mobile/trip/MCollabPolls.test.tsx index bf1618fe3..e2f0c58e6 100644 --- a/client/tests/unit/mobile/trip/MCollabPolls.test.tsx +++ b/client/tests/unit/mobile/trip/MCollabPolls.test.tsx @@ -10,7 +10,7 @@ import { buildPlanner, buildToast } from '../../../helpers/mobileTrip' import { resetAllStores, seedStore } from '../../../helpers/store' import { act, fireEvent, render, screen, waitFor } from '../../../helpers/render' -// FE-MOB-POLLS-001 to FE-MOB-POLLS-024 +// FE-MOB-POLLS-001 to FE-MOB-POLLS-030 const ME = 7 @@ -353,6 +353,25 @@ describe('MCollabPolls', () => { expect(await screen.findByText('Which hotel?')).toBeInTheDocument() }) + it('FE-MOB-POLLS-030: a deadline whose time was cleared closes at the end of that day on the local clock', async () => { + const createPoll = vi.spyOn(collabApi, 'createPoll').mockResolvedValue({ poll: poll({ id: 6 }) }) + setup([]) + + fireEvent.click(await screen.findByRole('button', { name: 'collab.polls.new' })) + fireEvent.change(await screen.findByPlaceholderText('collab.polls.questionPlaceholder'), { target: { value: 'Q' } }) + fireEvent.change(screen.getByPlaceholderText('collab.polls.optionPlaceholder:1'), { target: { value: 'A' } }) + fireEvent.change(screen.getByPlaceholderText('collab.polls.optionPlaceholder:2'), { target: { value: 'B' } }) + setDeadline('2030-08-01') + // Emptying the time field leaves the picker with the bare day, which a plain + // new Date() would read as UTC midnight. + fireEvent.change(screen.getByPlaceholderText('00:00'), { target: { value: '' } }) + fireEvent.click(screen.getByRole('button', { name: 'collab.polls.create' })) + + await waitFor(() => expect(createPoll).toHaveBeenCalledWith(1, expect.objectContaining({ + deadline: new Date(2030, 7, 1, 23, 59).toISOString(), + }))) + }) + it('FE-MOB-POLLS-023: gates the submit button on a question plus two non-blank options', async () => { setup([])