diff --git a/client/src/components/Dashboard/useDashboardTimezones.test.ts b/client/src/components/Dashboard/useDashboardTimezones.test.ts index c2fb01c13..b5580930f 100644 --- a/client/src/components/Dashboard/useDashboardTimezones.test.ts +++ b/client/src/components/Dashboard/useDashboardTimezones.test.ts @@ -1,4 +1,4 @@ -// FE-COMP-TZHOOK-001 to -007: the world clocks both dashboards share. +// FE-COMP-TZHOOK-001 to -009: the world clocks both dashboards share. import { act, renderHook, waitFor } from '@testing-library/react'; import { useSettingsStore } from '../../store/settingsStore'; @@ -97,4 +97,27 @@ describe('useDashboardTimezones', () => { expect(localStorage.getItem('trek_dashboard_tz')).toBeNull(); expect(updateSetting).not.toHaveBeenCalled(); }); + + // #2694: Chrome on Windows names no zone for a system zone it cannot map. + it('FE-COMP-TZHOOK-008: a browser that names no zone still gets the default clocks', () => { + const original = Intl.DateTimeFormat.prototype.resolvedOptions; + const spy = vi.spyOn(Intl.DateTimeFormat.prototype, 'resolvedOptions').mockImplementation(function ( + this: Intl.DateTimeFormat + ) { + return { ...original.call(this), timeZone: undefined as unknown as string }; + }); + try { + const { result } = renderHook(() => useDashboardTimezones('en')); + expect(result.current.zones).toEqual(['Europe/London', 'Asia/Tokyo']); + expect(() => result.current.zones.map((tz) => result.current.timeIn(tz))).not.toThrow(); + } finally { + spy.mockRestore(); + } + }); + + it('FE-COMP-TZHOOK-009: a stored zone this browser does not know is left out instead of crashing the clocks', () => { + seedSettings(['Europe/Berlin', 'Mars/Olympus_Mons', '']); + const { result } = renderHook(() => useDashboardTimezones('en')); + expect(result.current.zones).toEqual(['Europe/Berlin']); + }); }); diff --git a/client/src/components/Dashboard/useDashboardTimezones.ts b/client/src/components/Dashboard/useDashboardTimezones.ts index bc7ca6d3d..a2da83bb0 100644 --- a/client/src/components/Dashboard/useDashboardTimezones.ts +++ b/client/src/components/Dashboard/useDashboardTimezones.ts @@ -1,6 +1,7 @@ import { useEffect, useMemo, useState } from 'react'; import { useSettingsStore } from '../../store/settingsStore'; +import { browserTimeZone, isValidTimeZone } from '../../utils/localDate'; const DEFAULT_ZONES = ['Europe/London', 'Asia/Tokyo']; @@ -38,13 +39,15 @@ export function shortZone(tz: string): string { * clocks tick every 30 seconds, `adding` toggles the zone picker. */ export function useDashboardTimezones(locale: string) { - const home = Intl.DateTimeFormat().resolvedOptions().timeZone; + const home = browserTimeZone(); const [now, setNow] = useState(() => new Date()); const isLoaded = useSettingsStore((s) => s.isLoaded); const updateSetting = useSettingsStore((s) => s.updateSetting); const stored = useSettingsStore((s) => s.settings.dashboard_timezones); // Unset (never chosen) falls back to home + defaults; an explicit list is honoured. - const zones = stored ?? [home, ...DEFAULT_ZONES]; + // A browser that names no zone (#2694) or a zone this browser does not know + // would throw while rendering a clock, so such entries are left out. + const zones = (stored ?? [home, ...DEFAULT_ZONES]).filter(isValidTimeZone); const setZones = (next: string[]) => { updateSetting('dashboard_timezones', next).catch(() => {}); }; diff --git a/client/src/components/PDF/TripPDF.test.ts b/client/src/components/PDF/TripPDF.test.ts index 1d2c4c5ce..5d010a344 100644 --- a/client/src/components/PDF/TripPDF.test.ts +++ b/client/src/components/PDF/TripPDF.test.ts @@ -397,6 +397,24 @@ describe('downloadTripPDF', () => { expect(iframe!.srcdoc).toContain('€') }) + // #2692: a place's description and notes print as the planner shows them, not as raw markdown. + it('FE-COMP-TRIPPDF-016c: renders markdown in a place description, sanitized', async () => { + const place = { ...placeWithDetails, description: '**Colosseum** tickets + +| Gate | Time | +| --- | --- | +| A | 9:00 | + +' } + const md = { ...richArgs, places: [place], assignments: { '10': [{ ...assignmentForDay, place }] } } + await downloadTripPDF(md as any) + const html = getIframe()!.srcdoc + expect(html).toContain('Colosseum') + expect(html).toContain('9:00') + expect(html).not.toContain('**Colosseum**') + expect(html).not.toContain('') + }) + it('FE-COMP-TRIPPDF-016b: formats price chip and totals in the trip currency, not EUR', async () => { const usdArgs = { ...richArgs, @@ -796,7 +814,7 @@ describe('downloadTripPDF remaining branches', () => { }])) const html = srcdoc() - expect(html).toContain('ICE 599 · Gl. 7 · Seat 21A · FRA → BER') + expect(html).toContain('ICE 599 · reservations.meta.platform 7 · reservations.meta.seat 21A · FRA → BER') }) it('FE-W5PDF-006: a multi-leg train renders one line per leg', async () => { @@ -811,7 +829,7 @@ describe('downloadTripPDF remaining branches', () => { }])) const html = srcdoc() - expect(html).toContain('IC 1 · Gl. 3 · BER → MUC') + expect(html).toContain('IC 1 · reservations.meta.platform 3 · BER → MUC') expect(html).toContain('EC 2 · MUC → ZRH') }) diff --git a/client/src/components/PDF/TripPDF.tsx b/client/src/components/PDF/TripPDF.tsx index a4691f793..6bbbe2805 100644 --- a/client/src/components/PDF/TripPDF.tsx +++ b/client/src/components/PDF/TripPDF.tsx @@ -24,6 +24,7 @@ import { fetchExchangeRates } from '../../hooks/useExchangeRates' import { getFlightLegs, getTrainLegs, usesStationRoute } from '../../utils/flightLegs' import { isServiceStopType } from '../Roadtrip/roadtripModel' import { onlyMyPlan } from './pdfScope' +import { createMarkdownHtml } from '../shared/SafeMarkdown' /** * Every day starts a new page by default. On a trip of short days that prints @@ -231,6 +232,10 @@ export async function downloadTripPDF({ trip, days, places, assignments: allStor let hasTransportNotes = false const loc = _locale || undefined const tr = _t || (k => k) + // A place's description and notes are markdown in the app, so the export renders + // them the same way instead of printing the raw syntax (#2692). + const markdown = createMarkdownHtml() + const mdBlock = (text: string) => `
${markdown.html(text)}
` // The store read is the fallback, not the source: a caller that forgets the // prop still prints the reader's own format instead of silently reverting. const is12h = (_timeFormat || useSettingsStore.getState().settings.time_format || '24h') === '12h' @@ -439,8 +444,8 @@ export async function downloadTripPDF({ trip, days, places, assignments: allStor const source = (usesStationRoute(r.type) ? getTrainLegs(r) : getFlightLegs(r))[l.index] subtitleLines = [[ l.airline, l.flight_number, l.train_number, - l.platform ? `Gl. ${l.platform}` : '', - l.seat ? `Seat ${l.seat}` : '', + l.platform ? `${tr('reservations.meta.platform')} ${l.platform}` : '', + l.seat ? `${tr('reservations.meta.seat')} ${l.seat}` : '', (l.from || l.to) ? [l.from, l.to].filter(Boolean).join(' → ') : '', source?.confirmation_number, ].filter(Boolean).join(' · ')].filter(Boolean) @@ -471,7 +476,7 @@ export async function downloadTripPDF({ trip, days, places, assignments: allStor // Multi-leg: one line per leg so every train number + segment route shows, // with the segment's own booking code where it has one (#1943). subtitleLines = legs.map(l => - [l.train_number, l.platform ? `Gl. ${l.platform}` : '', + [l.train_number, l.platform ? `${tr('reservations.meta.platform')} ${l.platform}` : '', (l.from || l.to) ? [l.from, l.to].filter(Boolean).join(' → ') : '', l.confirmation_number] .filter(Boolean).join(' · ')) @@ -479,7 +484,7 @@ export async function downloadTripPDF({ trip, days, places, assignments: allStor } else { const stops = (r.endpoints || []).slice().sort((a, b) => (a.sequence ?? 0) - (b.sequence ?? 0)).map(e => e.code || e.name) const route = stops.length >= 2 ? stops.join(' → ') : '' - subtitle = [meta.train_number, meta.platform ? `Gl. ${meta.platform}` : '', meta.seat ? `Seat ${meta.seat}` : '', route].filter(Boolean).join(' · ') + subtitle = [meta.train_number, meta.platform ? `${tr('reservations.meta.platform')} ${meta.platform}` : '', meta.seat ? `${tr('reservations.meta.seat')} ${meta.seat}` : '', route].filter(Boolean).join(' · ') } } else if (r.type === 'car') { @@ -587,10 +592,10 @@ export async function downloadTripPDF({ trip, days, places, assignments: allStor ${place.address ? `
${svgPin}${escHtml(place.address)}
` : ''} ${(place.lat != null && place.lng != null) ? `
${Number(place.lat).toFixed(5)}, ${Number(place.lng).toFixed(5)}
` : ''} - ${place.description ? `
${escHtml(place.description)}
` : ''} + ${place.description ? mdBlock(place.description) : ''} ${chips ? `
${chips}
` : ''} - ${place.notes ? `
${escHtml(place.notes)}
` : ''} - ${item.data.notes ? `
${escHtml(item.data.notes)}
` : ''} + ${place.notes ? mdBlock(place.notes) : ''} + ${item.data.notes ? mdBlock(item.data.notes) : ''} ` }).join('') @@ -836,7 +841,17 @@ export async function downloadTripPDF({ trip, days, places, assignments: allStor .info-spacer { width: 13px; flex-shrink: 0; } .info-text { font-size: 9px; color: #64748b; line-height: 1.5; } .info-text.muted { color: #94a3b8; } - .info-text.italic { font-style: italic; } + .info-text.md { min-width: 0; overflow-wrap: anywhere; } + .md > :first-child { margin-top: 0; } + .md > :last-child { margin-bottom: 0; } + .md p, .md ul, .md ol, .md table, .md blockquote, .md pre { margin: 0 0 4px; } + .md ul, .md ol { padding-left: 14px; } + .md h1, .md h2, .md h3, .md h4, .md h5, .md h6 { font-size: 10px; font-weight: 700; color: #475569; margin: 4px 0 2px; } + .md table { border-collapse: collapse; } + .md th, .md td { border: 1px solid #e2e8f0; padding: 2px 5px; text-align: left; } + .md code { font-family: ui-monospace, monospace; font-size: 8.5px; } + .md a { color: inherit; text-decoration: underline; } + .md blockquote { border-left: 2px solid #e2e8f0; padding-left: 6px; } .chips { display: flex; flex-wrap: wrap; gap: 4px; padding-left: 21px; margin-top: 4px; } .chip { display: inline-flex; align-items: center; gap: 3px; font-size: 8px; font-weight: 600; background: #f1f5f9; color: #374151; border-radius: 99px; padding: 2px 7px; white-space: nowrap; } @@ -930,6 +945,7 @@ ${tripMapHtml} ${daysHtml} ${pluginSectionsHtml} ` + markdown.dispose() // Open in modal with srcdoc iframe (no URL loading = no X-Frame-Options issue) const overlay = document.createElement('div') diff --git a/client/src/components/Planner/DayPlanSidebar.tsx b/client/src/components/Planner/DayPlanSidebar.tsx index 6db8e6636..77f15210a 100644 --- a/client/src/components/Planner/DayPlanSidebar.tsx +++ b/client/src/components/Planner/DayPlanSidebar.tsx @@ -43,6 +43,7 @@ import './dayPlanRows.css' import { TypeTile } from './bookings/bookingParts' import { typeInfo } from './bookings/bookingsModel' +import { transportSubtitle } from './transportDetailModel' import { dayHeadStays } from './dayHeadStays' import { getAccommodationAnchors, getDayBookendHotels, shouldDrawMorningLeg, shouldDrawEveningLeg, type CarrierEdge } from '../../utils/dayOrder' import { @@ -2166,24 +2167,8 @@ const DayPlanSidebar = React.memo(function DayPlanSidebar(props: DayPlanSidebarP let meta: any = {} try { meta = typeof res.metadata === 'string' ? JSON.parse(res.metadata || '{}') : (res.metadata || {}) } catch { meta = {} } - // Subtitle aus Metadaten zusammensetzen - let subtitle = '' - if (res.__leg) { - // One leg of a multi-leg flight/train — show this segment's own detail. - const parts = res.type === 'train' - ? [res.__leg.train_number, res.__leg.platform ? `${t('reservations.meta.platform')} ${res.__leg.platform}` : '', res.__leg.seat ? `${t('reservations.meta.seat')} ${res.__leg.seat}` : ''].filter(Boolean) - : [res.__leg.airline, res.__leg.flight_number].filter(Boolean) - if (res.__leg.from || res.__leg.to) - parts.push([res.__leg.from, res.__leg.to].filter(Boolean).join(' → ')) - subtitle = parts.join(', ') - } else if (res.type === 'flight') { - const parts = [meta.airline, meta.flight_number].filter(Boolean) - if (meta.departure_airport || meta.arrival_airport) - parts.push([meta.departure_airport, meta.arrival_airport].filter(Boolean).join(' → ')) - subtitle = parts.join(', ') - } else if (res.type === 'train') { - subtitle = [meta.train_number, meta.platform ? `${t('reservations.meta.platform')} ${meta.platform}` : '', meta.seat ? `${t('reservations.meta.seat')} ${meta.seat}` : ''].filter(Boolean).join(', ') - } + // A leg of a multi-leg flight or train shows its own detail (#2701). + const subtitle = transportSubtitle(res, t) ?? '' // A transit journey (#1065) renders its itinerary inline — // line badges in their colors instead of a plain subtitle, diff --git a/client/src/components/Planner/transportDetailModel.ts b/client/src/components/Planner/transportDetailModel.ts index 431962a0a..1442613c8 100644 --- a/client/src/components/Planner/transportDetailModel.ts +++ b/client/src/components/Planner/transportDetailModel.ts @@ -23,3 +23,65 @@ export function bookingDayLabel(date: string, locale: string): string { export function segmentCodeLabel(leg: { from?: string | null; to?: string | null }, t: Translate): string { return [leg.from, leg.to].filter(Boolean).join(' → ') || t('reservations.confirmationCode'); } + +/** The per-leg detail the day plan's leg rows carry (utils/dayMerge's `__leg`). */ +export interface TransportLegDetail { + index: number; + from?: string | null; + to?: string | null; + airline?: string | null; + flight_number?: string | null; + train_number?: string | null; + platform?: string | null; + seat?: string | null; +} + +/** + * The subtitle of a transport row in the day plan, desktop and phone alike. A + * leg of a multi-leg train or flight names its own train or flight, platform + * and seat (#2701); a whole booking reads them off its metadata. Null for the + * other transport types, which each view labels its own way. + */ +export function transportSubtitle( + res: { type: string; metadata?: unknown; __leg?: TransportLegDetail | null }, + t: Translate +): string | null { + const meta = parseMeta(res.metadata); + const leg = res.__leg; + const trainParts = (d: { train_number?: unknown; platform?: unknown; seat?: unknown }) => [ + str(d.train_number), + str(d.platform) ? `${t('reservations.meta.platform')} ${str(d.platform)}` : '', + str(d.seat) ? `${t('reservations.meta.seat')} ${str(d.seat)}` : '', + ]; + if (leg) { + const parts = res.type === 'train' ? trainParts(leg) : [str(leg.airline), str(leg.flight_number)]; + if (leg.from || leg.to) parts.push([leg.from, leg.to].filter(Boolean).join(' → ')); + return parts.filter(Boolean).join(', '); + } + if (res.type === 'flight') { + const parts = [str(meta.airline), str(meta.flight_number)]; + if (meta.departure_airport || meta.arrival_airport) { + parts.push([str(meta.departure_airport), str(meta.arrival_airport)].filter(Boolean).join(' → ')); + } + return parts.filter(Boolean).join(', '); + } + if (res.type === 'train') return trainParts(meta).filter(Boolean).join(', '); + return null; +} + +function str(value: unknown): string { + return typeof value === 'string' || typeof value === 'number' ? String(value) : ''; +} + +function parseMeta(metadata: unknown): Record { + let meta = metadata; + // An earlier bug could double-encode the metadata; reading it twice heals that. + for (let i = 0; i < 2 && typeof meta === 'string'; i++) { + try { + meta = JSON.parse(meta || '{}'); + } catch { + meta = {}; + } + } + return meta && typeof meta === 'object' ? (meta as Record) : {}; +} diff --git a/client/src/components/Plugins/PluginFrame.tsx b/client/src/components/Plugins/PluginFrame.tsx index cbd4968e6..21f514780 100644 --- a/client/src/components/Plugins/PluginFrame.tsx +++ b/client/src/components/Plugins/PluginFrame.tsx @@ -11,6 +11,7 @@ import ConfirmDialog from '../shared/ConfirmDialog' import { pluginsApi } from '../../api/client' import { addListener, removeListener } from '../../api/websocket' import { useIsPhone } from '../../mobile/useIsPhone' +import { browserTimeZone } from '../../utils/localDate' // The design-token contract handed to plugins (#4 richer context): non-secret CSS // values, resolved for the CURRENT theme, so a plugin can match TREK exactly (and @@ -379,7 +380,7 @@ export default function PluginFrame({ pluginId, tripId = null, placeId = null, d timeFormat: settings.time_format, distanceUnit: settings.distance_unit, temperatureUnit: settings.temperature_unit, - timezone: Intl.DateTimeFormat().resolvedOptions().timeZone, + timezone: browserTimeZone() ?? 'UTC', blurBookingCodes: Boolean(settings.blur_booking_codes), }, tokens: readThemeTokens(), diff --git a/client/src/components/shared/SafeMarkdown.test.tsx b/client/src/components/shared/SafeMarkdown.test.tsx new file mode 100644 index 000000000..70d1877a4 --- /dev/null +++ b/client/src/components/shared/SafeMarkdown.test.tsx @@ -0,0 +1,36 @@ +import { render, screen } from '@testing-library/react'; +import { describe, expect, it } from 'vitest'; + +import { SafeMarkdown, createMarkdownHtml } from './SafeMarkdown'; + +describe('SafeMarkdown (#2692)', () => { + it('FE-COMP-SAFEMD-001: renders GitHub markdown with kept line breaks and safe links', () => { + render({'# Title\nfirst\nsecond\n\n[site](https://example.com)'}); + expect(screen.getByRole('heading', { name: 'Title' })).toBeInTheDocument(); + expect(document.querySelector('br')).not.toBeNull(); + const link = screen.getByRole('link', { name: 'site' }); + expect(link).toHaveAttribute('target', '_blank'); + expect(link).toHaveAttribute('rel', 'noopener noreferrer nofollow'); + }); + + it('FE-COMP-SAFEMD-002: shows raw HTML as text and never as an element', () => { + render({'Room '}); + expect(document.querySelector('img')).toBeNull(); + expect(screen.getByText(/Room /)).toBeInTheDocument(); + }); +}); + +describe('createMarkdownHtml (#2692)', () => { + it('FE-COMP-SAFEMD-003: returns the sanitized HTML, the same for the same text', () => { + const markdown = createMarkdownHtml(); + try { + const html = markdown.html('**bold** and '); + expect(html).toContain('bold'); + expect(html).not.toContain('')).toBe(html); + expect(markdown.html('- a\n- b')).toContain('
  • a
  • '); + } finally { + markdown.dispose(); + } + }); +}); diff --git a/client/src/components/shared/SafeMarkdown.tsx b/client/src/components/shared/SafeMarkdown.tsx new file mode 100644 index 000000000..97ef2c1d8 --- /dev/null +++ b/client/src/components/shared/SafeMarkdown.tsx @@ -0,0 +1,47 @@ +import { flushSync } from 'react-dom'; +import { createRoot } from 'react-dom/client'; +import Markdown from 'react-markdown'; +import remarkBreaks from 'remark-breaks'; +import remarkGfm from 'remark-gfm'; +import { sanitizedMarkdownComponents, sanitizedMarkdownPlugins } from './markdownSanitize'; + +/** + * Text a user wrote in markdown (a place's description, its notes), rendered + * the way the planner shows it: GitHub flavour, line breaks kept, raw HTML + * shown as text, the rest sanitized, links in a new tab without an opener. + * Safe for pages strangers see, like a shared trip (#2692). + */ +export function SafeMarkdown({ children }: { children: string }) { + return ( + + {children} + + ); +} + +/** + * Turns markdown into the HTML {@link SafeMarkdown} renders, for output built as + * a string such as the PDF export (#2692). It renders through the same + * pipeline into a detached node, so the sanitizer is the one the app uses and + * no second markdown library is bundled. Call it outside a render and dispose + * of it when done; the same text is rendered once. + */ +export function createMarkdownHtml(): { html: (text: string) => string; dispose: () => void } { + const host = document.createElement('div'); + const root = createRoot(host); + const done = new Map(); + return { + html: (text) => { + const known = done.get(text); + if (known !== undefined) return known; + flushSync(() => root.render({text})); + done.set(text, host.innerHTML); + return host.innerHTML; + }, + dispose: () => root.unmount(), + }; +} diff --git a/client/src/mobile/screens/trip/plan/MPlanTimeline.tsx b/client/src/mobile/screens/trip/plan/MPlanTimeline.tsx index 1198396a4..3db3587c2 100644 --- a/client/src/mobile/screens/trip/plan/MPlanTimeline.tsx +++ b/client/src/mobile/screens/trip/plan/MPlanTimeline.tsx @@ -224,7 +224,7 @@ export default function MPlanTimeline({ planner, shell }: MPlanTimelineProps) { drag={dragFor(row)} onOpen={() => { if (editing) tl.editTransport(row.res) - else shell.openSheet('transport', { reservationId: row.res.id }) + else shell.openSheet('transport', { reservationId: row.res.id, legIndex: row.res.__leg?.index }) }} /> {dayScheduleFor('reservation', row.res.id)} diff --git a/client/src/mobile/screens/trip/plan/MPlanTimelineRows.tsx b/client/src/mobile/screens/trip/plan/MPlanTimelineRows.tsx index 2b0ea7819..2508bda41 100644 --- a/client/src/mobile/screens/trip/plan/MPlanTimelineRows.tsx +++ b/client/src/mobile/screens/trip/plan/MPlanTimelineRows.tsx @@ -265,7 +265,7 @@ export function TransportRow({ res, dayId, chrome, reorder, drag, onOpen }: { const time = start ? `${fmtTime(start, chrome)}${phase === 'single' && end ? ` – ${fmtTime(end, chrome)}` : ''}` : '' - const sub = transportSubtitle(res) + const sub = transportSubtitle(res, chrome.t) return (
    - if (res.__leg) { - const parts = [res.__leg.from, res.__leg.to].filter(Boolean).length - ? [[res.__leg.from, res.__leg.to].filter(Boolean).join(' → ')] - : [] - return parts.join(' · ') - } - if (res.type === 'flight') { - const parts = [meta.airline, meta.flight_number].filter(Boolean) as string[] - if (meta.departure_airport || meta.arrival_airport) { - parts.push([meta.departure_airport, meta.arrival_airport].filter(Boolean).join(' → ')) - } - return parts.join(' · ') - } - if (res.type === 'train') { - return [meta.train_number, meta.platform ? `Gl. ${meta.platform}` : '', meta.seat ? `Sitz ${meta.seat}` : ''] - .filter(Boolean).join(' · ') - } - return res.location || '' +export function transportSubtitle(res: TransportEntry, t: TranslationFn): string { + return dayPlanTransportSubtitle(res, t) ?? (res.location || '') } const sameCoord = (a: [number, number], b: [number, number]): boolean => diff --git a/client/src/mobile/screens/trip/sheets/MTransportSheet.tsx b/client/src/mobile/screens/trip/sheets/MTransportSheet.tsx index c01e23021..e329defac 100644 --- a/client/src/mobile/screens/trip/sheets/MTransportSheet.tsx +++ b/client/src/mobile/screens/trip/sheets/MTransportSheet.tsx @@ -6,7 +6,7 @@ import { useTranslation } from '../../../../i18n' import { useSettingsStore } from '../../../../store/settingsStore' import { RES_ICONS } from '../../../../components/Planner/DayPlanSidebar.constants' import { splitReservationDateTime } from '../../../../utils/formatters' -import { getFlightLegs, getTrainLegs, usesStationRoute } from '../../../../utils/flightLegs' +import { getFlightLegs, getTrainLegs, usesStationRoute, type FlightLeg, type TrainLeg } from '../../../../utils/flightLegs' import { openFile } from '../../../../utils/fileDownload' import { runsOnDay } from '../../../../utils/reservationRoutes' import { filesFor } from '../../../../utils/reservationFiles' @@ -19,6 +19,8 @@ import { Eyebrow, INNER_CLS, StatBox, TileHeader, displayTime } from './MTripShe interface TransportSheetPayload { reservationId?: number + /** The leg of a multi-leg train or flight the day plan row stood for (#2701). */ + legIndex?: number } interface TransitLeg { @@ -118,24 +120,37 @@ export default function MTransportSheet({ planner, shell }: MTripSheetsProps) { const to = (res.endpoints || []).find(e => e.role === 'to') const { date, time: startTime } = splitReservationDateTime(res.reservation_time) const { time: endTime } = splitReservationDateTime(res.reservation_end_time) - const depTime = from?.local_time || startTime - const arrTime = to?.local_time || endTime - - const subParts: string[] = [] - if (meta.airline) subParts.push(meta.airline) - if (meta.flight_number) subParts.push(meta.flight_number) - if (meta.train_number) subParts.push(meta.train_number) - if (from?.name && to?.name) subParts.push(`${from.name} → ${to.name}`) - else if (date) subParts.push(bookingDayLabel(date, locale)) - - const seat = meta.seat - const platform = meta.platform - const transitLegs: TransitLeg[] = Array.isArray(meta.transit?.legs) ? meta.transit.legs : [] + const bookingDepTime = from?.local_time || startTime + const bookingArrTime = to?.local_time || endTime // Per-segment booking codes (#1943), only on a real stopover booking: the // single-leg fallback would just echo the booking's own code shown below. - const routeLegs = res.type === 'flight' ? getFlightLegs(res) : usesStationRoute(res.type) ? getTrainLegs(res) : [] + const routeLegs: (FlightLeg | TrainLeg)[] = res.type === 'flight' ? getFlightLegs(res) : usesStationRoute(res.type) ? getTrainLegs(res) : [] const legCodes = routeLegs.length > 1 ? routeLegs.filter(l => l.confirmation_number) : [] + // Opened from one leg's row, the sheet shows that leg's own number, seat, + // platform and times rather than the first leg's (#2701). + const leg = routeLegs.length > 1 && payload.legIndex != null ? routeLegs[payload.legIndex] ?? null : null + const legDetail = (leg ?? {}) as Partial + const depTime = leg ? leg.dep_time || '' : bookingDepTime + const arrTime = leg ? leg.arr_time || '' : bookingArrTime + const depLabel = (leg ? leg.from : from?.name) || t('reservations.time') + const arrLabel = (leg ? leg.to : to?.name) || t('reservations.time') + + const subParts: string[] = [] + const airline = leg ? legDetail.airline : meta.airline + const flightNumber = leg ? legDetail.flight_number : meta.flight_number + const trainNumber = leg ? legDetail.train_number : meta.train_number + if (airline) subParts.push(airline) + if (flightNumber) subParts.push(flightNumber) + if (trainNumber) subParts.push(trainNumber) + if (leg && (leg.from || leg.to)) subParts.push([leg.from, leg.to].filter(Boolean).join(' → ')) + else if (from?.name && to?.name) subParts.push(`${from.name} → ${to.name}`) + else if (date) subParts.push(bookingDayLabel(date, locale)) + + // A flight's legs carry no seat or platform of their own, so those stay the booking's. + const seat = leg && res.type !== 'flight' ? legDetail.seat : meta.seat + const platform = leg && res.type !== 'flight' ? legDetail.platform : meta.platform + const transitLegs: TransitLeg[] = Array.isArray(meta.transit?.legs) ? meta.transit.legs : [] const resFiles = filesFor(res, planner.files || []) @@ -186,10 +201,10 @@ export default function MTransportSheet({ planner, shell }: MTripSheetsProps) { {(depTime || arrTime || seat || platform) && (
    {depTime && ( - + )} {arrTime && ( - + )} {platform && } {seat && } diff --git a/client/src/pages/JourneyPage.tsx b/client/src/pages/JourneyPage.tsx index 7c5bcd036..11c587a62 100644 --- a/client/src/pages/JourneyPage.tsx +++ b/client/src/pages/JourneyPage.tsx @@ -9,6 +9,7 @@ import { import type { Journey } from '../store/journeyStore' import { computeJourneyLifecycle } from '../utils/journeyLifecycle' import { useJourney } from './journey/useJourney' +import { journeyYearLabel } from './journey/journeyModel' import HelpAnchor from '../components/Help/HelpAnchor' import { DialogButton, DialogFooter, DialogHeader, DialogSection, DialogShell, DialogTile, FooterSpacer, NEUTRAL_TINT, fs } from '../components/shared/DialogShell' import { EditorField, INPUT } from '../components/shared/dialogParts' @@ -438,7 +439,7 @@ function JourneyCard({ journey, onClick }: { journey: Journey & { entry_count?: - {new Date(j.created_at).getFullYear()} + {journeyYearLabel(j)} {lifecycle !== 'live' && ( { await waitFor(() => expect(screen.getByText('Somewhere 1')).toBeInTheDocument()); expect(screen.queryByText('1 h')).toBeNull(); }); + + // #2692: the description and notes are markdown in the planner, so the shared page renders them too. + it('renders markdown in the description and notes, and keeps raw HTML as text', async () => { + const marked = { + 21: [{ + id: 304, day_id: 21, order_index: 0, notes: '**Bring** cash', + place: { + id: 504, name: 'Market', description: '## Opening + +| Day | Hours | +| --- | --- | +| Sat | 8 to 14 | + +', + address: 'Market Square 1', lat: null, lng: null, duration_minutes: 0, notes: '- fruit +- bread', + website: null, phone: null, category_id: null, price: null, place_time: null, end_time: null, + image_url: null, transport_mode: 'walking', category: null, tags: [], + }, + }], + }; + await open('markdown-token', payload({ days, assignments: marked })); + await waitFor(() => expect(screen.getByText('Market Square 1')).toBeInTheDocument()); + + expect(screen.getByRole('heading', { name: 'Opening' })).toBeInTheDocument(); + expect(screen.getByRole('cell', { name: '8 to 14' })).toBeInTheDocument(); + expect(screen.getByText('Bring').tagName).toBe('STRONG'); + expect(screen.getByText('fruit').tagName).toBe('LI'); + expect(document.querySelector('img[src="x"]')).toBeNull(); + expect(screen.queryByText('## Opening')).toBeNull(); + }); }); describe('FE-PAGE-SHARED-039: a booking shows its note and its link, and nothing that is not http(s) (#2320)', () => { diff --git a/client/src/pages/journey/journeyModel.test.ts b/client/src/pages/journey/journeyModel.test.ts new file mode 100644 index 000000000..e51f432d9 --- /dev/null +++ b/client/src/pages/journey/journeyModel.test.ts @@ -0,0 +1,26 @@ +import { describe, expect, it } from 'vitest'; + +import { journeyYearLabel } from './journeyModel'; + +describe('journeyYearLabel (#2685)', () => { + it('FE-PAGE-JOURNEY-YEAR-001: names the year of the trips, not the year the journey was written', () => { + expect( + journeyYearLabel({ trip_date_min: '2024-09-12', trip_date_max: '2024-09-20', created_at: '2026-03-01 10:00:00' }) + ).toBe('2024'); + }); + + it('FE-PAGE-JOURNEY-YEAR-002: a trip over New Year names both years', () => { + expect( + journeyYearLabel({ trip_date_min: '2024-12-28', trip_date_max: '2025-01-04', created_at: '2026-03-01 10:00:00' }) + ).toBe('2024/2025'); + }); + + it('FE-PAGE-JOURNEY-YEAR-003: one known date is enough, and without any it falls back to when it was written', () => { + expect( + journeyYearLabel({ trip_date_min: null, trip_date_max: '2023-05-02', created_at: '2026-03-01 10:00:00' }) + ).toBe('2023'); + expect(journeyYearLabel({ trip_date_min: null, trip_date_max: null, created_at: '2026-03-01 10:00:00' })).toBe( + '2026' + ); + }); +}); diff --git a/client/src/pages/journey/journeyModel.ts b/client/src/pages/journey/journeyModel.ts new file mode 100644 index 000000000..da2379dd8 --- /dev/null +++ b/client/src/pages/journey/journeyModel.ts @@ -0,0 +1,13 @@ +/** The year a journey card names: the years its trips cover, not the year it was written (#2685). */ +export function journeyYearLabel(journey: { + trip_date_min?: string | null; + trip_date_max?: string | null; + created_at: string; +}): string { + // The dates are calendar dates, so the year is read from the text, not through a Date in some zone. + const from = journey.trip_date_min?.slice(0, 4); + const to = journey.trip_date_max?.slice(0, 4); + if (from && to && to !== from) return `${from}/${to}`; + if (from || to) return (from || to) as string; + return String(new Date(journey.created_at).getFullYear()); +} diff --git a/client/src/pages/sharedTrip/SharedPlaceDetails.tsx b/client/src/pages/sharedTrip/SharedPlaceDetails.tsx index 34f7dfdca..dd2b77202 100644 --- a/client/src/pages/sharedTrip/SharedPlaceDetails.tsx +++ b/client/src/pages/sharedTrip/SharedPlaceDetails.tsx @@ -3,6 +3,7 @@ import { useTranslation } from '../../i18n' import { fs } from '../../components/shared/DialogShell' import { Tooltip } from '../../components/shared/Tooltip' import { WhiteBadge } from '../../components/Planner/planParts' +import { SafeMarkdown } from '../../components/shared/SafeMarkdown' import { getGoogleMapsUrlForPlace } from '../../components/Planner/placeGoogleMaps' import { formatDurationMinutes, isHttpUrl, plannedStayMinutes } from './sharedTripModel' @@ -61,7 +62,7 @@ export function SharedPlaceDetails({ place, assignmentNotes }: { place: SharedPl
    )} {place.description && ( -
    {place.description}
    +
    {place.description}
    )} {dayNote && } {placeNote && } @@ -98,7 +99,7 @@ function NoteLine({ label, text, strong = false }: { label: string; text: string
    - {text} +
    {text}
    ) diff --git a/client/src/store/assistantStore.ts b/client/src/store/assistantStore.ts index 9a9dfb8b8..2d5abcc8e 100644 --- a/client/src/store/assistantStore.ts +++ b/client/src/store/assistantStore.ts @@ -21,6 +21,7 @@ import { aiConnectionsRepo } from '../repo/aiConnectionsRepo'; import { assistantRepo } from '../repo/assistantRepo'; import { OnlineOnlyError } from '../repo/onlineOnly'; import type { Assignment } from '../types'; +import { browserTimeZone } from '../utils/localDate'; import { randomId } from '../utils/randomId'; import type { RouteProfileFocus } from '../utils/routeGeometry'; import { assistantScopeOf, assistantTargetOf, type AssistantChatKey } from './assistantChatKey'; @@ -331,7 +332,7 @@ function errorCodeOf(err: unknown): AssistantErrorCode { function clientContext() { return { locale: useSettingsStore.getState().settings.language || 'en', - timeZone: Intl.DateTimeFormat().resolvedOptions().timeZone || 'UTC', + timeZone: browserTimeZone() ?? 'UTC', }; } diff --git a/client/src/store/authStore.ts b/client/src/store/authStore.ts index ba43ded6b..297b14562 100644 --- a/client/src/store/authStore.ts +++ b/client/src/store/authStore.ts @@ -18,6 +18,7 @@ import { forgetServerLanguage } from './settingsStore' import { forgetResumeRoute } from '../utils/resumeRoute' import { markSignedOut, clearSignedOut } from '../utils/signedOut' import { forgetPushDeviceOnLogout, resyncPushSubscription } from '../push/webPush' +import { browserTimeZone } from '../utils/localDate' /** How long a logout waits for the queued changes to go out. */ const LOGOUT_FLUSH_MS = 5000 @@ -154,7 +155,7 @@ export const useAuthStore = create()( hasMapsKey: false, hasAmapKey: false, placesProvider: 'auto', - serverTimezone: Intl.DateTimeFormat().resolvedOptions().timeZone, + serverTimezone: browserTimeZone() ?? '', appRequireMfa: false, tripRemindersEnabled: false, placesPhotosEnabled: true, diff --git a/client/src/utils/localDate.test.ts b/client/src/utils/localDate.test.ts index 2078e5ec6..9995bff29 100644 --- a/client/src/utils/localDate.test.ts +++ b/client/src/utils/localDate.test.ts @@ -1,5 +1,5 @@ import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest' -import { isLocalToday, localIsoDate, localMinutes } from './localDate' +import { browserTimeZone, isLocalToday, isValidTimeZone, localIsoDate, localMinutes } from './localDate' /** * "Today" must be the user's local calendar date. `toISOString()` is the UTC @@ -66,3 +66,26 @@ describe('isLocalToday', () => { expect(isLocalToday(undefined)).toBe(false) }) }) + +describe('browserTimeZone and isValidTimeZone (#2694)', () => { + it('names the browser zone, and nothing when the browser names none', () => { + expect(browserTimeZone()).toBe(Intl.DateTimeFormat().resolvedOptions().timeZone) + const original = Intl.DateTimeFormat.prototype.resolvedOptions + const spy = vi.spyOn(Intl.DateTimeFormat.prototype, 'resolvedOptions').mockImplementation(function (this: Intl.DateTimeFormat) { + return { ...original.call(this), timeZone: undefined as unknown as string } + }) + try { + expect(browserTimeZone()).toBeUndefined() + } finally { + spy.mockRestore() + } + }) + + it('accepts the zones Intl knows and refuses the rest', () => { + expect(isValidTimeZone('Europe/Berlin')).toBe(true) + expect(isValidTimeZone('UTC')).toBe(true) + expect(isValidTimeZone('Mars/Olympus_Mons')).toBe(false) + expect(isValidTimeZone('')).toBe(false) + expect(isValidTimeZone(undefined)).toBe(false) + }) +}) diff --git a/client/src/utils/localDate.ts b/client/src/utils/localDate.ts index 834c65f4f..8e0356bf0 100644 --- a/client/src/utils/localDate.ts +++ b/client/src/utils/localDate.ts @@ -27,3 +27,24 @@ export function localMinutes(d: Date = new Date()): number { export function isLocalToday(date: string | null | undefined): boolean { return !!date && date.slice(0, 10) === localIsoDate() } + +/** + * The browser's IANA time zone, or undefined when it cannot name one. Chrome + * on Windows answers undefined for a system zone it cannot map, such as + * Alberta's permanent UTC-6 (#2694), so every reader picks its own fallback. + */ +export function browserTimeZone(): string | undefined { + const tz = Intl.DateTimeFormat().resolvedOptions().timeZone as string | undefined + return typeof tz === 'string' && tz ? tz : undefined +} + +/** Whether `Intl` accepts the zone; formatting with one it rejects throws a RangeError. */ +export function isValidTimeZone(tz: unknown): tz is string { + if (typeof tz !== 'string' || !tz) return false + try { + new Intl.DateTimeFormat(undefined, { timeZone: tz }) + return true + } catch { + return false + } +} diff --git a/client/tests/unit/mobile/trip/MPlanTimelineRows.test.tsx b/client/tests/unit/mobile/trip/MPlanTimelineRows.test.tsx index 11c371cef..59a29f770 100644 --- a/client/tests/unit/mobile/trip/MPlanTimelineRows.test.tsx +++ b/client/tests/unit/mobile/trip/MPlanTimelineRows.test.tsx @@ -234,7 +234,7 @@ describe('TransportRow', () => { } as unknown as TransportEntry render() - expect(screen.getByText('ICE 599 · Gl. 7 · Sitz 21A')).toBeInTheDocument() + expect(screen.getByText('ICE 599, reservations.meta.platform 7, reservations.meta.seat 21A')).toBeInTheDocument() }) it('FE-MOB-PLROW-018: an untimed booking of an unknown type still renders its title', () => { diff --git a/client/tests/unit/mobile/trip/MTransportSheet.test.tsx b/client/tests/unit/mobile/trip/MTransportSheet.test.tsx index ddc26aeab..84e8a5521 100644 --- a/client/tests/unit/mobile/trip/MTransportSheet.test.tsx +++ b/client/tests/unit/mobile/trip/MTransportSheet.test.tsx @@ -7,7 +7,7 @@ import { buildPlanner, buildShell } from '../../../helpers/mobileTrip' import { resetAllStores, seedStore } from '../../../helpers/store' import { fireEvent, render, screen } from '../../../helpers/render' -// FE-MOB-TRSH-001 to FE-MOB-TRSH-033 +// FE-MOB-TRSH-001 to FE-MOB-TRSH-035 vi.mock('../../../../src/utils/fileDownload', () => ({ openFile: vi.fn() })) @@ -442,4 +442,34 @@ describe('MTransportSheet', () => { expect(planner.handleSelectDay).toHaveBeenCalledWith(3, false) }) }) + + // #2701: a leg row opens the sheet on that leg, not on the booking's first one. + describe('opened from one leg of a multi-leg train', () => { + const TRAIN = { + ...FLIGHT, id: 8, type: 'train', title: 'Takayama to Kyoto', confirmation_number: null, + metadata: JSON.stringify({ + train_number: 'Hida 6', seat: '10-4C', + legs: [ + { from: 'Takayama', to: 'Nagoya', train_number: 'Hida 6', seat: '10-4C', platform: '1', dep_time: '09:40', arr_time: '12:10' }, + { from: 'Nagoya', to: 'Kyoto', train_number: 'Nozomi 67', seat: '4-5A', platform: '14', dep_time: '12:35', arr_time: '13:10' }, + ], + }), + } as unknown as Reservation + + it("FE-MOB-TRSH-034: shows the second leg's own train, seat, platform and times", () => { + render() + expect(screen.getByText(/Nozomi 67/)).toBeInTheDocument() + expect(screen.getByText('4-5A')).toBeInTheDocument() + expect(screen.getByText('14')).toBeInTheDocument() + expect(screen.getByText('12:35')).toBeInTheDocument() + expect(screen.getByText('13:10')).toBeInTheDocument() + expect(screen.queryByText('10-4C')).not.toBeInTheDocument() + }) + + it('FE-MOB-TRSH-035: without a leg the sheet still shows the booking as a whole', () => { + render() + expect(screen.getByText('10-4C')).toBeInTheDocument() + expect(screen.queryByText('4-5A')).not.toBeInTheDocument() + }) + }) }) diff --git a/client/tests/unit/mobile/trip/planTimelineModel.test.ts b/client/tests/unit/mobile/trip/planTimelineModel.test.ts index c0e2783d7..2c81e2eec 100644 --- a/client/tests/unit/mobile/trip/planTimelineModel.test.ts +++ b/client/tests/unit/mobile/trip/planTimelineModel.test.ts @@ -128,14 +128,17 @@ describe('planTimelineModel — metadata parsing', () => { }) describe('planTimelineModel — transportSubtitle', () => { + // The labels stay keys, so the assertions read what the subtitle puts where. + const tr: TranslationFn = (key) => key + it('FE-MOB-PTLM-006: renders a synthetic leg as from → to', () => { const res = { ...buildReservation({ type: 'flight' }), __leg: { index: 0, total: 2, from: 'FRA', to: 'IST' } } as TransportEntry - expect(transportSubtitle(res)).toBe('FRA → IST') + expect(transportSubtitle(res, tr)).toBe('FRA → IST') }) it('FE-MOB-PTLM-007: renders a leg without endpoints as an empty subtitle', () => { const res = { ...buildReservation({ type: 'flight' }), __leg: { index: 1, total: 2, from: null, to: null } } as TransportEntry - expect(transportSubtitle(res)).toBe('') + expect(transportSubtitle(res, tr)).toBe('') }) it('FE-MOB-PTLM-008: joins airline, flight number and airports for a flight', () => { @@ -143,25 +146,42 @@ describe('planTimelineModel — transportSubtitle', () => { type: 'flight', metadata: JSON.stringify({ airline: 'LH', flight_number: 'LH123', departure_airport: 'FRA', arrival_airport: 'HND' }), }) - expect(transportSubtitle(res)).toBe('LH · LH123 · FRA → HND') + expect(transportSubtitle(res, tr)).toBe('LH, LH123, FRA → HND') }) it('FE-MOB-PTLM-009: omits the airport pair when neither airport is known', () => { const res = buildReservation({ type: 'flight', metadata: JSON.stringify({ airline: 'LH', flight_number: 'LH123' }) }) - expect(transportSubtitle(res)).toBe('LH · LH123') + expect(transportSubtitle(res, tr)).toBe('LH, LH123') }) it('FE-MOB-PTLM-010: labels platform and seat for a train', () => { const full = buildReservation({ type: 'train', metadata: JSON.stringify({ train_number: 'ICE 599', platform: '7', seat: '32A' }), }) - expect(transportSubtitle(full)).toBe('ICE 599 · Gl. 7 · Sitz 32A') - expect(transportSubtitle(buildReservation({ type: 'train', metadata: '{"train_number":"ICE 599"}' }))).toBe('ICE 599') + expect(transportSubtitle(full, tr)).toBe('ICE 599, reservations.meta.platform 7, reservations.meta.seat 32A') + expect(transportSubtitle(buildReservation({ type: 'train', metadata: '{"train_number":"ICE 599"}' }), tr)).toBe('ICE 599') + }) + + // #2701: a leg names its own train, platform and seat, not the first leg's. + it('FE-MOB-PTLM-011b: a train leg carries its own number, platform and seat', () => { + const res = { + ...buildReservation({ type: 'train', metadata: JSON.stringify({ train_number: 'Hida 6', seat: '10-4C' }) }), + __leg: { index: 1, total: 2, from: 'Nagoya', to: 'Kyoto', train_number: 'Nozomi 67', platform: '14', seat: '4-5A' }, + } as TransportEntry + expect(transportSubtitle(res, tr)).toBe('Nozomi 67, reservations.meta.platform 14, reservations.meta.seat 4-5A, Nagoya → Kyoto') + }) + + it('FE-MOB-PTLM-011c: a flight leg carries its own airline and flight number', () => { + const res = { + ...buildReservation({ type: 'flight' }), + __leg: { index: 1, total: 2, from: 'IST', to: 'HND', airline: 'TK', flight_number: 'TK52' }, + } as TransportEntry + expect(transportSubtitle(res, tr)).toBe('TK, TK52, IST → HND') }) it('FE-MOB-PTLM-011: falls back to the location for any other type', () => { - expect(transportSubtitle(buildReservation({ type: 'bus', location: 'Central Station' }))).toBe('Central Station') - expect(transportSubtitle(buildReservation({ type: 'bus', location: null }))).toBe('') + expect(transportSubtitle(buildReservation({ type: 'bus', location: 'Central Station' }), tr)).toBe('Central Station') + expect(transportSubtitle(buildReservation({ type: 'bus', location: null }), tr)).toBe('') }) })