import type { PlacesLibraryTripDetail, PlacesLibraryTripOrigin } from '@trek/shared'; /** * The dates of "All places" in the reader's language: a trip as one short range * ("1 to 5 Dec" in the locale's own form), a planned day as its weekday and date ("Wed, 2 Dec"). Dates are * calendar days without a time zone, read and written in UTC so no zone shifts them. */ const SHORT: Intl.DateTimeFormatOptions = { day: 'numeric', month: 'short', timeZone: 'UTC' }; const asDate = (iso: string | null | undefined): Date | null => { if (!iso) return null; const d = new Date(`${iso.slice(0, 10)}T00:00:00Z`); return Number.isNaN(d.getTime()) ? null : d; }; export function tripRange( start: string | null | undefined, end: string | null | undefined, language: string ): string | null { const a = asDate(start); const b = asDate(end); if (a && b) { // ES2020's lib does not know formatRange yet; every browser TREK runs in has it. const range = new Intl.DateTimeFormat(language, SHORT) as Intl.DateTimeFormat & { formatRange?: (from: Date, to: Date) => string; }; if (range.formatRange) return range.formatRange(a, b); return `${range.format(a)} – ${range.format(b)}`; } const one = a ?? b; return one ? new Intl.DateTimeFormat(language, SHORT).format(one) : null; } export function dayDate(date: string | null | undefined, language: string): string | null { const d = asDate(date); return d ? new Intl.DateTimeFormat(language, { ...SHORT, weekday: 'short' }).format(d) : null; } /** What a trip origin says under its name: the planned day, or the trip's dates when it is not planned yet. */ export function tripLine( origin: Pick, detail: Pick, language: string, t: (key: string, params?: Record) => string ): string | null { const day = detail.days[0]; if (!day) return tripRange(origin.trip_start, origin.trip_end, language); const when = [dayDate(day.date, language), day.time].filter(Boolean).join(', '); const first = when ? t('collections.library.dayOn', { day: day.day_number, date: when }) : t('collections.library.day', { day: day.day_number }); return detail.days.length > 1 ? `${first} ${t('collections.library.moreOrigins', { count: detail.days.length - 1 })}` : first; }