From a5de1bc52d71aec1813d11f93d1b225a787d0d2a Mon Sep 17 00:00:00 2001 From: Maurice Date: Sun, 22 Nov 2026 21:34:29 +0100 Subject: [PATCH] feat(pdf): redesign the trip PDF The trip PDF gets a new layout in the app's current look, with nothing it printed before left out and more of each place on the page. - Cover: the trip photo full bleed, title and dates over it, the trip's figures on frosted tiles. - Overview: the route map, every day at a glance (colour, date, plan, the night's stay, stops, cost) and all bookings and stays with their codes. - Days: the header in the day's map colour, a photo strip of the day's stops, where the night is spent, then the plan as a timeline with the times on the left. - Places: photo or category tile, category, duration, price, rating, tags, address, coordinates, description, notes, opening hours of that day, phone, website, e-mail and the members going. The rating, e-mail, hours and reservation note come from the trip's place, since the assignment only carries a projection of it. - Bookings: route first, then airline, number, seat or platform as badges, each leg with its own code, status and the booking's code. - A second row of switches in the preview: overview, photos, coordinates, and contact and hours, next to page per day, large text and transport notes. Each one is a class on the document and remembered. The document is split into modules for its helpers, icons, stylesheet, cover and overview, and the day, so the export itself only gathers the data. --- client/src/components/PDF/TripPDF.map.test.ts | 2 +- client/src/components/PDF/TripPDF.test.ts | 164 ++-- client/src/components/PDF/TripPDF.tsx | 893 +++++------------- client/src/components/PDF/pdfImages.test.ts | 16 +- client/src/components/PDF/pdfImages.ts | 29 +- client/src/components/PDF/pdfPreview.test.ts | 56 +- client/src/components/PDF/pdfPreview.ts | 66 +- client/src/components/PDF/tripPdfDay.test.ts | 261 +++++ client/src/components/PDF/tripPdfDay.ts | 427 +++++++++ client/src/components/PDF/tripPdfHtml.ts | 82 ++ client/src/components/PDF/tripPdfIcons.ts | 165 ++++ client/src/components/PDF/tripPdfOverview.ts | 119 +++ client/src/components/PDF/tripPdfStyles.ts | 381 ++++++++ shared/src/i18n/ar/pdf.ts | 8 + shared/src/i18n/az/pdf.ts | 8 + shared/src/i18n/br/pdf.ts | 8 + shared/src/i18n/ca/pdf.ts | 8 + shared/src/i18n/cs/pdf.ts | 8 + shared/src/i18n/de/pdf.ts | 8 + shared/src/i18n/en/pdf.ts | 8 + shared/src/i18n/es/pdf.ts | 8 + shared/src/i18n/et/pdf.ts | 8 + shared/src/i18n/fr/pdf.ts | 8 + shared/src/i18n/gr/pdf.ts | 8 + shared/src/i18n/he/pdf.ts | 8 + shared/src/i18n/hu/pdf.ts | 8 + shared/src/i18n/id/pdf.ts | 8 + shared/src/i18n/it/pdf.ts | 8 + shared/src/i18n/ja/pdf.ts | 8 + shared/src/i18n/ko/pdf.ts | 8 + shared/src/i18n/nl/pdf.ts | 8 + shared/src/i18n/pl/pdf.ts | 8 + shared/src/i18n/ru/pdf.ts | 8 + shared/src/i18n/sk/pdf.ts | 8 + shared/src/i18n/sv/pdf.ts | 8 + shared/src/i18n/th/pdf.ts | 8 + shared/src/i18n/tr/pdf.ts | 8 + shared/src/i18n/uk/pdf.ts | 8 + shared/src/i18n/vi/pdf.ts | 8 + shared/src/i18n/zh-TW/pdf.ts | 8 + shared/src/i18n/zh/pdf.ts | 8 + 41 files changed, 2117 insertions(+), 768 deletions(-) create mode 100644 client/src/components/PDF/tripPdfDay.test.ts create mode 100644 client/src/components/PDF/tripPdfDay.ts create mode 100644 client/src/components/PDF/tripPdfHtml.ts create mode 100644 client/src/components/PDF/tripPdfIcons.ts create mode 100644 client/src/components/PDF/tripPdfOverview.ts create mode 100644 client/src/components/PDF/tripPdfStyles.ts diff --git a/client/src/components/PDF/TripPDF.map.test.ts b/client/src/components/PDF/TripPDF.map.test.ts index 45713930d..5f1e0311e 100644 --- a/client/src/components/PDF/TripPDF.map.test.ts +++ b/client/src/components/PDF/TripPDF.map.test.ts @@ -245,7 +245,7 @@ describe('trip route map in the PDF', () => { expect(html).toContain(' el?.textContent?.trim() ?? '' + +/** + * Each booking on the days' timelines, read the way it prints: the span label over the + * title, the start and end in the time column, one line per leg (its route, then its + * facts, then its own code, as one string) and the codes of the whole booking. + */ +function bookingsOf(html: string) { + const doc = new DOMParser().parseFromString(html, 'text/html') + return [...doc.querySelectorAll('.timeline .tl-booking')].map(item => ({ + kicker: textOf(item.querySelector('.note-kicker')), + title: textOf(item.querySelector('.note-text')), + start: textOf(item.querySelector('.tl-start')), + end: textOf(item.querySelector('.tl-end')), + lines: [...item.querySelectorAll('.note-line')].map(line => + [...line.children].map(part => textOf(part)).filter(Boolean).join(' · ')), + codes: [...item.querySelectorAll('.note-extra .code-chip')].map(code => textOf(code)), + })) +} + +/** Every line printed under the bookings' titles, across the days. */ +const bookingLines = (html: string) => bookingsOf(html).flatMap(b => b.lines) + +/** The booking of that title and span label, as bookingsOf reads it. */ +function bookingCard(html: string, title: string, kicker = '') { + const card = bookingsOf(html).find(b => b.title === title && b.kicker === kicker) + if (!card) throw new Error(`no booking "${title}" labelled "${kicker}"`) + return card +} + // ── Setup ───────────────────────────────────────────────────────────────────── beforeEach(() => { @@ -175,8 +210,8 @@ describe('downloadTripPDF', () => { expect(srcdoc).toContain('') expect(srcdoc).toContain('') - // The dark bar (background/padding/flex) lives in an inner wrapper inside the thead. - expect(srcdoc).toContain('class="day-header-bar"') + // The header (number, date, title, figures) lives in an inner wrapper inside the thead. + expect(srcdoc).toContain('
') // Day content still renders inside the new structure. expect(srcdoc).toContain('Rome Day') expect(srcdoc).toContain('Colosseum') @@ -188,10 +223,10 @@ describe('downloadTripPDF', () => { const srcdoc = iframe!.srcdoc // The thead is repeated on every overflow page, so the spacing below the header bar // must be declared on its cell... - expect(srcdoc).toContain('.day-header > tr > td { padding-bottom: 12px; }') + expect(srcdoc).toContain('.day-header > tr > td { padding: 0 var(--gutter) 5mm; }') // ...and not as a block-start padding on .day-body, which the print engine only paints // on the first fragment of the (fragmented) body cell. - expect(srcdoc).toContain('.day-body { padding: 0 28px 6px; }') + expect(srcdoc).toContain('.day-body { padding: 0 var(--gutter) 4mm; }') }) it('FE-COMP-TRIPPDF-006: escHtml prevents XSS in trip title', async () => { @@ -255,8 +290,8 @@ describe('downloadTripPDF', () => { const iframe = getIframe() expect(iframe!.srcdoc).toContain('Flight to Rome') expect(iframe!.srcdoc).toContain('ABC123') - // Single-leg flight keeps its full-route subtitle. - expect(iframe!.srcdoc).toContain('Air Italia · AI123 · CDG → FCO') + // Single-leg flight keeps its full route, then airline and number as badges. + expect(bookingLines(iframe!.srcdoc)).toContain('CDG → FCO · Air Italia · AI123') }) it('FE-COMP-TRIPPDF-013s: a flight prints its seat, a direct one and each leg of one with a stop alike', async () => { @@ -272,10 +307,10 @@ describe('downloadTripPDF', () => { }), } await downloadTripPDF({ ...richArgs, reservations: [direct, stopover] }) - const html = getIframe()?.srcdoc ?? '' - expect(html).toContain('Air Italia · AI123 · reservations.meta.seat 31A · CDG → FCO') - expect(html).toContain('Lufthansa · LH2 · reservations.meta.seat 14C · BER → HND') - expect(html).not.toContain('LH1 · reservations.meta.seat') + const lines = bookingLines(getIframe()?.srcdoc ?? '') + expect(lines).toContain('CDG → FCO · Air Italia · AI123 · reservations.meta.seat 31A') + expect(lines).toContain('BER → HND · Lufthansa · LH2 · reservations.meta.seat 14C') + expect(lines).toContain('FRA → BER · Lufthansa · LH1') }) it('FE-COMP-TRIPPDF-013f: the stop a booked night wrote is not listed, so a morning flight prints before the hotel (#2434)', async () => { @@ -329,15 +364,14 @@ describe('downloadTripPDF', () => { const iframe = getIframe() // Without the landing time the reader cannot tell what is left of the day. - expect(iframe!.srcdoc).toContain('14:30 – 16:45') + expect(bookingCard(iframe!.srcdoc, 'Flight to Rome')).toMatchObject({ start: '14:30', end: '16:45' }) }) it('FE-COMP-TRIPPDF-013d: a flight without a landing time still shows its departure', async () => { await downloadTripPDF(richArgs) const iframe = getIframe() - expect(iframe!.srcdoc).toContain('14:30') - expect(iframe!.srcdoc).not.toContain('14:30 –') + expect(bookingCard(iframe!.srcdoc, 'Flight to Rome')).toMatchObject({ start: '14:30', end: '' }) }) it('FE-COMP-TRIPPDF-013e: an overnight flight keeps its arrival on the arrival day (#1310)', async () => { @@ -351,16 +385,16 @@ describe('downloadTripPDF', () => { }) const iframe = getIframe() - expect(iframe!.srcdoc).not.toContain('14:30 – 06:15') - expect(iframe!.srcdoc).toContain('06:15') + const html = iframe!.srcdoc + expect(bookingCard(html, 'Flight to Rome', 'reservations.span.departure')).toMatchObject({ start: '14:30', end: '' }) + expect(bookingCard(html, 'Flight to Rome', 'reservations.span.arrival')).toMatchObject({ start: '06:15' }) }) it('FE-COMP-TRIPPDF-013b: renders every flight number for a multi-leg flight', async () => { await downloadTripPDF({ ...richArgs, reservations: [multiLegFlight] }) const iframe = getIframe() - // One subtitle line per leg, each with its own flight number and segment route. - expect(iframe!.srcdoc).toContain('Lufthansa · LH1 · FRA → BER') - expect(iframe!.srcdoc).toContain('Lufthansa · LH2 · BER → HND') + // One line per leg, each with its own flight number and segment route. + expect(bookingLines(iframe!.srcdoc)).toEqual(['FRA → BER · Lufthansa · LH1', 'BER → HND · Lufthansa · LH2']) }) it('FE-COMP-TRIPPDF-014: renders cover image when trip has cover_image', async () => { @@ -760,11 +794,9 @@ describe('downloadTripPDF remaining branches', () => { }])) const html = srcdoc() - expect(html).toContain('reservations.span.start: Nordic Cruise') - expect(html).toContain('reservations.span.ongoing: Nordic Cruise') - expect(html).toContain('reservations.span.end: Nordic Cruise') - expect(html).toContain('09:00') - expect(html).toContain('18:00') + expect(bookingCard(html, 'Nordic Cruise', 'reservations.span.start').start).toBe('09:00') + expect(bookingCard(html, 'Nordic Cruise', 'reservations.span.ongoing').start).toBe('') + expect(bookingCard(html, 'Nordic Cruise', 'reservations.span.end').start).toBe('18:00') }) it('FE-W5PDF-002: a multi-day flight uses departure/arrival wording', async () => { @@ -775,8 +807,8 @@ describe('downloadTripPDF remaining branches', () => { }])) const html = srcdoc() - expect(html).toContain('reservations.span.departure: Red Eye') - expect(html).toContain('reservations.span.arrival: Red Eye') + expect(bookingCard(html, 'Red Eye', 'reservations.span.departure').start).toBe('23:00') + expect(bookingCard(html, 'Red Eye', 'reservations.span.arrival').start).toBe('06:00') }) it('FE-W5PDF-003: a multi-day car hire is labelled pickup/return and skips the middle day', async () => { @@ -786,8 +818,10 @@ describe('downloadTripPDF remaining branches', () => { }])) const html = srcdoc() - expect(html).toContain('reservations.span.pickup: Rental') - expect(html).toContain('reservations.span.return: Rental') + expect(bookingsOf(html).map(b => [b.kicker, b.title])).toEqual([ + ['reservations.span.pickup', 'Rental'], + ['reservations.span.return', 'Rental'], + ]) expect(html).not.toContain('reservations.span.active') }) @@ -798,8 +832,10 @@ describe('downloadTripPDF remaining branches', () => { }])) const html = srcdoc() - expect(html).toContain('reservations.span.dropOff: Airport Parking') - expect(html).toContain('reservations.span.pickup: Airport Parking') + expect(bookingsOf(html).map(b => [b.kicker, b.title])).toEqual([ + ['reservations.span.dropOff', 'Airport Parking'], + ['reservations.span.pickup', 'Airport Parking'], + ]) expect(html).not.toContain('reservations.span.ongoing') // Day B holds nothing else, so it prints the empty-day hint rather than the booking. expect(html).toContain('dayplan.emptyDay') @@ -828,7 +864,7 @@ describe('downloadTripPDF remaining branches', () => { }])) const html = srcdoc() - expect(html).toContain('ICE 599 · reservations.meta.platform 7 · reservations.meta.seat 21A · FRA → BER') + expect(bookingLines(html)).toEqual(['FRA → BER · ICE 599 · reservations.meta.platform 7 · reservations.meta.seat 21A']) }) it('FE-W5PDF-006: a multi-leg train renders one line per leg', async () => { @@ -843,8 +879,7 @@ describe('downloadTripPDF remaining branches', () => { }])) const html = srcdoc() - expect(html).toContain('IC 1 · reservations.meta.platform 3 · BER → MUC') - expect(html).toContain('EC 2 · MUC → ZRH') + expect(bookingLines(html)).toEqual(['BER → MUC · IC 1 · reservations.meta.platform 3', 'MUC → ZRH · EC 2']) }) it('FE-W5PDF-007: restaurant, event, tour and unknown types get their own subtitles', async () => { @@ -856,7 +891,8 @@ describe('downloadTripPDF remaining branches', () => { ])) const html = srcdoc() - expect(html).toContain('4 guests') + // The party size needs no word: it prints beside the people icon. + expect(bookingCard(html, 'Dinner').lines).toEqual(['4']) expect(html).toContain('Arena') expect(html).toContain('GuideCo') expect(html).toContain('Mystery') @@ -889,8 +925,7 @@ describe('downloadTripPDF remaining branches', () => { }])) const html = srcdoc() - expect(html).toContain('AirX · X1') - expect(html).toContain('AirX · X2 · AAA → BBB') + expect(bookingLines(html)).toEqual(['AirX · X1', 'AAA → BBB · AirX · X2']) }) it('FE-W5PDF-030: a stopover flight prints the booking code of each segment that has one (#1943)', async () => { @@ -905,11 +940,12 @@ describe('downloadTripPDF remaining branches', () => { }])) const html = srcdoc() - expect(html).toContain('LH · LH1 · FRA → BER · ABC123') + // Each leg is its own card, the way the day plan shows it, with its own line. + const legs = bookingsOf(html).filter(b => b.title === 'Layover') + expect(legs.map(leg => leg.lines)).toEqual([['FRA → BER · LH · LH1 · ABC123'], ['BER → HND · ANA · NH2']]) // A segment without one keeps the line it had before, and the booking's own - // reference still prints once for the whole card. - expect(html).toContain('ANA · NH2 · BER → HND') - expect(html).toContain('Code: BOOK1') + // reference still prints on its card. + expect(legs[0].codes).toEqual(['BOOK1']) }) it('FE-W5PDF-010: a single-leg flight with waypoints joins the whole route', async () => { @@ -919,7 +955,7 @@ describe('downloadTripPDF remaining branches', () => { metadata: { airline: 'LH', flight_number: 'LH7' }, }])) - expect(srcdoc()).toContain('LH · LH7 · FRA → Berlin → HND') + expect(bookingLines(srcdoc())).toEqual(['FRA → Berlin → HND · LH · LH7']) }) it('FE-W5PDF-011: an assignment without a place contributes nothing', async () => { @@ -1003,9 +1039,11 @@ describe('downloadTripPDF remaining branches', () => { await downloadTripPDF(spanArgs([])) const html = srcdoc() - expect(html.indexOf('Earlier Inn')).toBeLessThan(html.indexOf('Later Inn')) + const days = daysOf(html) + expect(days.indexOf('Earlier Inn')).toBeGreaterThan(-1) + expect(days.indexOf('Earlier Inn')).toBeLessThan(days.indexOf('Later Inn')) // the shared days list two hotels, so they lose the single-column class - expect(html).toContain('class="day-accommodations "') + expect(html).toContain('class="day-accommodations"') }) it('FE-W5PDF-017: a trip without dated days prints no date range and no day dates', async () => { @@ -1018,7 +1056,7 @@ describe('downloadTripPDF remaining branches', () => { expect(html).not.toContain('class="cover-dates"') expect(html).not.toContain('class="day-date"') - expect(html).toContain('class="cover-circle-ph"') + expect(html).toContain('
') }) it('FE-W5PDF-018: the print button asks the preview frame to print', async () => { @@ -1045,7 +1083,7 @@ describe('downloadTripPDF remaining branches', () => { trip: { id: 1, title: 'Cover Trip', description: null, cover_image: '/uploads/cover.svg' } as any, }) expect(srcdoc()).not.toContain('/uploads/cover.svg') - expect(srcdoc()).toContain('class="cover-circle-ph"') + expect(srcdoc()).toContain('
') }) it('FE-W5PDF-020: plugin sections render their paragraphs and tables', async () => { @@ -1081,7 +1119,7 @@ describe('downloadTripPDF defaults', () => { // no translator, no days, no places, no notes expect(html).toContain('pdf.travelPlan') - expect(html).toContain('
My Trip
') + expect(html).toContain('

My Trip

') expect(html).toContain('
0
') }) @@ -1146,11 +1184,9 @@ describe('downloadTripPDF defaults', () => { reservations: [{ id: 1, title: 'Overnight Bus', type: 'bus', day_id: 1, end_day_id: 2, reservation_time: '22:00', reservation_end_time: null }] as any[], }) const html = srcdoc() - const endSection = html.slice(html.indexOf('End Day')) - expect(html).toContain('reservations.span.start: Overnight Bus') - expect(endSection).toContain('reservations.span.end: Overnight Bus') - expect(endSection).not.toContain('22:00') + expect(bookingCard(html, 'Overnight Bus', 'reservations.span.start').start).toBe('22:00') + expect(bookingCard(html, 'Overnight Bus', 'reservations.span.end')).toMatchObject({ start: '', end: '' }) }) it('FE-W5PDF-027: an export without a locale still renders, with lang="en"', async () => { @@ -1217,12 +1253,16 @@ describe('page breaks between days (#1292)', () => { expect(toggle()!.style.background).toContain('--border-primary') }) - it('FE-PDF-BREAK-003: the first day never carries a break of its own', async () => { + // The first day opens the plan after the cover and the overview, so it always starts a + // sheet; the switch decides only whether the days after it do. + it('FE-PDF-BREAK-003: the first day never carries the switchable break', async () => { await downloadTripPDF(twoDays) const html = getIframe()!.srcdoc - expect(html.indexOf('')).toBeGreaterThan(-1) + expect(html.indexOf('
{ @@ -1305,8 +1345,8 @@ describe('a printed day follows the plan (#1978)', () => { const d2 = { id: 22, day_number: 2, title: 'Day Two', date: '2025-06-02' } as any const srcdoc = () => getIframe()!.srcdoc - /** Where each needle first appears, so order can be asserted without parsing. */ - const positions = (html: string, needles: string[]) => needles.map(n => html.indexOf(n)) + /** Where each needle first appears in the days, so order can be asserted without parsing. */ + const positions = (html: string, needles: string[]) => needles.map(n => daysOf(html).indexOf(n)) it('orders the day by the clock, not by the order the API sent rows in', async () => { await downloadTripPDF({ @@ -1390,7 +1430,7 @@ describe('a printed day follows the plan (#1978)', () => { dayId: 21, }).map(item => (item.type === 'place' ? item.data.place.name : item.data.title)) - const seen = expected.map(name => html.indexOf(name)) + const seen = expected.map(name => daysOf(html).indexOf(name)) for (const at of seen) expect(at).toBeGreaterThan(-1) expect(seen).toEqual([...seen].sort((a, b) => a - b)) }) @@ -1473,18 +1513,20 @@ describe('downloadTripPDF — large text', () => { expect(html).not.toContain('pdf-large-text"') expect(largeToggle().getAttribute('aria-checked')).toBe('false') // One scale and one set of greys, at today's values unless the class is on. - expect(html).toContain('--pdf-text: 1;') + expect(html).toContain('--t: 1;') expect(html).toContain('body.pdf-large-text {') - expect(html).toContain('.place-name { font-size: calc(11.5px * var(--pdf-text));') - expect(html).toContain('.note-text { font-size: calc(9.5px * var(--pdf-text)); color: var(--pdf-ink);') + expect(html).toContain('.place-name { flex: 1; font-size: calc(12px * var(--t));') + expect(html).toContain('.note-text { font-size: calc(9.5px * var(--t)); color: var(--ink);') }) it('FE-PDF-LARGE-002: the clock and the booking code of a transport scale with the rest', async () => { await downloadTripPDF(richArgs) const html = previewFrame().srcdoc - expect(html).toContain('') - expect(html).toContain('
Code: ABC123
') + // The clock sits in the time column and the code in its chip, both on the scale. + expect(bookingCard(html, 'Flight to Rome')).toMatchObject({ start: '14:30', codes: ['ABC123'] }) + expect(html).toContain('.tl-start { display: block; font-size: calc(9.5px * var(--t));') + expect(html).toContain('font-family: var(--num); font-size: calc(8px * var(--t)); font-weight: 600; letter-spacing: 0.04em;') expect(html).not.toContain('font-size:10px;') }) @@ -1549,14 +1591,14 @@ describe('downloadTripPDF — photos at thumbnail size', () => { await downloadTripPDF(withImage('/uploads/colosseum.jpg')) const html = previewFrame().srcdoc - expect(html).toContain(``) + expect(html).toContain(``) expect(html).not.toContain('colosseum.jpg') }) it('FE-PDF-THUMB-002: a photo from another origin keeps its URL', async () => { await downloadTripPDF(withImage('https://images.example.com/colosseum.jpg')) - expect(previewFrame().srcdoc).toContain('') + expect(previewFrame().srcdoc).toContain('') }) it('FE-PDF-THUMB-003: a closed export dialog stops the photos and opens nothing', async () => { diff --git a/client/src/components/PDF/TripPDF.tsx b/client/src/components/PDF/TripPDF.tsx index ede3ec289..cc101a813 100644 --- a/client/src/components/PDF/TripPDF.tsx +++ b/client/src/components/PDF/TripPDF.tsx @@ -1,129 +1,39 @@ // Trip PDF via browser print window -import { createElement } from 'react' -import { getCategoryIcon } from '../shared/categoryIcons' -import { FileText, Info, Clock, MapPin, Navigation, Train, Plane, Bus, Car, Ship, Sailboat, CableCar, Bike, CarTaxiFront, Route, Coffee, Ticket, Star, Heart, Camera, Flag, Lightbulb, AlertTriangle, ShoppingBag, Bookmark, Hotel, LogIn, LogOut, KeyRound, BedDouble, Utensils, Users, ParkingSquare, LucideIcon } from 'lucide-react' import { mapsApi, pluginsApi } from '../../api/client' import { accommodationRepo } from '../../repo/accommodationRepo' -import type { Trip, Day, Place, Category, AssignmentsMap, DayNote, DistanceUnit, BudgetItem } from '../../types' +import type { Trip, Day, Place, Category, AssignmentsMap, Assignment, DayNote, DistanceUnit, BudgetItem, Accommodation } from '../../types' import { isDayInAccommodationRange, getDayOrder } from '../../utils/dayOrder' import { hidesOnMiddleDay, getTransportForDay, getMergedItems, getSpanPhase, getDisplayTimeForDay } from '../../utils/dayMerge' -import { safeHexColor } from '../../utils/safeColor' import { pdfSwitchOn } from '../../utils/pdfSwitch' -import { openPdfPreview, LARGE_TEXT_KEY, PAGE_BREAK_KEY, TRANSPORT_NOTES_KEY } from './pdfPreview' -import { renderIconMarkup } from '../../utils/iconMarkup' -import { formatMoney, formatMoneySum, formatClockTime, splitReservationDateTime, type MoneyEntry } from '../../utils/formatters' +import { openPdfPreview, LARGE_TEXT_KEY, PAGE_BREAK_KEY, TRANSPORT_NOTES_KEY, PHOTOS_KEY, OVERVIEW_KEY, COORDINATES_KEY, DETAILS_KEY } from './pdfPreview' +import { formatMoneySum, formatClockTime, splitReservationDateTime, type MoneyEntry } from '../../utils/formatters' import { useSettingsStore } from '../../store/settingsStore' import { useTripStore } from '../../store/tripStore' import { tripAddonEnabledNow } from '../../store/tripAddonsStore' import { projectDayItinerary } from '../Map/dayTourProjection' +import { dayRouteColor } from '../Map/tripRouteGeometry' import { planCosts } from '../Planner/planCosts' import { routeDistanceLabel } from '../Map/tripRouteLabels' import { drawTripRoute, type TripPdfRouteOptions } from './tripPdfRoute' import { fetchExchangeRates } from '../../hooks/useExchangeRates' -import { getFlightLegs, getTrainLegs, usesStationRoute } from '../../utils/flightLegs' import { onlyMyPlan, planAssignments } from './pdfScope' -import { createPdfMarkdown, PDF_MARKDOWN_CSS } from './pdfMarkdown' -import { shrinkPdfImages } from './pdfImages' +import { createPdfMarkdown } from './pdfMarkdown' +import { STRIP_PX, shrinkPdfImages } from './pdfImages' +import { absUrl, escHtml, hexColour, longDateRange, safeImg, shortDate } from './tripPdfHtml' +import { bookingIcon, bookingTint, glyph } from './tripPdfIcons' +import { bookingItem, bookingLinesHtml, dayHeader, noteItem, photoStrip, placeItem, staysBlock, type PdfBooking, type PdfDayContext } from './tripPdfDay' +import { coverHtml, glanceHtml, ledgerHtml, type CoverStat, type GlanceRow, type LedgerRow } from './tripPdfOverview' +import { tripPdfCss } from './tripPdfStyles' -function renderLucideIcon(icon:LucideIcon, props = {}) { - return renderIconMarkup( - createElement(icon, props) - ); -} +/** A day's colour when the route gave it none: the same palette entry the map would use. */ +const dayColourOf = (day: Day): string => hexColour(dayRouteColor(day).line, '#17171c') -const NOTE_ICON_MAP = { FileText, Info, Clock, MapPin, Navigation, Train, Plane, Bus, Car, Ship, Coffee, Ticket, Star, Heart, Camera, Flag, Lightbulb, AlertTriangle, ShoppingBag, Bookmark } -function noteIconSvg(iconId) { - const Icon = NOTE_ICON_MAP[iconId] || FileText - return renderLucideIcon(Icon, { size: 14, strokeWidth: 1.8, color: '#94a3b8' }) -} - -const RESERVATION_ICON_MAP = { flight: Plane, train: Train, bus: Bus, car: Car, taxi: CarTaxiFront, bicycle: Bike, cruise: Ship, ferry: Sailboat, cable_car: CableCar, transport_other: Route, restaurant: Utensils, event: Ticket, tour: Users, parking: ParkingSquare, other: FileText } -const RESERVATION_COLOR_MAP = { flight: '#3b82f6', train: '#06b6d4', bus: '#059669', car: '#6b7280', taxi: '#ca8a04', bicycle: '#84cc16', cruise: '#0ea5e9', ferry: '#0d9488', cable_car: '#dc2626', transport_other: '#6b7280', restaurant: '#ef4444', event: '#f59e0b', tour: '#10b981', parking: '#2563eb', other: '#6b7280' } -function reservationIconSvg(type) { - const Icon = RESERVATION_ICON_MAP[type] || Ticket - const color = RESERVATION_COLOR_MAP[type] || '#3b82f6' - return renderLucideIcon(Icon, { size: 14, strokeWidth: 1.8, color }) -} - -const ACCOMMODATION_ICON_MAP = { accommodation: Hotel, checkin: LogIn, checkout: LogOut, location: MapPin, note: FileText, confirmation: KeyRound } -function accommodationIconSvg(type) { - const Icon = ACCOMMODATION_ICON_MAP[type] || BedDouble - return renderLucideIcon(Icon, { size: 14, strokeWidth: 1.8, color: '#03398f', className: 'accommodation-icon' }) -} - -// ── SVG inline icons (for chips) ───────────────────────────────────────────── -const svgPin = `` -const svgClock = `` -const svgClock2= `` -const svgCheck = `` -const svgMoney = `` - -function escHtml(str) { - if (!str) return '' - return String(str).replace(/&/g, '&').replace(//g, '>').replace(/"/g, '"') -} - -// The style attribute is decoded back into raw quotes before the CSS is parsed, so -// escHtml alone cannot stop a cover_image from closing the url() and appending its own -// declaration. Percent-encoding is transparent to the fetch. -function cssUrl(url) { - return String(url).replace(/["'()\\\s]/g, c => '%' + c.codePointAt(0).toString(16).padStart(2, '0')) -} - -// The day colours come from a fixed palette, but this is a style attribute being built -// by string concatenation — the same place cssUrl exists for. Anything that is not a -// plain hex triple is not a colour, and gets the route blue instead of a chance to -// close the declaration. -function hexColour(value) { - return /^#[0-9a-f]{6}$/i.test(String(value)) ? String(value) : '#0a84ff' -} - -function absUrl(url) { - if (!url) return null - if (url.startsWith('http://') || url.startsWith('https://') || url.startsWith('data:')) return url - return window.location.origin + (url.startsWith('/') ? '' : '/') + url -} - -function safeImg(url) { - if (!url) return null - if (url.startsWith('https://') || url.startsWith('http://')) return url - // The in-app place-photo proxy always streams a JPEG but has no file extension - // (it ends in …/bytes), so the extension check below would wrongly reject it — - // which is why persisted place photos showed as category icons in the PDF. - if (url.startsWith('/api/maps/place-photo/')) return absUrl(url) - // gif is in the list because place-image-upload.ts accepts it; without it an - // uploaded GIF hero silently fell back to the category icon in the PDF. - return /\.(jpe?g|png|gif|webp|bmp|tiff?)(\?.*)?$/i.test(url) ? absUrl(url) : null -} - -// A place card's picture: direct > google photo > fallback icon (null). Both go -// through safeImg so the proxy path is resolved to an absolute URL the PDF can load. +// A place card's picture: direct > google photo > none. Both go through safeImg so +// the proxy path is resolved to an absolute URL the PDF can load. function placeImage(place: { id: number; image_url?: string | null }, photoMap: Record): string | null { return safeImg(place.image_url) || safeImg(photoMap[place.id]) } -// Generate SVG string from Lucide icon name (for category thumbnails) -function categoryIconSvg(iconName, color = '#6366f1', size = 24) { - const Icon = getCategoryIcon(iconName) - return renderIconMarkup( - createElement(Icon, { size, strokeWidth: 1.8, color: 'rgba(255,255,255,0.92)' }) - ) -} - -function shortDate(d, locale) { - if (!d) return '' - return new Date(d + 'T00:00:00Z').toLocaleDateString(locale, { weekday: 'short', day: 'numeric', month: 'short', timeZone: 'UTC' }) -} - -function longDateRange(days, locale) { - const dd = [...days].filter(d => d.date).sort((a, b) => a.day_number - b.day_number) - if (!dd.length) return null - const f = new Date(dd[0].date + 'T00:00:00Z') - const l = new Date(dd[dd.length - 1].date + 'T00:00:00Z') - return `${f.toLocaleDateString(locale, { day: 'numeric', month: 'long', timeZone: 'UTC' })} – ${l.toLocaleDateString(locale, { day: 'numeric', month: 'long', year: 'numeric', timeZone: 'UTC' })}` -} - - // Pre-fetch place photos for all assigned places. // Assignment places are a server-side projection that drops osm_id, so we recover // the full place from the trip's places pool and key the photo off the same id the @@ -131,7 +41,6 @@ function longDateRange(days, locale) { // places fell back to category icons in the PDF even though they show photos in-app. async function fetchPlacePhotos(assignments: AssignmentsMap, places: Place[]) { const photoMap: Record = {} - // The assignment projection drops osm_id, so recover it from the full places pool. const osmById = new Map((places || []).map(p => [p.id, p.osm_id])) const allPlaces = Object.values(assignments).flatMap(a => a.map(x => x.place)).filter(Boolean) const unique = [...new Map(allPlaces.map(p => [p.id, p])).values()] @@ -192,6 +101,17 @@ interface downloadTripPDFProps { signal?: AbortSignal } +/** The stays a day touches, in the order their nights began. */ +function staysForDay(day: Day, days: Day[], stays: Accommodation[]): Accommodation[] { + return stays + .filter(a => isDayInAccommodationRange(day, a.start_day_id, a.end_day_id, days)) + .sort((a, b) => { + const startA = days.find(d => d.id === a.start_day_id) + const startB = days.find(d => d.id === b.start_day_id) + return (startA ? getDayOrder(startA, days) : 0) - (startB ? getDayOrder(startB, days) : 0) + }) +} + // `assignments` is normalised here once, to the plan's own list; every read below // (and fetchPlacePhotos) relies on it being an object. export async function downloadTripPDF({ trip, days, places, assignments: allStored = {}, categories, dayNotes, reservations: allReservations = [], t: _t, locale: _locale, timeFormat: _timeFormat, distanceUnit: _distanceUnit, showServiceStops = true, budgetItems, costsEnabled, toursEnabled: toursOn, onlyUserId, route, signal }: downloadTripPDFProps) { @@ -199,19 +119,25 @@ export async function downloadTripPDF({ trip, days, places, assignments: allStor ? onlyMyPlan(allStored, allReservations, onlyUserId) : { assignments: allStored, reservations: allReservations } const assignments = planAssignments(stored, showServiceStops) - const breaksPerDay = pdfSwitchOn(PAGE_BREAK_KEY) - const showTransportNotes = pdfSwitchOn(TRANSPORT_NOTES_KEY) - const largeText = pdfSwitchOn(LARGE_TEXT_KEY, false) + const switches = { + breaksPerDay: pdfSwitchOn(PAGE_BREAK_KEY), + showTransportNotes: pdfSwitchOn(TRANSPORT_NOTES_KEY), + largeText: pdfSwitchOn(LARGE_TEXT_KEY, false), + photos: pdfSwitchOn(PHOTOS_KEY), + overview: pdfSwitchOn(OVERVIEW_KEY), + coordinates: pdfSwitchOn(COORDINATES_KEY), + details: pdfSwitchOn(DETAILS_KEY), + } // Set while the days render: the switch only shows when there is a note to hide. - let hasTransportNotes = false + const flags = { transportNote: false } const loc = _locale || undefined - const tr = _t || (k => k) + const tr = _t || ((k: string) => k) const markdown = createPdfMarkdown() // 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' const fmtTime = (v?: string | null) => formatClockTime(v, is12h) - const sorted = [...(days || [])].sort((a, b) => a.day_number - b.day_number) + const sorted = [...(days || [])].sort((a, b) => (a.day_number ?? 0) - (b.day_number ?? 0)) const range = longDateRange(sorted, loc) const coverImg = safeImg(trip?.cover_image) //retrieve accommodations for the trip to display on the day sections and prefetch their photos if needed @@ -219,7 +145,7 @@ export async function downloadTripPDF({ trip, days, places, assignments: allStor // The endpoint answers `{ accommodations: [...] }`, not a bare array. Unwrapped once // here so every reader below gets the list itself — passing the envelope on is what // cost the route map its hotel legs, and silently (#1736). - const accommodationList = Array.isArray(accommodations?.accommodations) ? accommodations.accommodations : [] + const accommodationList: Accommodation[] = Array.isArray(accommodations?.accommodations) ? accommodations.accommodations : [] // Sections contributed by pdfSectionProvider plugins — server-normalized plain // text (counts + lengths capped), appended after the days. Fail-safe: an error @@ -246,9 +172,10 @@ export async function downloadTripPDF({ trip, days, places, assignments: allStor const totalDistanceLabel = tripRoute && tripRoute.totalDistance > 0 ? routeDistanceLabel(tripRoute.totalDistance, unroutedLegs, unit, tr) : null + const routedDays = new Map((tripRoute?.days || []).map(d => [d.dayNumber, d])) // Each day named and coloured exactly as the legend on the planner map, so the two // read as the same picture. Days that routed to nothing are already out of `days`. - const tripMapHtml = tripMapSvg ? ` + const tripMapHtml = tripMapSvg && tripRoute ? `
${escHtml(tr('pdf.mapTitle'))} @@ -258,26 +185,24 @@ export async function downloadTripPDF({ trip, days, places, assignments: allStor ${tripMapSvg}
${tripRoute.days.filter(d => d.lines.length).map(d => ` - - ${escHtml(d.title || tr('dayplan.dayN', { n: d.dayNumber }))} + + ${escHtml(d.title || tr('dayplan.dayN', { n: d.dayNumber }))} ${escHtml(routeDistanceLabel(d.distance, d.unroutedLegs ?? 0, unit, tr))} `).join('')}
${escHtml(tr('pdf.mapCredit'))}
` : '' - // Pre-fetch place photos (Google, OSM and coords-only places) const photoMap = await fetchPlacePhotos(assignments, places) - // Each card's picture at thumbnail size, so the saved PDF does not carry every - // photo at full resolution (#1501). A picture missing here prints from its URL. - const thumbs = await shrinkPdfImages( - Object.values(assignments).flatMap(list => list.flatMap(a => { - const url = a.place && placeImage(a.place, photoMap) - return url ? [url] : [] - })), - signal, - ).catch(() => new Map()) + const photoUrls = Object.values(assignments).flatMap(list => list.flatMap(a => { + const url = a.place && placeImage(a.place, photoMap) + return url ? [url] : [] + })) + // Each card's picture at its printed size, so the saved PDF does not carry every + // photo at full resolution (#1501); the strip that opens a day gets a larger copy of + // its first three. A picture missing here prints from its URL. + const thumbs = await shrinkPdfImages(photoUrls, signal).catch(() => new Map()) const totalAssigned = new Set( Object.values(assignments).flatMap(a => a.map(x => x.place?.id)).filter(Boolean) @@ -308,300 +233,161 @@ export async function downloadTripPDF({ trip, days, places, assignments: allStor // pre-fetched rates, or listed per-currency when rates are unavailable (#1561). const dayCost = (dayId: number) => formatMoneySum(costs.byDay.get(dayId) || [], tripCur, loc || 'en', fxRates) - /* - * The span label is the only PDF-specific piece left here. Everything else - * about how a day is ordered — which transports belong to it, what time each - * one shows, where it sits among the places — comes from utils/dayMerge, the - * same functions the day plan itself uses (#1978). - * - * There used to be a second implementation in this file. It ordered by - * `day_plan_position`, which is one global number per booking, seeded from - * whichever day happened to render first; on any other day of a span it - * pointed at the wrong slot, and when it was still null the export fell back - * to the order the API returned. That is why the PDF was right some of the - * time and swapped two bookings the rest of it. - */ - const pdfGetSpanLabel = (r: any, phase: string): string | null => { - if (phase === 'single') return null - if (r.type === 'flight') return tr(`reservations.span.${phase === 'start' ? 'departure' : phase === 'end' ? 'arrival' : 'inTransit'}`) - if (r.type === 'car') return tr(`reservations.span.${phase === 'start' ? 'pickup' : phase === 'end' ? 'return' : 'active'}`) - // Parking reuses span.pickup for its end day: you drop the car off and collect it - // again later, so the rental car's wording carries over without a second key. - if (r.type === 'parking') return tr(`reservations.span.${phase === 'start' ? 'dropOff' : phase === 'end' ? 'pickup' : 'ongoing'}`) - return tr(`reservations.span.${phase === 'start' ? 'start' : phase === 'end' ? 'end' : 'ongoing'}`) + const ctx: PdfDayContext = { + tr, + fmtTime, + locale: loc, + tripCurrency: tripCur, + categories, + placesById: new Map((places || []).map(p => [p.id, p])), + photoOf: place => { + const url = placeImage(place, photoMap) + return url ? thumbs.get(url) ?? url : null + }, + markdown: text => markdown.row(text), } - // Build day HTML - const daysHtml = sorted.map((day, di) => { + + /* + * Everything about how a day is ordered — which transports belong to it, what time + * each one shows, where it sits among the places — comes from utils/dayMerge, the + * same functions the day plan itself uses (#1978), so the page and the print cannot + * disagree about what order a day is in. + */ + const planOf = (day: Day) => { // What the plan lists (planAssignments): the stop a booked night wrote sat at the // head of its day, so the hotel printed above a morning flight (#2434). - const assigned = (assignments[String(day.id)] || []) + const assigned: Assignment[] = (assignments[String(day.id)] || []) .slice() .sort((a, b) => (a.order_index ?? 0) - (b.order_index ?? 0)) const notes = (dayNotes || []).filter(n => n.day_id === day.id).slice() - .sort((a: any, b: any) => (a.sort_order ?? 0) - (b.sort_order ?? 0)) - const cost = dayCost(day.id) - - // Assembled exactly the way DayPlanSidebar assembles it, so the page and the - // print cannot disagree about what order a day is in. + .sort((a, b) => (a.sort_order ?? 0) - (b.sort_order ?? 0)) const dayTransports = getTransportForDay({ reservations: reservations || [], dayId: day.id, - dayAssignmentIds: assigned.map((a: any) => a.id), + dayAssignmentIds: assigned.map(a => a.id), days: sorted, }) + // Hotels come out in the stays block, a rental car's middle days appear only in + // the sidebar header, and a multi-day parking's middle days nowhere at all. + const merged = getMergedItems({ dayAssignments: assigned, dayNotes: notes, dayTransports, dayId: day.id }) + .filter(item => { + if (item.type !== 'transport') return true + const r = item.data + if (r.type === 'car' && getSpanPhase(r, day.id) === 'middle') return false + return !hidesOnMiddleDay(r, day.id) + }) + return { assigned, merged } + } + const plans = new Map(sorted.map(day => [day.id, planOf(day)])) - // Hotels come out in the accommodations block, a rental car's middle days - // appear only in the sidebar header, and a multi-day parking's middle days - // nowhere at all. - const merged = getMergedItems({ - dayAssignments: assigned, - dayNotes: notes, - dayTransports, - dayId: day.id, - }).filter(item => { - if (item.type !== 'transport') return true - const r: any = item.data - if (r.type === 'car' && getSpanPhase(r, day.id) === 'middle') return false - return !hidesOnMiddleDay(r, day.id) + // The first three photographed stops of each day, larger, for the strip that opens it. + const stripPhotos = new Map(sorted.map(day => { + const seen = new Set() + const photos = (plans.get(day.id)?.assigned || []).flatMap(a => { + const url = a.place && placeImage(a.place, photoMap) + if (!url || seen.has(url)) return [] + seen.add(url) + return [{ url, caption: a.place.name }] }) + return [day.id, photos.slice(0, 3)] + })) + const stripCopies = await shrinkPdfImages([...stripPhotos.values()].flat().map(p => p.url), signal, STRIP_PX) + .catch(() => new Map()) - let pi = 0 + const daysHtml = sorted.map((day, di) => { + const { assigned, merged } = plans.get(day.id) || { assigned: [], merged: [] } + let number = 0 const itemsHtml = merged.length === 0 ? `
${escHtml(tr('dayplan.emptyDay'))}
` - : merged.map(item => { - if (item.type === 'transport') { - const r = item.data - const meta = typeof r.metadata === 'string' ? JSON.parse(r.metadata || '{}') : (r.metadata || {}) - const icon = reservationIconSvg(r.type) - const color = RESERVATION_COLOR_MAP[r.type] || '#3b82f6' - let subtitle = '' - // Flights render one subtitle line per leg (see below); everything else is a single line. - let subtitleLines: string[] = [] - /* - * A multi-leg booking arrives as one item per leg now, the way the - * day plan shows it, because the shared merge expands legs so each - * one can sit at its own time among the day's places. Previously - * the export printed a single row with every leg as a subtitle - * line, which put the second leg's departure next to the first - * leg's clock. - */ - if (r.__leg) { - const l = r.__leg - // The segment's own booking code, which the leg object does not - // carry — read back from the booking by index. At the gate that is - // the code the airline asks for (#1943), so losing it here would - // have been a real regression for a stopover flight. - const source = (usesStationRoute(r.type) ? getTrainLegs(r) : getFlightLegs(r))[l.index] - subtitleLines = [[ - l.airline, l.flight_number, l.train_number, - 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) - } - else if (r.type === 'flight') { - const legs = getFlightLegs(r) - if (legs.length > 1) { - // Multi-leg: one line per leg so every flight number + segment route is - // shown, with the segment's own booking code where it has one (#1943). - // At the gate that is the number the airline asks for. - subtitleLines = legs.map(l => - [l.airline, l.flight_number, - (l.from || l.to) ? [l.from, l.to].filter(Boolean).join(' → ') : '', - l.confirmation_number] - .filter(Boolean).join(' · ')) - .filter(Boolean) - } else { - // Single-leg: full route over all waypoints (FRA → BER → HND), falling back to the - // flat metadata pair for legacy single-leg flights without endpoints. - 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(' → ') : (meta.departure_airport && meta.arrival_airport ? `${meta.departure_airport} → ${meta.arrival_airport}` : '') - subtitle = [meta.airline, meta.flight_number, meta.seat ? `${tr('reservations.meta.seat')} ${meta.seat}` : '', route].filter(Boolean).join(' · ') - } - } - else if (r.type === 'train') { - const legs = getTrainLegs(r) - if (legs.length > 1) { - // 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 ? `${tr('reservations.meta.platform')} ${l.platform}` : '', - (l.from || l.to) ? [l.from, l.to].filter(Boolean).join(' → ') : '', - l.confirmation_number] - .filter(Boolean).join(' · ')) - .filter(Boolean) - } 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 ? `${tr('reservations.meta.platform')} ${meta.platform}` : '', meta.seat ? `${tr('reservations.meta.seat')} ${meta.seat}` : '', route].filter(Boolean).join(' · ') - } - } - else if (r.type === 'car') { - // A rental with stops is a drive, and the printout is what people take - // into the car (#1797). Without this the route reads as pick-up and return - // with everything in between missing. - // - // Consecutive repeats collapse, and a chain that names one place only is - // dropped: the ordinary rental is picked up and returned at the same desk, - // which satisfies "two endpoints" and would otherwise print the counter's - // name twice with an arrow between. A genuine round trip keeps both ends, - // because Dresden sits between them. - const stops = (r.endpoints || []).slice() - .sort((a, b) => (a.sequence ?? 0) - (b.sequence ?? 0)) - .map(e => e.name) - .filter((name, i, all) => name && name !== all[i - 1]) - subtitle = new Set(stops).size >= 2 ? stops.join(' → ') : '' - } - else if (r.type === 'restaurant') subtitle = [meta.party_size ? `${meta.party_size} guests` : ''].filter(Boolean).join(' · ') - else if (r.type === 'event') subtitle = [meta.venue].filter(Boolean).join(' · ') - else if (r.type === 'tour') subtitle = [meta.operator].filter(Boolean).join(' · ') - if (subtitleLines.length === 0 && subtitle) subtitleLines = [subtitle] - const locationLine = r.location || meta.location || '' - const phase = getSpanPhase(r, day.id) - const spanLabel = pdfGetSpanLabel(r, phase) - const displayTime = getDisplayTimeForDay(r, day.id) - // Start and end, the way the day plan draws it (#1310). Without the - // landing time a flight reads as an open-ended block and the reader - // cannot tell how much of the day is left for anything else. - // - // Only on a transport that begins and ends on this day: across a - // span the arrival belongs to the arrival day, which already shows - // it as its own time, and repeating it here would put tomorrow's - // clock next to today's departure. - const startTime = fmtTime(splitReservationDateTime(displayTime).time) - const endTime = phase === 'single' ? fmtTime(splitReservationDateTime(r.reservation_end_time).time) : '' - const time = [startTime, endTime].filter(Boolean).join(' – ') - const titleHtml = `${spanLabel ? escHtml(spanLabel) + ': ' : ''}${escHtml(r.title)}` - const transportNote = typeof r.notes === 'string' ? r.notes.trim() : '' - if (transportNote) hasTransportNotes = true - return ` -
-
- ${icon} -
-
${titleHtml}${time ? ` ${time}` : ''}
- ${subtitleLines.filter(Boolean).map(s => `
${escHtml(s)}
`).join('')} - ${locationLine ? `
${escHtml(locationLine)}
` : ''} - ${r.confirmation_number ? `
Code: ${escHtml(r.confirmation_number)}
` : ''} - ${transportNote ? `
${escHtml(transportNote)}
` : ''} -
-
` - } - - if (item.type === 'note') { - const note = item.data - // A coloured note carries its colour into print the same way a - // reservation does (#1629) — the rule and the spine, not a fill, - // because a tint costs ink and reads as grey on a mono printer. - const noteColor = note.color || '' - return ` -
-
- ${noteIconSvg(note.icon)} -
-
${escHtml(note.text)}
- ${note.time ? `
${escHtml(note.time)}
` : ''} -
-
` - } - - pi++ - const place = item.data.place - if (!place) return '' - const cat = categories.find(c => c.id === place.category_id) - const color = safeHexColor(cat?.color, '#6366f1') - - const img = placeImage(place, photoMap) - const iconSvg = categoryIconSvg(cat?.icon, color, 24) - const thumbHtml = img - ? `` - : `
- ${iconSvg} -
` - - const chips = [ - place.place_time ? `${svgClock}${escHtml(fmtTime(place.place_time))}` : '', - place.price && Number.parseFloat(place.price) > 0 ? `${svgMoney}${formatMoney(Number(place.price), place.currency || trip.currency, loc)}` : '', - ].filter(Boolean).join('') - - return ` -
-
- ${thumbHtml} -
-
- ${pi} - ${escHtml(place.name)} - ${cat ? `${escHtml(cat.name)}` : ''} -
- ${place.address ? `
${svgPin}${escHtml(place.address)}
` : ''} - ${(place.lat != null && place.lng != null) ? `
${Number(place.lat).toFixed(5)}, ${Number(place.lng).toFixed(5)}
` : ''} - ${place.description ? markdown.row(place.description) : ''} - ${chips ? `
${chips}
` : ''} - ${place.notes ? markdown.row(place.notes) : ''} - ${item.data.notes ? markdown.row(item.data.notes) : ''} -
-
` - }).join('') - - const accommodationsForDay = accommodationList.filter(a => - day ? isDayInAccommodationRange(day, a.start_day_id, a.end_day_id, days) : false - ).sort((a, b) => { - const startA = days.find(d => d.id === a.start_day_id) - const startB = days.find(d => d.id === b.start_day_id) - return (startA ? getDayOrder(startA, days) : 0) - (startB ? getDayOrder(startB, days) : 0) - }) - - const accommodationDetails = accommodationsForDay.map(item => { - const isCheckIn = day.id === item.start_day_id - const isCheckOut = day.id === item.end_day_id - const actionLabel = isCheckIn ? tr('reservations.meta.checkIn') - : isCheckOut ? tr('reservations.meta.checkOut') - : tr('reservations.meta.linkAccommodation') - const actionIcon = isCheckIn ? accommodationIconSvg('checkin') - : isCheckOut ? accommodationIconSvg('checkout') - : accommodationIconSvg('accommodation') - const timeStr = isCheckIn ? fmtTime(item.check_in) - : isCheckOut ? fmtTime(item.check_out) - : '' - - return ` -
-
${actionIcon} ${escHtml(actionLabel)}
- ${timeStr ? `
${accommodationIconSvg('checkin')} ${escHtml(timeStr)}
` : ''} -
${accommodationIconSvg('accommodation')} ${escHtml(item.place_name)}
- ${item.place_address ? `
${accommodationIconSvg('location')} ${escHtml(item.place_address)}
` : ''} - ${item.notes ? `
${accommodationIconSvg('note')} ${escHtml(item.notes)}
` : ''} - ${isCheckIn && item.confirmation ? `
${accommodationIconSvg('confirmation')} ${escHtml(item.confirmation)}
` : ''} -
` - }).join('') - - const accommodationsHtml = accommodationsForDay.length > 0 - ? `
-
${accommodationDetails}
-
` - : '' + : `
    ${merged.map(item => { + if (item.type === 'transport') return bookingItem(item.data as PdfBooking, day, ctx, flags) + if (item.type === 'note') return noteItem(item.data as DayNote) + const a = item.data as Assignment + if (!a.place) return '' + number++ + return placeItem(a, number, day, ctx) + }).join('')}
` + const routed = routedDays.get(day.day_number ?? -1) + const header = dayHeader(day, { + stops: assigned.filter(a => a.place).length, + distance: routed && routed.distance > 0 ? routeDistanceLabel(routed.distance, routed.unroutedLegs ?? 0, unit, tr) : null, + cost: dayCost(day.id) || null, + }, ctx) + const strip = photoStrip((stripPhotos.get(day.id) || []).map(p => ({ ...p, url: stripCopies.get(p.url) ?? p.url }))) + const intro = day.notes && day.notes.trim() ? `
${escHtml(day.notes.trim())}
` : '' + const stays = staysBlock(staysForDay(day, days, accommodationList), day, ctx) // A real
so the browser repeats the day header at the top of // every page an overflowing day spills onto (#1471). CSS `table-header-group` // on a
is NOT repeated by Chromium's print engine — only real thead is. return ` -
- +
-
- ${escHtml(tr('dayplan.dayN', { n: day.day_number })).toUpperCase()} - ${escHtml(day.title || tr('dayplan.dayN', { n: day.day_number }))} - ${day.date ? `${shortDate(day.date, loc)}` : ''} - ${cost ? `${cost}` : ''} -
-
+
${header}
-
${accommodationsHtml}${itemsHtml}
+
${strip}${intro}${stays}${itemsHtml}
` }).join('') + // The overview's day rows and booking list, in day order. + const dayNumberOf = new Map(sorted.map(d => [d.id, d])) + const glanceRows: GlanceRow[] = sorted.map(day => { + const assigned = plans.get(day.id)?.assigned || [] + const nightStays = staysForDay(day, days, accommodationList).filter(a => a.end_day_id !== day.id) + return { + number: day.day_number ?? 0, + colour: dayColourOf(day), + date: day.date ? shortDate(day.date, loc) : '', + title: day.title || tr('dayplan.dayN', { n: day.day_number ?? 0 }), + stops: assigned.filter(a => a.place).length, + stay: nightStays.map(a => a.place_name || a.reservation_title || '').filter(Boolean).join(', '), + cost: dayCost(day.id) || null, + } + }) + const orderOf = (dayId: number | null | undefined) => { + const d = dayId != null ? dayNumberOf.get(dayId) : undefined + return d ? getDayOrder(d, sorted) : Number.MAX_SAFE_INTEGER + } + const ledgerRows: (LedgerRow & { order: number; minute: string })[] = [ + ...accommodationList.map(stay => { + const from = dayNumberOf.get(stay.start_day_id) + const to = dayNumberOf.get(stay.end_day_id) + return { + order: orderOf(stay.start_day_id), + minute: '', + icon: glyph('bed', 13), + tint: '#17171c', + title: stay.place_name || stay.reservation_title || '', + sub: escHtml(stay.place_address || ''), + when: [from?.date ? shortDate(from.date, loc) : '', to?.date ? shortDate(to.date, loc) : ''].filter(Boolean).join(' – '), + code: stay.confirmation || null, + } + }), + ...(reservations || []) + .filter(r => r.type !== 'hotel' && r.day_id != null && dayNumberOf.has(r.day_id)) + .map((r: PdfBooking) => { + const day = dayNumberOf.get(r.day_id ?? -1) + const time = fmtTime(splitReservationDateTime(day ? getDisplayTimeForDay(r, day.id) : null).time) + return { + order: orderOf(r.day_id), + minute: time, + icon: bookingIcon(r.type, 13), + tint: hexColour(bookingTint(r.type), '#6b6b75'), + title: r.title || '', + sub: bookingLinesHtml(r, tr), + when: [day?.date ? shortDate(day.date, loc) : '', time].filter(Boolean).join(' '), + code: r.confirmation_number || null, + } + }), + ].sort((a, b) => a.order - b.order || a.minute.localeCompare(b.minute)) + + const overviewHtml = `
+ ${hasInvalidTour ? `

${escHtml(tr('tours.dayRoute.endpointUnknown'))}

` : ''} + ${tripMapHtml} + ${glanceHtml(glanceRows, tr)} + ${ledgerHtml(ledgerRows, tr)} +
` + // Plugin sections after the days — every value is host-vetted plain text and // still escHtml'd here (same treatment as the core content above). const pluginSectionsHtml = pluginSections.length === 0 ? '' : ` @@ -618,298 +404,61 @@ export async function downloadTripPDF({ trip, days, places, assignments: allStor
`).join('')} ` + const stats: CoverStat[] = [ + { value: String(sorted.length), label: tr('dashboard.days', { count: sorted.length }) }, + { value: String(places?.length || 0), label: tr('dashboard.places', { count: places?.length || 0 }) }, + { value: String(totalAssigned), label: tr('pdf.planned') }, + ...(totalDistanceLabel ? [{ value: totalDistanceLabel, label: tr('pdf.distanceLabel') }] : []), + ...(totalCostLabel ? [{ value: totalCostLabel, label: tr('pdf.costLabel') }] : []), + ] + const html = ` ${escHtml(trip?.title || tr('pdf.travelPlan'))} - + - - - - - - -
- ${coverImg ? `
` : ''} -
-
-
- ${coverImg - ? `
` - : `
`} -
${escHtml(tr('pdf.travelPlan'))}
-
${escHtml(trip?.title || 'My Trip')}
- ${trip?.description ? `
${escHtml(trip.description)}
` : ''} - ${range ? `
${range}
` : ''} -
-
-
-
${sorted.length}
-
${escHtml(tr('dashboard.days', { count: sorted.length }))}
-
-
-
${places?.length || 0}
-
${escHtml(tr('dashboard.places', { count: places?.length || 0 }))}
-
-
-
${totalAssigned}
-
${escHtml(tr('pdf.planned'))}
-
- ${totalDistanceLabel ? `
-
${escHtml(totalDistanceLabel)}
-
${escHtml(tr('pdf.distanceLabel'))}
-
` : ''} - ${totalCostLabel ? `
-
${totalCostLabel}
-
${escHtml(tr('pdf.costLabel'))}
-
` : ''} -
-
-
- - -${hasInvalidTour ? `

${escHtml(tr('tours.dayRoute.endpointUnknown'))}

` : ''} -${tripMapHtml} - - + +
+${coverHtml({ + title: trip?.title || 'My Trip', + description: trip?.description || null, + range, + image: coverImg, + logo: absUrl('/logo-light.svg'), + stats, + tr, +})} +${overviewHtml} ${daysHtml} ${pluginSectionsHtml} +
made withTREK
+
` markdown.dispose() if (signal?.aborted) return - openPdfPreview({ html, title: trip?.title || tr('pdf.travelPlan'), tripId: trip?.id, tr, breaksPerDay, showTransportNotes, hasTransportNotes, largeText }) + openPdfPreview({ + html, + title: trip?.title || tr('pdf.travelPlan'), + tripId: trip?.id, + tr, + ...switches, + hasTransportNotes: flags.transportNote, + }) } -function bodyClassAttr(breaksPerDay: boolean, showTransportNotes: boolean, largeText: boolean): string { - const classes = [!breaksPerDay && 'pdf-flow', !showTransportNotes && 'pdf-no-transport-notes', largeText && 'pdf-large-text'].filter(Boolean) +function bodyClassAttr(s: { breaksPerDay: boolean; showTransportNotes: boolean; largeText: boolean; photos: boolean; overview: boolean; coordinates: boolean; details: boolean }): string { + const classes = [ + !s.breaksPerDay && 'pdf-flow', + !s.showTransportNotes && 'pdf-no-transport-notes', + s.largeText && 'pdf-large-text', + !s.photos && 'pdf-no-photos', + !s.overview && 'pdf-no-overview', + !s.coordinates && 'pdf-no-coords', + !s.details && 'pdf-no-details', + ].filter(Boolean) return classes.length ? ` class="${classes.join(' ')}"` : '' } diff --git a/client/src/components/PDF/pdfImages.test.ts b/client/src/components/PDF/pdfImages.test.ts index 12c6f9753..1abb92d86 100644 --- a/client/src/components/PDF/pdfImages.test.ts +++ b/client/src/components/PDF/pdfImages.test.ts @@ -8,7 +8,7 @@ import { http, HttpResponse } from 'msw'; import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import { server } from '../../../tests/helpers/msw/server'; -import { shrinkPdfImages } from './pdfImages'; +import { shrinkPdfImages, STRIP_PX } from './pdfImages'; const origin = window.location.origin; const JPEG = 'data:image/jpeg;base64,c21hbGw='; @@ -64,19 +64,27 @@ afterEach(() => { }); describe('shrinkPdfImages', () => { - it('FE-PDFIMAGES-001: a same-origin photo comes back as a JPEG with its short side at 156 px', async () => { + it('FE-PDFIMAGES-001: a same-origin photo comes back as a JPEG with its short side at 222 px', async () => { const url = `${origin}/uploads/places/a.jpg`; const shrunk = await shrinkPdfImages([url]); expect(shrunk.get(url)).toBe(JPEG); - expect(drawn).toEqual([{ width: 234, height: 156 }]); + expect(drawn).toEqual([{ width: 333, height: 222 }]); expect(HTMLCanvasElement.prototype.toDataURL).toHaveBeenCalledWith('image/jpeg', expect.any(Number)); }); it('FE-PDFIMAGES-001b: a photo is decoded near thumbnail size, not in full', async () => { await shrinkPdfImages([`${origin}/uploads/places/a.jpg`]); - expect(createImageBitmap).toHaveBeenCalledWith(expect.any(Blob), { resizeHeight: 312, resizeQuality: 'medium' }); + expect(createImageBitmap).toHaveBeenCalledWith(expect.any(Blob), { resizeHeight: 444, resizeQuality: 'medium' }); + }); + + it('FE-PDFIMAGES-001c: the photo strip of a day asks for a larger copy, decoded at twice its size', async () => { + const url = `${origin}/uploads/places/a.jpg`; + await shrinkPdfImages([url], undefined, STRIP_PX); + + expect(drawn).toEqual([{ width: 720, height: 480 }]); + expect(createImageBitmap).toHaveBeenCalledWith(expect.any(Blob), { resizeHeight: 960, resizeQuality: 'medium' }); }); it('FE-PDFIMAGES-002: a photo from another origin keeps its URL and is never fetched', async () => { diff --git a/client/src/components/PDF/pdfImages.ts b/client/src/components/PDF/pdfImages.ts index dc573f8e9..2f793c22d 100644 --- a/client/src/components/PDF/pdfImages.ts +++ b/client/src/components/PDF/pdfImages.ts @@ -12,16 +12,16 @@ * than FETCH_TIMEOUT_MS. */ -/** The short side of a copy: three times the 52 px thumbnail, sharp at print resolution. */ -const THUMB_PX = 156; +/** The short side of a place card's copy: three times its 74 px photo, sharp at print resolution. */ +const THUMB_PX = 222; +/** The short side of a copy for the photo strip that opens a day, which runs the width of the page. */ +export const STRIP_PX = 480; const JPEG_QUALITY = 0.72; /** * Photos in flight at once: a trip of hundreds should neither queue one by one nor * decode all at once. Kept low for the phone, where each decode costs memory. */ const CONCURRENCY = 3; -/** Height a photo is decoded at: twice THUMB_PX, so a portrait one still has room to shrink. */ -const DECODE_PX = THUMB_PX * 2; const FETCH_TIMEOUT_MS = 10_000; /** Anything larger is not read into memory for a thumbnail; it keeps its URL. */ const MAX_BYTES = 20 * 1024 * 1024; @@ -31,14 +31,18 @@ const MAX_BYTES = 20 * 1024 * 1024; * missing from the result prints as it is. Stops starting new photos once * `signal` aborts, and returns what it has. */ -export async function shrinkPdfImages(urls: Iterable, signal?: AbortSignal): Promise> { +export async function shrinkPdfImages( + urls: Iterable, + signal?: AbortSignal, + shortSide = THUMB_PX +): Promise> { const shrunk = new Map(); const queue = [...new Set(urls)].filter(isSameOrigin); if (queue.length === 0 || !canShrink()) return shrunk; const worker = async () => { for (let url = queue.shift(); url !== undefined && !signal?.aborted; url = queue.shift()) { - const copy = await shrinkImage(url, signal); + const copy = await shrinkImage(url, shortSide, signal); if (copy) shrunk.set(url, copy); } }; @@ -61,7 +65,7 @@ function canShrink(): boolean { return typeof createImageBitmap === 'function' && document.createElement('canvas').getContext('2d') !== null; } -async function shrinkImage(url: string, signal?: AbortSignal): Promise { +async function shrinkImage(url: string, shortSide: number, signal?: AbortSignal): Promise { // A controller and a timer rather than AbortSignal.timeout/any, which Safari only // has from 16 and 17.4 on; a throw there would cost the whole export. const fetching = new AbortController(); @@ -76,9 +80,10 @@ async function shrinkImage(url: string, signal?: AbortSignal): Promise= 1) return null; const canvas = document.createElement('canvas'); canvas.width = Math.max(1, Math.round(bitmap.width * scale)); diff --git a/client/src/components/PDF/pdfPreview.test.ts b/client/src/components/PDF/pdfPreview.test.ts index 4a05270a3..7b82606b5 100644 --- a/client/src/components/PDF/pdfPreview.test.ts +++ b/client/src/components/PDF/pdfPreview.test.ts @@ -1,12 +1,21 @@ /** - * FE-PDFPREVIEW-001 to FE-PDFPREVIEW-007: the trip PDF's preview and the control + * FE-PDFPREVIEW-001 to FE-PDFPREVIEW-009: the trip PDF's preview and the control * that saves it. An iPhone or iPad ignores print() in the Home Screen app, so * there the preview hands the export to Safari instead of offering a button that * does nothing. */ import { afterEach, describe, expect, it, vi } from 'vitest'; -import { LARGE_TEXT_KEY, PAGE_BREAK_KEY, openPdfPreview, type PdfPreviewOptions } from './pdfPreview'; +import { + COORDINATES_KEY, + DETAILS_KEY, + LARGE_TEXT_KEY, + OVERVIEW_KEY, + PAGE_BREAK_KEY, + PHOTOS_KEY, + openPdfPreview, + type PdfPreviewOptions, +} from './pdfPreview'; const tr = (key: string) => key; @@ -20,6 +29,10 @@ function open(overrides: Partial = {}) { showTransportNotes: true, hasTransportNotes: false, largeText: false, + photos: true, + overview: true, + coordinates: true, + details: true, ...overrides, }); } @@ -111,4 +124,43 @@ describe('openPdfPreview', () => { } expect(document.getElementById('pdf-large-text-toggle')?.getAttribute('aria-checked')).toBe('true'); }); + + it('FE-PDFPREVIEW-008: the switches sit in a row of their own under the title and the actions', () => { + open({ hasTransportNotes: true }); + const row = document.getElementById('pdf-settings-row'); + const ids = [...(row?.querySelectorAll('[role="switch"]') ?? [])].map((toggle) => toggle.id); + expect(ids).toEqual([ + 'pdf-daybreak-toggle', + 'pdf-large-text-toggle', + 'pdf-overview-toggle', + 'pdf-photos-toggle', + 'pdf-coordinates-toggle', + 'pdf-details-toggle', + 'pdf-transport-notes-toggle', + ]); + // The header keeps only the title and its two actions. + expect(row?.previousElementSibling?.querySelector('[role="switch"]')).toBeNull(); + expect(row?.previousElementSibling?.querySelector('#pdf-print-btn')).not.toBeNull(); + }); + + it.each([ + ['pdf-overview-toggle', OVERVIEW_KEY, 'pdf-no-overview'], + ['pdf-photos-toggle', PHOTOS_KEY, 'pdf-no-photos'], + ['pdf-coordinates-toggle', COORDINATES_KEY, 'pdf-no-coords'], + ['pdf-details-toggle', DETAILS_KEY, 'pdf-no-details'], + ])('FE-PDFPREVIEW-009: %s hides its part of the open document at once and is remembered', (id, key, hidden) => { + open(); + const toggle = document.getElementById(id); + const body = document.querySelector('#pdf-preview-overlay iframe')?.contentDocument?.body; + expect(toggle?.getAttribute('aria-checked')).toBe('true'); + + toggle?.click(); + expect(toggle?.getAttribute('aria-checked')).toBe('false'); + expect(localStorage.getItem(key)).toBe('0'); + if (body) expect(body.classList.contains(hidden)).toBe(true); + + toggle?.click(); + expect(localStorage.getItem(key)).toBe('1'); + if (body) expect(body.classList.contains(hidden)).toBe(false); + }); }); diff --git a/client/src/components/PDF/pdfPreview.ts b/client/src/components/PDF/pdfPreview.ts index c92969b36..b7f6bdf3f 100644 --- a/client/src/components/PDF/pdfPreview.ts +++ b/client/src/components/PDF/pdfPreview.ts @@ -25,6 +25,17 @@ export const TRANSPORT_NOTES_KEY = 'trek_pdf_transport_notes'; */ export const LARGE_TEXT_KEY = 'trek_pdf_large_text'; +/** + * What the document shows besides the plan itself, each on by default and each a + * switch in the preview: the photos of the places and stays, the overview pages + * (route map, the days at a glance, bookings and stays), the coordinates under the + * addresses, and the contact lines, opening hours and companions of a place. + */ +export const PHOTOS_KEY = 'trek_pdf_photos'; +export const OVERVIEW_KEY = 'trek_pdf_overview'; +export const COORDINATES_KEY = 'trek_pdf_coordinates'; +export const DETAILS_KEY = 'trek_pdf_details'; + /* The overlay is imperative DOM, so the switch from Settings/ToggleSwitch is rebuilt here rather than rendered — as static markup it would carry no behaviour. Same geometry and the same tokens, so it reads as the same control. */ @@ -52,6 +63,10 @@ export interface PdfPreviewOptions { /** The transport-notes switch only shows when there is a note to hide. */ hasTransportNotes: boolean; largeText: boolean; + photos: boolean; + overview: boolean; + coordinates: boolean; + details: boolean; } /** @@ -84,6 +99,10 @@ export function openPdfPreview({ showTransportNotes, hasTransportNotes, largeText, + photos, + overview, + coordinates, + details, }: PdfPreviewOptions): void { // Open in modal with srcdoc iframe (no URL loading = no X-Frame-Options issue) const overlay = document.createElement('div'); @@ -104,10 +123,7 @@ export function openPdfPreview({ 'display:flex;align-items:center;justify-content:space-between;gap:8px;flex-wrap:wrap;padding:10px 16px;border-bottom:1px solid var(--border-primary);flex-shrink:0;'; header.innerHTML = ` ${escapeHtml(title)} -
- ${hasTransportNotes ? previewSwitch('pdf-transport-notes-toggle', tr('pdf.transportNotes'), showTransportNotes) : ''} - ${previewSwitch('pdf-daybreak-toggle', tr('pdf.pageBreakPerDay'), breaksPerDay)} - ${previewSwitch('pdf-large-text-toggle', tr('pdf.largeText'), largeText)} +
${save.html}
`; + // The document's switches in a row of their own under the header: the layout first, + // then what it shows, so the header keeps only the title and the actions. + const settings = document.createElement('div'); + settings.id = 'pdf-settings-row'; + settings.style.cssText = + 'display:flex;align-items:center;flex-wrap:wrap;gap:8px 18px;padding:8px 16px;border-bottom:1px solid var(--border-primary);background:var(--bg-secondary);flex-shrink:0;'; + settings.innerHTML = [ + previewSwitch('pdf-daybreak-toggle', tr('pdf.pageBreakPerDay'), breaksPerDay), + previewSwitch('pdf-large-text-toggle', tr('pdf.largeText'), largeText), + '', + previewSwitch('pdf-overview-toggle', tr('pdf.showOverview'), overview), + previewSwitch('pdf-photos-toggle', tr('pdf.showPhotos'), photos), + previewSwitch('pdf-coordinates-toggle', tr('collections.coordinates'), coordinates), + previewSwitch('pdf-details-toggle', tr('pdf.showDetails'), details), + hasTransportNotes ? previewSwitch('pdf-transport-notes-toggle', tr('pdf.transportNotes'), showTransportNotes) : '', + ].join(''); + const iframe = document.createElement('iframe'); iframe.style.cssText = 'flex:1;width:100%;border:none;'; // No script runs inside the document (print is parent-initiated), so withhold @@ -123,6 +156,7 @@ export function openPdfPreview({ iframe.srcdoc = html; card.appendChild(header); + card.appendChild(settings); if (save.hint) { const hint = document.createElement('p'); hint.id = 'pdf-safari-hint'; @@ -145,18 +179,18 @@ export function openPdfPreview({ // Each choice differs by one class on , so switching is instant in the // preview and there is no need to re-fetch photos or rebuild the document. - wirePreviewSwitch(header, 'pdf-daybreak-toggle', (on) => { - rememberPdfSwitch(PAGE_BREAK_KEY, on); - iframe.contentDocument?.body.classList.toggle('pdf-flow', !on); - }); - wirePreviewSwitch(header, 'pdf-transport-notes-toggle', (on) => { - rememberPdfSwitch(TRANSPORT_NOTES_KEY, on); - iframe.contentDocument?.body.classList.toggle('pdf-no-transport-notes', !on); - }); - wirePreviewSwitch(header, 'pdf-large-text-toggle', (on) => { - rememberPdfSwitch(LARGE_TEXT_KEY, on); - iframe.contentDocument?.body.classList.toggle('pdf-large-text', on); - }); + const bodyClass = (id: string, key: string, className: string, addWhenOn: boolean) => + wirePreviewSwitch(settings, id, (on) => { + rememberPdfSwitch(key, on); + iframe.contentDocument?.body.classList.toggle(className, addWhenOn ? on : !on); + }); + bodyClass('pdf-daybreak-toggle', PAGE_BREAK_KEY, 'pdf-flow', false); + bodyClass('pdf-transport-notes-toggle', TRANSPORT_NOTES_KEY, 'pdf-no-transport-notes', false); + bodyClass('pdf-large-text-toggle', LARGE_TEXT_KEY, 'pdf-large-text', true); + bodyClass('pdf-overview-toggle', OVERVIEW_KEY, 'pdf-no-overview', false); + bodyClass('pdf-photos-toggle', PHOTOS_KEY, 'pdf-no-photos', false); + bodyClass('pdf-coordinates-toggle', COORDINATES_KEY, 'pdf-no-coords', false); + bodyClass('pdf-details-toggle', DETAILS_KEY, 'pdf-no-details', false); } /** diff --git a/client/src/components/PDF/tripPdfDay.test.ts b/client/src/components/PDF/tripPdfDay.test.ts new file mode 100644 index 000000000..312dc35e9 --- /dev/null +++ b/client/src/components/PDF/tripPdfDay.test.ts @@ -0,0 +1,261 @@ +/** + * FE-PDFDAY-001 to FE-PDFDAY-012: one day of the trip PDF, built piece by piece. + * The whole export is covered by TripPDF.test.ts; these pin what each card prints + * from the data it is given, the trip's full place included. + */ +import { describe, expect, it } from 'vitest'; + +import type { Accommodation, Assignment, Category, Day, DayNote, Place } from '../../types'; +import { dayHeader, noteItem, photoStrip, placeItem, staysBlock, type PdfDayContext } from './tripPdfDay'; + +const day = { id: 10, day_number: 3, title: 'Kyoto', date: '2026-05-06' } as Day; // a Wednesday + +const category = { id: 4, name: 'Temple', icon: 'landmark', color: '#c2410c' } as Category; + +/** Monday first, like the stored week; Wednesday has hours, Thursday is closed. */ +const week = JSON.stringify([ + { open: '08:00', close: '18:00' }, + { open: '08:00', close: '18:00' }, + { open: '09:00', close: '17:30' }, + { closed: true }, + { open: '08:00', close: '18:00' }, + { open: '08:00', close: '18:00' }, + { open: '08:00', close: '18:00' }, +]); + +const fullPlace = { + id: 7, + name: 'Kiyomizu-dera', + category_id: 4, + address: '1 Chome-294 Kiyomizu, Kyoto', + lat: 34.994856, + lng: 135.785046, + rating_avg: 4.64, + rating_count: 12, + email: 'info@kiyomizudera.or.jp', + phone: '+81 75-551-1234', + website: 'https://www.kiyomizudera.or.jp/en/', + opening_hours: week, + reservation_notes: 'Tickets at the west gate', + tags: [{ name: 'Must see', color: '#16a34a' }], +} as unknown as Place; + +function context(over: Partial = {}): PdfDayContext { + return { + tr: (key, params) => (params ? `${key}:${JSON.stringify(params)}` : key), + fmtTime: (value) => value ?? '', + locale: 'en-US', + tripCurrency: 'JPY', + categories: [category], + placesById: new Map([[fullPlace.id, fullPlace]]), + photoOf: () => null, + markdown: (text) => `

${text}

`, + ...over, + }; +} + +/** The assignment as the API hands it over: a projection of its place, without the rating, e-mail or hours. */ +function assignment(over: Record = {}): Assignment { + return { + id: 200, + day_id: 10, + order_index: 0, + notes: 'Go early', + participants: [ + { user_id: 1, username: 'mia' }, + { user_id: 2, username: 'leo' }, + ], + place: { + id: 7, + name: 'Kiyomizu-dera', + category_id: 4, + address: '1 Chome-294 Kiyomizu, Kyoto', + lat: 34.994856, + lng: 135.785046, + place_time: '09:30', + end_time: '11:00', + duration_minutes: 90, + price: 500, + currency: null, + description: 'Wooden **stage** over the hill', + notes: null, + tags: [{ name: 'Must see', color: '#16a34a' }], + ...over, + }, + } as unknown as Assignment; +} + +const parse = (html: string) => new DOMParser().parseFromString(html, 'text/html'); +const texts = (doc: Document, selector: string) => + [...doc.querySelectorAll(selector)].map((el) => el.textContent?.replace(/\s+/g, ' ').trim()); + +describe('placeItem', () => { + it('FE-PDFDAY-001: prints the stop with its number, times, facts, address and coordinates', () => { + const doc = parse(placeItem(assignment(), 2, day, context())); + + expect(texts(doc, '.tl-marker')).toEqual(['2']); + expect(texts(doc, '.tl-start')).toEqual(['09:30']); + expect(texts(doc, '.tl-end')).toEqual(['11:00']); + expect(texts(doc, '.place-name')).toEqual(['Kiyomizu-dera']); + expect(texts(doc, '.cat-badge')).toEqual(['Temple']); + const facts = texts(doc, '.facts .chip'); + expect(facts[0]).toBe('1 h 30 min'); + expect(facts[1]).toMatch(/500/); + expect(facts.slice(2)).toEqual(['4.6 (12)', 'Must see']); + expect(texts(doc, '.info-row .info-text')).toEqual(['1 Chome-294 Kiyomizu, Kyoto', '34.99486, 135.78505']); + expect(doc.querySelector('.coords')).not.toBeNull(); + }); + + it('FE-PDFDAY-002: reads the rating, e-mail, hours and reservation note off the trip place', () => { + const doc = parse(placeItem(assignment(), 1, day, context())); + + // The day is a Wednesday: its hours, not Monday's. + expect(texts(doc, '.details .detail')).toEqual([ + 'inspector.openingHours 09:00 – 17:30', + '+81 75-551-1234', + 'kiyomizudera.or.jp', + 'info@kiyomizudera.or.jp', + 'inspector.participants: mia, leo', + ]); + expect(texts(doc, '.place-note')).toEqual(['Tickets at the west gate', 'Go early']); + expect(doc.querySelector('.place-text')?.innerHTML).toBe('

Wooden **stage** over the hill

'); + }); + + it('FE-PDFDAY-003: a day the place is closed says so', () => { + const thursday = { ...day, date: '2026-05-07' } as Day; + const doc = parse(placeItem(assignment(), 1, thursday, context())); + + expect(texts(doc, '.details .detail')[0]).toBe('inspector.openingHours inspector.closed'); + }); + + it('FE-PDFDAY-004: a place with neither photo nor extras prints its category tile and nothing empty', () => { + const bare = { + id: 201, + day_id: 10, + order_index: 0, + place: { id: 99, name: 'Corner shop', category_id: 4, lat: null, lng: null }, + } as unknown as Assignment; + const doc = parse(placeItem(bare, 1, { ...day, date: null } as Day, context())); + + expect(doc.querySelector('.place-thumb-fallback')).not.toBeNull(); + expect(doc.querySelector('.place-card')?.getAttribute('style')).toBe('--cat:#c2410c'); + for (const empty of ['.facts', '.info-row', '.details', '.place-note', '.place-text', '.tl-start', '.tl-end']) { + expect(doc.querySelector(empty)).toBeNull(); + } + }); + + it('FE-PDFDAY-005: the photo the export picked prints, and a hostile name and tag colour stay inert', () => { + const hostile = assignment({ + name: '', + tags: [{ name: 'x', color: 'red;background:url(x)' }], + }); + const html = placeItem(hostile, 1, day, context({ photoOf: () => 'data:image/jpeg;base64,AAA' })); + const doc = parse(html); + + expect(doc.querySelector('img.place-thumb')?.getAttribute('src')).toBe('data:image/jpeg;base64,AAA'); + expect(doc.querySelectorAll('img')).toHaveLength(1); + expect(texts(doc, '.place-name')).toEqual(['']); + expect(doc.querySelector('.chip-tag')?.getAttribute('style')).toBe('--tag:#6b6b75'); + }); +}); + +describe('noteItem', () => { + it('FE-PDFDAY-006: a coloured note carries its colour as the edge, an unknown colour none', () => { + const note = { + id: 1, + day_id: 10, + text: 'Buy ', + time: '08:00', + icon: 'Ticket', + color: '#2563eb', + } as DayNote; + const tinted = parse(noteItem(note)); + expect(tinted.querySelector('.note-card')?.className).toBe('note-card note-tinted'); + expect(tinted.querySelector('.note-card')?.getAttribute('style')).toBe('--note:#2563eb'); + expect(texts(tinted, '.note-text')).toEqual(['Buy ']); + expect(texts(tinted, '.tl-start')).toEqual(['08:00']); + + const plain = parse(noteItem({ ...note, color: 'not-a-colour', time: null } as DayNote)); + expect(plain.querySelector('.note-card')?.className).toBe('note-card'); + expect(plain.querySelector('.tl-start')).toBeNull(); + }); +}); + +describe('staysBlock', () => { + const stay = { + id: 1, + start_day_id: 10, + end_day_id: 12, + place_name: 'Hotel Gion', + place_address: 'Gion 1', + check_in: '15:00', + check_out: '10:00', + confirmation: 'HX-42', + notes: 'Late arrival', + place_image: null, + } as unknown as Accommodation; + + it('FE-PDFDAY-007: the arrival day gets the full card with time, address, notes and code', () => { + const doc = parse(staysBlock([stay], day, context())); + + expect(doc.querySelector('.day-accommodations')?.className).toBe('day-accommodations single'); + expect(texts(doc, '.stay-kicker')).toEqual(['reservations.meta.checkIn 15:00']); + expect(texts(doc, '.stay-name')).toEqual(['Hotel Gion']); + expect(texts(doc, '.stay-line')).toEqual(['Gion 1', 'Late arrival']); + expect(texts(doc, '.code-chip')).toEqual(['HX-42']); + }); + + it('FE-PDFDAY-008: a night in between is one quiet line, the leaving day the check-out', () => { + const middle = parse(staysBlock([stay], { ...day, id: 11 } as Day, context())); + expect(middle.querySelector('.stay-quiet')).not.toBeNull(); + expect(texts(middle, '.stay-kicker')).toEqual(['reservations.meta.linkAccommodation']); + expect(middle.querySelector('.stay-line')).toBeNull(); + + const leaving = parse(staysBlock([stay], { ...day, id: 12 } as Day, context())); + expect(texts(leaving, '.stay-kicker')).toEqual(['reservations.meta.checkOut 10:00']); + expect(leaving.querySelector('.code-chip')).toBeNull(); + }); + + it('FE-PDFDAY-009: no stay prints nothing, two drop the single-column class', () => { + expect(staysBlock([], day, context())).toBe(''); + const doc = parse(staysBlock([stay, { ...stay, id: 2, place_name: 'Ryokan' } as Accommodation], day, context())); + expect(doc.querySelector('.day-accommodations')?.className).toBe('day-accommodations'); + }); +}); + +describe('dayHeader', () => { + it('FE-PDFDAY-010: the number, date and title, with only the figures the day has', () => { + const doc = parse(dayHeader(day, { stops: 4, distance: '12 km', cost: '¥3,000' }, context())); + + expect(texts(doc, '.day-tag')).toEqual(['pdf.day 3']); + expect(texts(doc, '.day-date')[0]).toMatch(/May/); + expect(texts(doc, '.day-title')).toEqual(['Kyoto']); + expect(texts(doc, '.meta-pill, .day-cost')).toEqual(['4', '12 km', '¥3,000']); + + const untitled = parse( + dayHeader({ ...day, title: null, date: null } as Day, { stops: 0, distance: null, cost: null }, context()) + ); + expect(texts(untitled, '.day-title')).toEqual(['dayplan.dayN:{"n":3}']); + expect(untitled.querySelector('.day-date')).toBeNull(); + expect(untitled.querySelector('.day-meta')).toBeNull(); + }); +}); + +describe('photoStrip', () => { + it('FE-PDFDAY-011: up to three photos, each named on its label; none prints nothing', () => { + expect(photoStrip([])).toBe(''); + const doc = parse( + photoStrip([ + { url: 'https://a.example/1.jpg', caption: 'Gate ' }, + { url: 'https://a.example/2.jpg', caption: 'Stage' }, + ]) + ); + + expect(doc.querySelector('.day-strip')?.className).toBe('day-strip day-strip-2'); + expect(texts(doc, '.glass-label')).toEqual(['Gate ', 'Stage']); + expect([...doc.querySelectorAll('img')].map((img) => img.getAttribute('src'))).toEqual([ + 'https://a.example/1.jpg', + 'https://a.example/2.jpg', + ]); + }); +}); diff --git a/client/src/components/PDF/tripPdfDay.ts b/client/src/components/PDF/tripPdfDay.ts new file mode 100644 index 000000000..fb96fecf0 --- /dev/null +++ b/client/src/components/PDF/tripPdfDay.ts @@ -0,0 +1,427 @@ +import { parsePlaceHours } from '@trek/shared'; + +import type { Accommodation, Assignment, Category, Day, DayNote, Place, Reservation } from '../../types'; +import { getDisplayTimeForDay, getSpanPhase } from '../../utils/dayMerge'; +import { getFlightLegs, getTrainLegs, usesStationRoute } from '../../utils/flightLegs'; +import { formatMoney, splitReservationDateTime } from '../../utils/formatters'; +import type { TransportLegDetail } from '../Planner/transportDetailModel'; +import { escHtml, hexColour, safeImg, shortDate, websiteHost } from './tripPdfHtml'; +import { bookingIcon, bookingTint, categoryIcon, glyph, noteIcon } from './tripPdfIcons'; + +/* + * One day of the trip PDF: its header, where the night is spent, and the day's plan + * as a timeline, times on the left, a rail in the day's colour, and a card for every + * stop, booking and note. + */ + +type Translate = (key: string, params?: Record) => string; + +/** A booking as the day merge hands it over, a leg of a multi-leg booking included. */ +export type PdfBooking = Reservation & { __leg?: TransportLegDetail & { total?: number } }; + +/** What the day's markup needs from the export around it. */ +export interface PdfDayContext { + tr: Translate; + fmtTime: (value?: string | null) => string; + locale: string | undefined; + tripCurrency: string; + categories: readonly Category[]; + /** The trip's full places by id: an assignment carries only a projection of its place. */ + placesById: ReadonlyMap; + /** The picture to print for a place, already shrunk where it could be; null for none. */ + photoOf: (place: Assignment['place']) => string | null; + /** A place's description or notes as sanitized markdown. */ + markdown: (text: string) => string; +} + +const NEUTRAL = '#6b6b75'; + +function metadataOf(r: PdfBooking): Record { + if (!r.metadata) return {}; + try { + const parsed: unknown = typeof r.metadata === 'string' ? JSON.parse(r.metadata) : r.metadata; + return parsed && typeof parsed === 'object' ? (parsed as Record) : {}; + } catch { + return {}; + } +} + +const text = (value: unknown): string => (typeof value === 'string' || typeof value === 'number' ? String(value) : ''); + +/** "1 h 30 min", or null for no duration at all. */ +function durationLabel(minutes: number | null | undefined): string | null { + if (typeof minutes !== 'number' || !Number.isFinite(minutes) || minutes <= 0) return null; + const whole = Math.round(minutes); + const h = Math.floor(whole / 60); + const m = whole % 60; + if (h === 0) return `${m} min`; + return m === 0 ? `${h} h` : `${h} h ${m} min`; +} + +function timeColumn(start: string, end: string): string { + return `
${start ? `${escHtml(start)}` : ''}${ + end ? `${escHtml(end)}` : '' + }
`; +} + +function item(kind: string, time: string, marker: string, body: string, style = ''): string { + return `
  • ${time}
    ${marker}
    ${body}
  • `; +} + +// ── Bookings ────────────────────────────────────────────────────────────── + +/** "Departure", "Pick-up" and the like, for a booking that spans days; null on its single day. */ +function spanLabel(r: PdfBooking, phase: string, tr: Translate): string | null { + if (phase === 'single') return null; + const at = (start: string, end: string, middle: string) => + tr(`reservations.span.${phase === 'start' ? start : phase === 'end' ? end : middle}`); + if (r.type === 'flight') return at('departure', 'arrival', 'inTransit'); + if (r.type === 'car') return at('pickup', 'return', 'active'); + // Parking reuses span.pickup for its end day: you drop the car off and collect it + // again later, so the rental car's wording carries over without a second key. + if (r.type === 'parking') return at('dropOff', 'pickup', 'ongoing'); + return at('start', 'end', 'ongoing'); +} + +function stopsOf(r: PdfBooking, label: 'code' | 'name'): string[] { + return (r.endpoints || []) + .slice() + .sort((a, b) => (a.sequence ?? 0) - (b.sequence ?? 0)) + .map((e) => (label === 'code' ? e.code || e.name : e.name) || '') + .filter(Boolean); +} + +/** One line under a booking's title: the way it goes, its facts as badges and its own booking code. */ +interface BookingLine { + route: string; + facts: string[]; + code: string; + /** A table's party size, printed with the people icon so it needs no word. */ + people?: string; +} + +/** + * The lines under a booking's title. A multi-leg flight or train gets one per leg, each + * with its own number and booking code, since that is the code the gate asks for + * (#1943); a leg row prints its own leg; everything else gets one line or none. + */ +function bookingLines(r: PdfBooking, tr: Translate): BookingLine[] { + const meta = metadataOf(r); + const route = (from?: string | null, to?: string | null) => + from || to ? [from, to].filter(Boolean).join(' → ') : ''; + const seat = (value: unknown) => (text(value) ? `${tr('reservations.meta.seat')} ${text(value)}` : ''); + const platform = (value: unknown) => (text(value) ? `${tr('reservations.meta.platform')} ${text(value)}` : ''); + const line = (way: string, facts: unknown[], code: unknown = ''): BookingLine => ({ + route: way, + facts: facts.map(text).filter(Boolean), + code: text(code), + }); + const filled = (lines: BookingLine[]) => lines.filter((l) => l.route || l.facts.length || l.code); + + if (r.__leg) { + const l = r.__leg; + const source = (usesStationRoute(r.type) ? getTrainLegs(r) : getFlightLegs(r))[l.index]; + return filled([ + line( + route(l.from, l.to), + [l.airline, l.flight_number, l.train_number, platform(l.platform), seat(l.seat)], + source?.confirmation_number + ), + ]); + } + if (r.type === 'flight') { + const legs = getFlightLegs(r); + if (legs.length > 1) { + return filled( + legs.map((l) => line(route(l.from, l.to), [l.airline, l.flight_number, seat(l.seat)], l.confirmation_number)) + ); + } + const stops = stopsOf(r, 'code'); + const way = stops.length >= 2 ? stops.join(' → ') : route(text(meta.departure_airport), text(meta.arrival_airport)); + return filled([line(way, [meta.airline, meta.flight_number, seat(meta.seat)])]); + } + if (r.type === 'train') { + const legs = getTrainLegs(r); + if (legs.length > 1) { + return filled( + legs.map((l) => + line(route(l.from, l.to), [l.train_number, platform(l.platform), seat(l.seat)], l.confirmation_number) + ) + ); + } + const stops = stopsOf(r, 'code'); + return filled([ + line(stops.length >= 2 ? stops.join(' → ') : '', [meta.train_number, platform(meta.platform), seat(meta.seat)]), + ]); + } + if (r.type === 'car') { + // A rental with stops is a drive, and the printout is what people take into the car + // (#1797). Consecutive repeats collapse, and a chain of one place is no route: the + // ordinary rental is picked up and returned at the same desk. + const stops = stopsOf(r, 'name').filter((name, i, all) => name !== all[i - 1]); + return new Set(stops).size >= 2 ? [line(stops.join(' → '), [])] : []; + } + if (r.type === 'restaurant') return text(meta.party_size) ? [{ ...line('', []), people: text(meta.party_size) }] : []; + if (r.type === 'event') return filled([line('', [meta.venue])]); + if (r.type === 'tour') return filled([line('', [meta.operator])]); + return []; +} + +function bookingLineHtml(l: BookingLine): string { + return `
    ${l.route ? `${escHtml(l.route)}` : ''}${ + l.people ? `${glyph('people', 9)}${escHtml(l.people)}` : '' + }${l.facts + .map((fact) => `${escHtml(fact)}`) + .join('')}${l.code ? `${glyph('key', 9)}${escHtml(l.code)}` : ''}
    `; +} + +/** A booking's lines on their own, for the booking list of the overview. */ +export function bookingLinesHtml(r: PdfBooking, tr: Translate): string { + return bookingLines(r, tr).map(bookingLineHtml).join(''); +} + +/** A booking on the day's timeline. Sets `flags.transportNote` when it prints a note. */ +export function bookingItem(r: PdfBooking, day: Day, ctx: PdfDayContext, flags: { transportNote: boolean }): string { + const { tr, fmtTime } = ctx; + const phase = getSpanPhase(r, day.id); + const span = spanLabel(r, phase, tr); + // Start and end the way the day plan draws them (#1310). The landing time only on a + // booking that begins and ends this day: across a span the arrival belongs to the + // arrival day, which shows it as its own time. + const start = fmtTime(splitReservationDateTime(getDisplayTimeForDay(r, day.id)).time); + const end = phase === 'single' ? fmtTime(splitReservationDateTime(r.reservation_end_time).time) : ''; + const note = typeof r.notes === 'string' ? r.notes.trim() : ''; + if (note) flags.transportNote = true; + const meta = metadataOf(r); + const location = r.location || text(meta.location); + const status = r.status === 'confirmed' || r.status === 'pending' ? tr(`reservations.${r.status}`) : ''; + const tint = hexColour(bookingTint(r.type), NEUTRAL); + + const extras = [ + r.confirmation_number + ? `${glyph('key', 9)}${escHtml(r.confirmation_number)}` + : '', + status ? `${escHtml(status)}` : '', + ].filter(Boolean); + + const card = `
    + ${bookingIcon(r.type)} +
    + ${span ? `
    ${escHtml(span)}
    ` : ''} +
    ${escHtml(r.title)}
    + ${bookingLines(r, tr).map(bookingLineHtml).join('')} + ${location ? `
    ${escHtml(location)}
    ` : ''} + ${extras.length ? `
    ${extras.join('')}
    ` : ''} + ${note ? `
    ${escHtml(note)}
    ` : ''} +
    +
    `; + return item('booking', timeColumn(start, end), bookingIcon(r.type, 11), card, `--kind:${tint}`); +} + +// ── Notes ───────────────────────────────────────────────────────────────── + +/** + * A day note. A coloured note carries its colour as the rule along its edge and its + * icon (#1629), not as a fill: a tint costs ink and reads as grey on a mono printer. + */ +export function noteItem(note: DayNote): string { + const colour = note.color ? hexColour(note.color, '') : ''; + const card = `
    + ${noteIcon(note.icon)} +
    ${escHtml(note.text)}
    +
    `; + return item('note', timeColumn(note.time || '', ''), '', card); +} + +// ── Places ──────────────────────────────────────────────────────────────── + +/** The day's opening hours of a place, Monday first like the stored week; null when unknown. */ +function hoursOnDay(place: Partial, day: Day, ctx: PdfDayContext): string | null { + const week = parsePlaceHours(place.opening_hours); + if (!week || !day.date) return null; + const weekday = (new Date(day.date + 'T00:00:00Z').getUTCDay() + 6) % 7; + const hours = week[weekday]; + if (!hours) return null; + if (hours.closed) return ctx.tr('inspector.closed'); + if (!hours.open && !hours.close) return null; + return [ctx.fmtTime(hours.open), ctx.fmtTime(hours.close)].filter(Boolean).join(' – '); +} + +function placeFacts(place: Assignment['place'] & Partial, ctx: PdfDayContext): string[] { + const facts: string[] = []; + const duration = durationLabel(place.duration_minutes); + if (duration) facts.push(`${glyph('duration', 9)}${escHtml(duration)}`); + const price = Number(place.price); + if (Number.isFinite(price) && price > 0) { + facts.push( + `${glyph('price', 9)}${escHtml(formatMoney(price, place.currency || ctx.tripCurrency, ctx.locale))}` + ); + } + if (typeof place.rating_avg === 'number' && place.rating_avg > 0) { + const count = place.rating_count ? ` (${place.rating_count})` : ''; + facts.push(`${glyph('star', 9)}${place.rating_avg.toFixed(1)}${count}`); + } + for (const tag of place.tags || []) { + if (!tag.name) continue; + facts.push( + `${escHtml(tag.name)}` + ); + } + return facts; +} + +function placeDetails( + place: Assignment['place'] & Partial, + assignment: Assignment, + day: Day, + ctx: PdfDayContext +): string[] { + const details: string[] = []; + const hours = hoursOnDay(place, day, ctx); + if (hours) + details.push( + `${glyph('hours', 9)}${escHtml(ctx.tr('inspector.openingHours'))} ${escHtml(hours)}` + ); + if (place.phone) details.push(`${glyph('phone', 9)}${escHtml(place.phone)}`); + if (place.website) + details.push(`${glyph('web', 9)}${escHtml(websiteHost(place.website))}`); + if (place.email) details.push(`${glyph('mail', 9)}${escHtml(place.email)}`); + const people = (assignment.participants || []).map((p) => p.username).filter(Boolean); + if (people.length) { + details.push( + `${glyph('people', 9)}${escHtml(ctx.tr('inspector.participants'))}: ${escHtml(people.join(', '))}` + ); + } + return details; +} + +/** A planned place on the day's timeline, numbered like the stops on the map. */ +export function placeItem(assignment: Assignment, number: number, day: Day, ctx: PdfDayContext): string { + // The assignment carries a projection of its place; the rating, the e-mail, the + // hours and the reservation note are only on the trip's own place. + const place: Assignment['place'] & Partial = { + ...ctx.placesById.get(assignment.place.id), + ...assignment.place, + }; + const category = ctx.categories.find((c) => c.id === place.category_id); + const catColour = hexColour(category?.color, NEUTRAL); + const photo = ctx.photoOf(assignment.place); + const media = photo + ? `` + : `
    ${categoryIcon(category?.icon)}
    `; + const facts = placeFacts(place, ctx); + const details = placeDetails(place, assignment, day, ctx); + const hasPosition = place.lat != null && place.lng != null; + const notes = [place.notes, place.reservation_notes, assignment.notes].filter( + (value): value is string => typeof value === 'string' && value.trim() !== '' + ); + + const card = `
    + ${media} +
    +
    + ${escHtml(place.name)} + ${category ? `${escHtml(category.name)}` : ''} +
    + ${facts.length ? `
    ${facts.join('')}
    ` : ''} + ${place.address ? `
    ${glyph('pin')}${escHtml(place.address)}
    ` : ''} + ${ + hasPosition + ? `
    ${glyph('coords')}${Number(place.lat).toFixed(5)}, ${Number(place.lng).toFixed(5)}
    ` + : '' + } + ${place.description ? `
    ${ctx.markdown(place.description)}
    ` : ''} + ${notes.map((note) => `
    ${ctx.markdown(note)}
    `).join('')} + ${details.length ? `
    ${details.join('')}
    ` : ''} +
    +
    `; + const start = ctx.fmtTime(place.place_time); + const end = ctx.fmtTime(place.end_time); + return item('place', timeColumn(start, end), String(number), card); +} + +// ── Stays ───────────────────────────────────────────────────────────────── + +/** + * Where the day's night is spent. The day of arrival and the day of leaving get the + * full card with the time, the address and the booking code; the nights in between a + * quiet line, since the same hotel on every page is the plan's least news. + */ +export function staysBlock(stays: readonly Accommodation[], day: Day, ctx: PdfDayContext): string { + if (!stays.length) return ''; + const cards = stays.map((stay) => { + const isCheckIn = day.id === stay.start_day_id; + const isCheckOut = day.id === stay.end_day_id; + const name = stay.place_name || stay.reservation_title || ''; + const photo = safeImg(stay.place_image); + const media = `${photo ? `` : glyph(isCheckOut ? 'checkOut' : isCheckIn ? 'checkIn' : 'bed', 16)}`; + if (!isCheckIn && !isCheckOut) { + return `
    ${media}
    +
    ${escHtml(ctx.tr('reservations.meta.linkAccommodation'))}
    +
    ${escHtml(name)}
    +
    `; + } + const label = ctx.tr(isCheckIn ? 'reservations.meta.checkIn' : 'reservations.meta.checkOut'); + const time = ctx.fmtTime(isCheckIn ? stay.check_in : stay.check_out); + const extras = [ + isCheckIn && stay.confirmation + ? `${glyph('key', 9)}${escHtml(stay.confirmation)}` + : '', + ].filter(Boolean); + return `
    ${media}
    +
    ${escHtml(label)}${time ? ` ${escHtml(time)}` : ''}
    +
    ${escHtml(name)}
    + ${stay.place_address ? `
    ${escHtml(stay.place_address)}
    ` : ''} + ${stay.notes ? `
    ${escHtml(stay.notes)}
    ` : ''} + ${extras.length ? `
    ${extras.join('')}
    ` : ''} +
    `; + }); + return `
    ${cards.join('')}
    `; +} + +// ── Header ──────────────────────────────────────────────────────────────── + +export interface DayHeaderFacts { + stops: number; + distance: string | null; + cost: string | null; +} + +/** The day's header: its number in the day's colour, the date, the title and its figures. */ +export function dayHeader(day: Day, facts: DayHeaderFacts, ctx: PdfDayContext): string { + const n = day.day_number ?? 0; + const pills = [ + facts.stops > 0 ? `${glyph('pin', 9)}${facts.stops}` : '', + facts.distance ? `${glyph('route', 9)}${escHtml(facts.distance)}` : '', + facts.cost ? `${glyph('price', 9)}${facts.cost}` : '', + ].filter(Boolean); + return `
    + ${escHtml(ctx.tr('pdf.day'))}${n} +
    + ${day.date ? `
    ${escHtml(shortDate(day.date, ctx.locale))}
    ` : ''} +
    ${escHtml(day.title || ctx.tr('dayplan.dayN', { n }))}
    +
    + ${pills.length ? `
    ${pills.join('')}
    ` : ''} +
    `; +} + +// ── Photo strip ─────────────────────────────────────────────────────────── + +export interface StripPhoto { + url: string; + caption: string; +} + +/** + * The strip that opens a day: up to three of its photographed stops side by side, the + * first one widest, each named on a frosted label. Nothing for a day without photos. + */ +export function photoStrip(photos: readonly StripPhoto[]): string { + if (!photos.length) return ''; + return `
    ${photos + .map( + (p) => + `
    ${escHtml(p.caption)}
    ` + ) + .join('')}
    `; +} diff --git a/client/src/components/PDF/tripPdfHtml.ts b/client/src/components/PDF/tripPdfHtml.ts new file mode 100644 index 000000000..6f95ff251 --- /dev/null +++ b/client/src/components/PDF/tripPdfHtml.ts @@ -0,0 +1,82 @@ +/* + * The small text and URL helpers every part of the trip PDF builds its markup with. + * The document is an HTML string assembled outside React, so every value that comes + * from the trip goes through escHtml before it lands in it. + */ + +/** Text for element content or a double-quoted attribute. */ +export function escHtml(value: unknown): string { + if (value === null || value === undefined || value === '') return ''; + return String(value).replace(/&/g, '&').replace(//g, '>').replace(/"/g, '"'); +} + +/** + * The style attribute is decoded back into raw quotes before the CSS is parsed, so + * escHtml alone cannot stop a cover_image from closing the url() and appending its own + * declaration. Percent-encoding is transparent to the fetch. + */ +export function cssUrl(url: string): string { + return url.replace(/["'()\\\s]/g, (c) => '%' + (c.codePointAt(0) ?? 0).toString(16).padStart(2, '0')); +} + +/** + * A colour that goes into a style attribute built by string concatenation. Anything + * that is not a plain hex triple is not a colour and gets the fallback instead of a + * chance to close the declaration. + */ +export function hexColour(value: unknown, fallback: string): string { + return /^#[0-9a-f]{6}$/i.test(String(value)) ? String(value) : fallback; +} + +/** A path on this server as an absolute URL, so the print frame can load it. */ +export function absUrl(url: string | null | undefined): string | null { + if (!url) return null; + if (url.startsWith('http://') || url.startsWith('https://') || url.startsWith('data:')) return url; + return window.location.origin + (url.startsWith('/') ? '' : '/') + url; +} + +/** + * A picture the document may load: any web URL, the in-app place-photo proxy (it + * streams a JPEG under a path without an extension) and uploaded files with an image + * extension. Anything else prints as the fallback tile. + */ +export function safeImg(url: string | null | undefined): string | null { + if (!url) return null; + if (url.startsWith('https://') || url.startsWith('http://')) return url; + if (url.startsWith('/api/maps/place-photo/')) return absUrl(url); + return /\.(jpe?g|png|gif|webp|bmp|tiff?)(\?.*)?$/i.test(url) ? absUrl(url) : null; +} + +/** "Mon, 5 May" in the reader's language; empty for a day without a date. */ +export function shortDate(date: string | null | undefined, locale: string | undefined): string { + if (!date) return ''; + return new Date(date + 'T00:00:00Z').toLocaleDateString(locale, { + weekday: 'short', + day: 'numeric', + month: 'short', + timeZone: 'UTC', + }); +} + +/** "3 May – 24 May 2026" over the dated days, or null when none has a date. */ +export function longDateRange( + days: readonly { date?: string | null; day_number?: number }[], + locale: string | undefined +): string | null { + const dated = days.filter((d) => d.date).sort((a, b) => (a.day_number ?? 0) - (b.day_number ?? 0)); + if (!dated.length) return null; + const first = new Date(dated[0].date + 'T00:00:00Z'); + const last = new Date(dated[dated.length - 1].date + 'T00:00:00Z'); + const from = first.toLocaleDateString(locale, { day: 'numeric', month: 'long', timeZone: 'UTC' }); + const to = last.toLocaleDateString(locale, { day: 'numeric', month: 'long', year: 'numeric', timeZone: 'UTC' }); + return `${from} – ${to}`; +} + +/** The host of a website, which is what fits on a printed line. */ +export function websiteHost(url: string): string { + try { + return new URL(/^https?:\/\//i.test(url) ? url : `https://${url}`).host.replace(/^www\./, ''); + } catch { + return url; + } +} diff --git a/client/src/components/PDF/tripPdfIcons.ts b/client/src/components/PDF/tripPdfIcons.ts new file mode 100644 index 000000000..2030ce5c1 --- /dev/null +++ b/client/src/components/PDF/tripPdfIcons.ts @@ -0,0 +1,165 @@ +import { createElement } from 'react'; + +import { renderIconMarkup } from '../../utils/iconMarkup'; +import { getCategoryIcon } from '../shared/categoryIcons'; + +import { + AlertTriangle, + BedDouble, + Bike, + Bookmark, + Bus, + CableCar, + Camera, + Car, + CarTaxiFront, + Clock, + Coffee, + Crosshair, + FileText, + Flag, + Globe, + Heart, + Hourglass, + Info, + KeyRound, + Lightbulb, + LogIn, + LogOut, + Mail, + MapPin, + Navigation, + ParkingSquare, + Phone, + Plane, + Route, + Sailboat, + Ship, + ShoppingBag, + Star, + StickyNote, + Store, + Tag, + Ticket, + Train, + Users, + Utensils, + Wallet, + type LucideIcon, +} from 'lucide-react'; + +/* + * Every icon of the trip PDF as SVG markup. They draw in currentColor, so the + * stylesheet decides their colour, which keeps the palette in one place. + */ + +function iconSvg(Icon: LucideIcon, size: number, strokeWidth = 1.9): string { + return renderIconMarkup(createElement(Icon, { size, strokeWidth, color: 'currentColor', 'aria-hidden': 'true' })); +} + +/** The small glyphs of the facts, contact lines and stay rows. */ +const GLYPHS = { + pin: MapPin, + coords: Crosshair, + clock: Clock, + duration: Hourglass, + price: Wallet, + star: Star, + phone: Phone, + web: Globe, + mail: Mail, + hours: Store, + people: Users, + note: StickyNote, + tag: Tag, + route: Route, + bed: BedDouble, + checkIn: LogIn, + checkOut: LogOut, + key: KeyRound, +} satisfies Record; + +export type PdfGlyph = keyof typeof GLYPHS; + +export function glyph(name: PdfGlyph, size = 10): string { + return iconSvg(GLYPHS[name], size); +} + +const NOTE_ICONS: Record = { + FileText, + Info, + Clock, + MapPin, + Navigation, + Train, + Plane, + Bus, + Car, + Ship, + Coffee, + Ticket, + Star, + Heart, + Camera, + Flag, + Lightbulb, + AlertTriangle, + ShoppingBag, + Bookmark, +}; + +/** A day note's own icon, the note icon for one that names none. */ +export function noteIcon(iconId: string | null | undefined, size = 13): string { + return iconSvg((iconId && NOTE_ICONS[iconId]) || FileText, size); +} + +const BOOKING_ICONS: Record = { + flight: Plane, + train: Train, + bus: Bus, + car: Car, + taxi: CarTaxiFront, + bicycle: Bike, + cruise: Ship, + ferry: Sailboat, + cable_car: CableCar, + transport_other: Route, + restaurant: Utensils, + event: Ticket, + tour: Users, + parking: ParkingSquare, + other: FileText, +}; + +/** A booking's type icon; a type the export does not know gets the ticket. */ +export function bookingIcon(type: string | null | undefined, size = 14): string { + return iconSvg((type && BOOKING_ICONS[type]) || Ticket, size); +} + +/** The tint of each booking type, the same hues the day plan gives them. */ +const BOOKING_TINTS: Record = { + flight: '#3b82f6', + train: '#0891b2', + bus: '#059669', + car: '#64748b', + taxi: '#ca8a04', + bicycle: '#65a30d', + cruise: '#0284c7', + ferry: '#0d9488', + cable_car: '#dc2626', + transport_other: '#64748b', + restaurant: '#e11d48', + event: '#d97706', + tour: '#059669', + parking: '#2563eb', + other: '#64748b', +}; + +export function bookingTint(type: string | null | undefined): string { + return (type && BOOKING_TINTS[type]) || BOOKING_TINTS.flight; +} + +/** A category's icon for the tile a place without a photo prints. */ +export function categoryIcon(iconName: string | null | undefined, size = 22): string { + return iconSvg(getCategoryIcon(iconName), size, 1.7); +} diff --git a/client/src/components/PDF/tripPdfOverview.ts b/client/src/components/PDF/tripPdfOverview.ts new file mode 100644 index 000000000..b89b371ec --- /dev/null +++ b/client/src/components/PDF/tripPdfOverview.ts @@ -0,0 +1,119 @@ +import { cssUrl, escHtml } from './tripPdfHtml'; +import { glyph } from './tripPdfIcons'; + +/* + * The trip PDF's first pages: the cover, then the overview with the route map, every + * day at a glance and the list of bookings and stays with their codes. + */ + +type Translate = (key: string, params?: Record) => string; + +export interface CoverStat { + value: string; + label: string; +} + +export interface CoverInput { + title: string; + description: string | null; + range: string | null; + /** The cover photo, already checked to be one the document may load. */ + image: string | null; + /** The light TREK logo, absolute. */ + logo: string | null; + stats: readonly CoverStat[]; + tr: Translate; +} + +/** The cover: the trip's photo left bright, the title, the dates and its figures. */ +export function coverHtml({ title, description, range, image, logo, stats, tr }: CoverInput): string { + return `
    +
    +
    +
    + ${logo ? `TREK` : ''} + ${escHtml(tr('pdf.travelPlan'))} +
    +
    + ${range ? `
    ${escHtml(range)}
    ` : ''} +

    ${escHtml(title)}

    + ${description ? `

    ${escHtml(description)}

    ` : ''} +
    ${stats + .map( + (s) => + `
    ${escHtml(s.value)}
    ${escHtml(s.label)}
    ` + ) + .join('')}
    +
    +
    `; +} + +export interface GlanceRow { + number: number; + colour: string; + date: string; + title: string; + stops: number; + stay: string; + cost: string | null; +} + +/** Every day in one table: its colour, date and title, where the night is spent and what it costs. */ +export function glanceHtml(rows: readonly GlanceRow[], tr: Translate): string { + if (!rows.length) return ''; + const withCost = rows.some((r) => r.cost); + return `
    +
    ${escHtml(tr('pdf.atAGlance'))}
    + + + + + + + + ${withCost ? `` : ''} + + ${rows + .map( + (r) => ` + + + + + + ${withCost ? `` : ''} + ` + ) + .join('')} +
    ${escHtml(tr('pdf.day'))}${escHtml(tr('common.date'))}${escHtml(tr('pdf.plan'))}${escHtml(tr('pdf.stay'))}${glyph('pin', 9)}${escHtml(tr('pdf.costLabel'))}
    ${r.number}${escHtml(r.date)}${escHtml(r.title)}${escHtml(r.stay)}${r.stops || ''}${r.cost ?? ''}
    +
    `; +} + +export interface LedgerRow { + /** The type's icon, already markup. */ + icon: string; + /** The type's tint, a checked hex colour. */ + tint: string; + title: string; + /** Markup under the title: the route, the address or the booking's facts. */ + sub: string; + when: string; + code: string | null; +} + +/** The trip's bookings and stays in date order, each with the code to show at the desk. */ +export function ledgerHtml(rows: readonly LedgerRow[], tr: Translate): string { + if (!rows.length) return ''; + return `
    +
    ${escHtml(tr('pdf.bookings'))}
    +
    ${rows + .map( + (r) => `
    + ${r.icon} +
    ${escHtml(r.title)}
    ${r.sub ? `
    ${r.sub}
    ` : ''}
    +
    ${escHtml(r.when)}${r.code ? `
    ${glyph('key', 9)}${escHtml(r.code)}
    ` : ''}
    +
    ` + ) + .join('')}
    +
    `; +} diff --git a/client/src/components/PDF/tripPdfStyles.ts b/client/src/components/PDF/tripPdfStyles.ts new file mode 100644 index 000000000..8d23e8603 --- /dev/null +++ b/client/src/components/PDF/tripPdfStyles.ts @@ -0,0 +1,381 @@ +import geist400 from '@fontsource/geist-sans/files/geist-sans-latin-400-normal.woff2?url'; +import geist500 from '@fontsource/geist-sans/files/geist-sans-latin-500-normal.woff2?url'; +import geist600 from '@fontsource/geist-sans/files/geist-sans-latin-600-normal.woff2?url'; + +import { PDF_MARKDOWN_CSS } from './pdfMarkdown'; + +/* + * The trip PDF's stylesheet. A print document has a fixed palette rather than the + * reader's scheme, so its colours are declared once, as the custom properties at the + * top, and every rule below names them. The type follows the app: Poppins for words, + * Geist for figures, times and the small capitals. + * + * Every switch of the preview is one class on (pdfPreview.ts), so turning one + * over is instant and needs no rebuild: + * pdf-flow days run on instead of each starting a page + * pdf-large-text larger type and darker greys + * pdf-no-transport-notes the notes of flights, trains and rentals left out + * pdf-no-photos no photos on the places and stays + * pdf-no-overview no route map, day overview or booking list + * pdf-no-coords no coordinates under the addresses + * pdf-no-details no contact lines, opening hours or companions + */ +export function tripPdfCss(): string { + return ` + @font-face { font-family: 'Poppins'; font-style: normal; font-weight: 400; src: url('/fonts/Poppins-Regular.ttf') format('truetype'); } + @font-face { font-family: 'Poppins'; font-style: italic; font-weight: 400; src: url('/fonts/Poppins-Italic.ttf') format('truetype'); } + @font-face { font-family: 'Poppins'; font-style: normal; font-weight: 500; src: url('/fonts/Poppins-Medium.ttf') format('truetype'); } + @font-face { font-family: 'Poppins'; font-style: normal; font-weight: 600; src: url('/fonts/Poppins-SemiBold.ttf') format('truetype'); } + @font-face { font-family: 'Poppins'; font-style: normal; font-weight: 700; src: url('/fonts/Poppins-Bold.ttf') format('truetype'); } + @font-face { font-family: 'Geist PDF'; font-weight: 400; src: url('${geist400}') format('woff2'); } + @font-face { font-family: 'Geist PDF'; font-weight: 500; src: url('${geist500}') format('woff2'); } + @font-face { font-family: 'Geist PDF'; font-weight: 600; src: url('${geist600}') format('woff2'); } + + :root { + --ink: #17171c; + --ink-2: #3e3e47; + --ink-3: #6a6a74; + --ink-4: #9a9aa4; + --hair: #e7e5e0; + --paper: #ffffff; + --wash: #f6f5f2; + --wash-2: #eeede8; + --night: #141418; + --shade: rgba(10, 10, 14, 0.82); + --shade-mid: rgba(10, 10, 14, 0.35); + --shade-none: rgba(10, 10, 14, 0); + --glass: rgba(255, 255, 255, 0.13); + --glass-edge: rgba(255, 255, 255, 0.22); + --glass-dark: rgba(14, 14, 18, 0.42); + --on-night: rgba(255, 255, 255, 0.78); + --on-night-2: rgba(255, 255, 255, 0.56); + --gold: #b7791f; + --day: var(--ink); + --t: 1; + --sans: 'Poppins', system-ui, -apple-system, 'Segoe UI', sans-serif; + --num: 'Geist PDF', 'Poppins', system-ui, sans-serif; + --gutter: 14mm; + } + body.pdf-large-text { + --t: 1.3; + --ink-2: #2b2b33; + --ink-3: #4b4b55; + --ink-4: #62626c; + } + + @page { size: A4; margin: 12mm 0 14mm; } + @page :first { margin: 0; } + *, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; } + html, body { background: var(--paper); } + body { + font-family: var(--sans); color: var(--ink); + font-size: calc(9.5px * var(--t)); line-height: 1.5; + -webkit-print-color-adjust: exact; print-color-adjust: exact; + } + img { display: block; } + svg { flex-shrink: 0; } + .num { font-family: var(--num); font-variant-numeric: tabular-nums; } + .eyebrow { + font-family: var(--num); font-size: calc(7.5px * var(--t)); font-weight: 600; + letter-spacing: 0.14em; text-transform: uppercase; color: var(--ink-3); + } + .page-break { break-before: page; } + + @media screen { + html { background: var(--wash-2); } + .doc { max-width: 210mm; margin: 0 auto; background: var(--paper); box-shadow: 0 0 0 1px var(--hair); } + } + + /* ── Cover ───────────────────────────────────────────────── */ + .cover { + position: relative; height: 297mm; overflow: hidden; + background: var(--night); color: var(--paper); break-after: page; + } + .cover-bg { position: absolute; inset: 0; background-size: cover; background-position: center; } + .cover-plain .cover-bg { + background: radial-gradient(120% 80% at 85% 10%, var(--ink-2) 0%, var(--night) 60%); + } + .cover-shade { + position: absolute; inset: 0; + background: linear-gradient(180deg, var(--shade-mid) 0%, var(--shade-none) 24%, var(--shade-none) 40%, var(--shade) 100%); + } + .cover-top { + position: absolute; inset-block-start: 14mm; inset-inline: var(--gutter); + display: flex; align-items: center; justify-content: space-between; + } + .cover-top img { height: 22px; } + .cover-top .eyebrow { color: var(--on-night); } + .cover-body { position: absolute; inset-inline: var(--gutter); inset-block-end: 16mm; } + .cover-dates { font-family: var(--num); font-size: 11px; font-weight: 500; letter-spacing: 0.04em; color: var(--on-night); } + .cover-title { font-size: 46px; font-weight: 700; line-height: 1.04; letter-spacing: -0.02em; margin: 6px 0 10px; } + .cover-desc { max-width: 135mm; font-size: 12px; line-height: 1.6; color: var(--on-night); } + .cover-stats { display: grid; grid-template-columns: repeat(auto-fit, minmax(30mm, 1fr)); gap: 8px; margin-block-start: 10mm; } + .cover-stat { + background: var(--glass); border: 1px solid var(--glass-edge); border-radius: 16px; + padding: 12px 14px 11px; -webkit-backdrop-filter: blur(14px); backdrop-filter: blur(14px); + } + .cover-stat-num { font-family: var(--num); font-size: 20px; font-weight: 600; line-height: 1.1; font-variant-numeric: tabular-nums; } + .cover-stat-lbl { + font-family: var(--num); font-size: 7.5px; font-weight: 500; letter-spacing: 0.14em; + text-transform: uppercase; color: var(--on-night-2); margin-block-start: 5px; + } + + /* ── Overview: route map, the days at a glance, bookings and stays ─────── */ + .overview { padding: 2mm var(--gutter) 0; } + .pdf-no-overview .overview { display: none; } + .sec-head { display: flex; align-items: baseline; justify-content: space-between; gap: 12px; margin-block-end: 4mm; } + .sec-title { font-size: calc(17px * var(--t)); font-weight: 600; letter-spacing: -0.01em; } + .sec-block { break-inside: avoid; margin-block-end: 9mm; } + .trip-map { margin-block-end: 9mm; } + .trip-map-head { display: flex; align-items: baseline; justify-content: space-between; gap: 16px; margin-block-end: 4mm; } + .trip-map-title { font-size: calc(17px * var(--t)); font-weight: 600; letter-spacing: -0.01em; } + .trip-map-total { + font-family: var(--num); font-size: calc(9px * var(--t)); font-weight: 600; color: var(--ink-2); + background: var(--wash); border-radius: 99px; padding: 4px 10px; + } + .trip-map-note { font-size: 9px; font-weight: 600; color: var(--gold); margin: -2mm 0 3mm; } + .trip-map-svg { width: 100%; height: auto; border-radius: 16px; border: 1px solid var(--hair); display: block; overflow: hidden; } + .trip-map-legend { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 5px 14px; margin-block-start: 4mm; } + .trip-map-leg { display: flex; align-items: center; gap: 6px; min-width: 0; font-size: calc(8.5px * var(--t)); color: var(--ink-2); } + .trip-map-leg-name { flex: 1; min-width: 0; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } + .trip-map-dot { width: 8px; height: 8px; border-radius: 50%; } + .trip-map-leg-dist { font-family: var(--num); color: var(--ink-4); white-space: nowrap; } + .trip-map-credit { font-size: 7px; color: var(--ink-4); margin-block-start: 3mm; } + + .glance { width: 100%; border-collapse: collapse; font-size: calc(8.5px * var(--t)); } + .glance th { + font-family: var(--num); font-size: calc(7px * var(--t)); font-weight: 600; letter-spacing: 0.12em; + text-transform: uppercase; color: var(--ink-4); text-align: start; padding: 0 6px 6px; + border-block-end: 1px solid var(--hair); + } + .glance td { padding: 6px; border-block-end: 1px solid var(--wash-2); vertical-align: top; color: var(--ink-2); } + .glance tr { break-inside: avoid; } + .glance-day { display: inline-flex; align-items: center; justify-content: center; min-width: 22px; height: 18px; padding: 0 5px; border-radius: 6px; background: var(--day); color: var(--paper); font-family: var(--num); font-weight: 600; font-size: calc(8px * var(--t)); } + .glance-title { color: var(--ink); font-weight: 500; } + .glance .num, .glance-end { text-align: end; white-space: nowrap; } + + .ledger { display: grid; gap: 5px; } + .ledger-row { + display: grid; grid-template-columns: 26px 1fr auto; gap: 10px; align-items: center; + padding: 7px 10px; border: 1px solid var(--hair); border-radius: 12px; break-inside: avoid; + } + .ledger-icon { + width: 26px; height: 26px; border-radius: 8px; display: flex; align-items: center; justify-content: center; + background: color-mix(in srgb, var(--kind) 14%, var(--paper)); color: var(--kind); + } + .ledger-title { font-weight: 600; font-size: calc(9.5px * var(--t)); } + .ledger-sub { font-size: calc(8px * var(--t)); color: var(--ink-3); } + .ledger-when { font-family: var(--num); font-size: calc(8px * var(--t)); color: var(--ink-3); text-align: end; white-space: nowrap; } + + /* ── Day ─────────────────────────────────────────────────── */ + /* A real , so the browser repeats the day header on every page an + overflowing day spills onto (#1471); CSS table-header-group on a
    is not + repeated by Chromium's print engine. */ + .day-section { width: 100%; border-collapse: collapse; table-layout: fixed; } + .day-break { break-before: page; } + /* The first day always opens a page of its own, after the cover or the overview. */ + .day-first { break-before: page; } + .pdf-flow .day-break { break-before: auto; } + .pdf-flow .day-section + .day-section { margin-block-start: 8mm; } + /* Hold a flowing day together where it fits, so a header is never stranded at the + foot of a sheet with its content on the next one (#1471). */ + .pdf-flow .day-section { break-inside: avoid; page-break-inside: avoid; } + /* The gap under the header sits inside the repeated cell: a block-start padding on the + body is only painted on its first fragment (#1531). */ + .day-header > tr > td { padding: 0 var(--gutter) 5mm; } + .day-head { + display: flex; align-items: center; gap: 12px; padding-block: 3mm 3.5mm; + border-block-end: 1px solid var(--hair); position: relative; + } + .day-head::after { + content: ''; position: absolute; inset-inline-start: 0; inset-block-end: -1px; + width: 26mm; height: 2px; border-radius: 2px; background: var(--day); + } + .day-tag { + width: 42px; height: 42px; border-radius: 13px; background: var(--day); color: var(--paper); + display: flex; flex-direction: column; align-items: center; justify-content: center; flex-shrink: 0; + } + .day-tag-lbl { font-family: var(--num); font-size: 6.5px; font-weight: 600; letter-spacing: 0.14em; opacity: 0.85; } + .day-tag-num { font-family: var(--num); font-size: 17px; font-weight: 600; line-height: 1; } + .day-head-main { flex: 1; min-width: 0; } + .day-date { font-family: var(--num); font-size: calc(8px * var(--t)); font-weight: 600; letter-spacing: 0.1em; text-transform: uppercase; color: var(--ink-3); } + .day-title { font-size: calc(17px * var(--t)); font-weight: 600; line-height: 1.25; letter-spacing: -0.01em; } + .day-meta { display: flex; flex-wrap: wrap; justify-content: flex-end; gap: 5px; max-width: 70mm; } + .meta-pill, .day-cost { + display: inline-flex; align-items: center; gap: 4px; white-space: nowrap; + font-family: var(--num); font-size: calc(8px * var(--t)); font-weight: 600; color: var(--ink-2); + background: var(--wash); border-radius: 99px; padding: 4px 9px; + } + .meta-pill svg, .day-cost svg { color: var(--ink-4); } + .day-body { padding: 0 var(--gutter) 4mm; } + .day-intro { + margin-block-end: 4mm; padding: 9px 12px; border-radius: 12px; background: var(--wash); + font-size: calc(9px * var(--t)); color: var(--ink-2); white-space: pre-line; + } + + /* ── Photo strip ─────────────────────────────────────────── */ + .day-strip { display: grid; gap: 4px; height: 48mm; margin-block-end: 5mm; border-radius: 16px; overflow: hidden; } + .day-strip-1 { grid-template-columns: 1fr; } + .day-strip-2 { grid-template-columns: 3fr 2fr; } + .day-strip-3 { grid-template-columns: 2fr 1fr 1fr; } + .day-strip-photo { position: relative; min-width: 0; overflow: hidden; background: var(--wash-2); } + .day-strip-photo img { width: 100%; height: 100%; object-fit: cover; } + .glass-label { + position: absolute; inset-inline-start: 8px; inset-block-end: 8px; max-width: calc(100% - 16px); + padding: 4px 10px; border-radius: 99px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; + font-size: calc(8px * var(--t)); font-weight: 500; color: var(--paper); + background: var(--glass-dark); border: 1px solid var(--glass-edge); + -webkit-backdrop-filter: blur(10px); backdrop-filter: blur(10px); + } + .pdf-no-photos .day-strip { display: none; } + + /* ── Stays ───────────────────────────────────────────────── */ + .day-accommodations { display: grid; grid-template-columns: repeat(auto-fit, minmax(80mm, 1fr)); gap: 6px; margin-block-end: 5mm; } + .day-accommodation { + display: flex; gap: 10px; align-items: center; padding: 8px 10px; + border: 1px solid var(--hair); border-radius: 14px; break-inside: avoid; + } + .day-accommodation.stay-quiet { padding: 6px 10px; background: var(--wash); border-color: transparent; } + .stay-media { + width: 40px; height: 40px; border-radius: 11px; overflow: hidden; flex-shrink: 0; + display: flex; align-items: center; justify-content: center; + background: color-mix(in srgb, var(--day) 12%, var(--paper)); color: var(--day); + } + .stay-quiet .stay-media { width: 26px; height: 26px; border-radius: 8px; } + .stay-media img { width: 100%; height: 100%; object-fit: cover; } + .pdf-no-photos .stay-media img { display: none; } + .stay-main { flex: 1; min-width: 0; } + .stay-kicker { font-family: var(--num); font-size: calc(7.5px * var(--t)); font-weight: 600; letter-spacing: 0.12em; text-transform: uppercase; color: var(--day); } + .stay-name { font-size: calc(10.5px * var(--t)); font-weight: 600; line-height: 1.35; } + .stay-quiet .stay-name { font-size: calc(9px * var(--t)); font-weight: 500; } + .stay-line { font-size: calc(8.5px * var(--t)); color: var(--ink-3); } + .stay-extra { display: flex; flex-wrap: wrap; gap: 4px; margin-block-start: 4px; } + + /* ── Timeline ────────────────────────────────────────────── */ + .timeline { list-style: none; } + .tl-item { display: grid; grid-template-columns: 13mm 22px minmax(0, 1fr); column-gap: 8px; break-inside: avoid; } + .tl-time { text-align: end; padding-block-start: 11px; font-family: var(--num); font-variant-numeric: tabular-nums; } + .tl-start { display: block; font-size: calc(9.5px * var(--t)); font-weight: 600; color: var(--ink); } + .tl-end { display: block; font-size: calc(8px * var(--t)); color: var(--ink-4); } + .tl-rail { position: relative; display: flex; justify-content: center; } + .tl-rail::before { + content: ''; position: absolute; inset-block: 0; inset-inline-start: calc(50% - 0.75px); width: 1.5px; + background: color-mix(in srgb, var(--day) 26%, var(--paper)); + } + .tl-item:first-child .tl-rail::before { inset-block-start: 14px; } + .tl-item:last-child .tl-rail::before { inset-block-end: auto; height: 14px; } + .tl-item:only-child .tl-rail::before { display: none; } + .tl-marker { + position: relative; margin-block-start: 8px; width: 22px; height: 22px; border-radius: 50%; + display: flex; align-items: center; justify-content: center; + background: var(--paper); border: 1.5px solid var(--day); color: var(--day); + font-family: var(--num); font-size: calc(8.5px * var(--t)); font-weight: 600; + } + .tl-place .tl-marker { background: var(--day); color: var(--paper); } + .tl-booking .tl-marker { border-color: var(--kind); color: var(--kind); } + .tl-note .tl-marker { width: 10px; height: 10px; margin-block-start: 13px; background: var(--wash-2); border-color: var(--wash-2); } + .tl-body { padding-block: 3px 7px; min-width: 0; } + .empty-day { padding: 10mm 0; text-align: center; color: var(--ink-4); font-size: calc(9px * var(--t)); } + + /* ── Place ───────────────────────────────────────────────── */ + .place-card { + display: flex; gap: 11px; padding: 10px; border: 1px solid var(--hair); border-radius: 14px; + background: var(--paper); break-inside: avoid; + } + .place-thumb, .place-thumb-fallback { width: 74px; height: 74px; border-radius: 11px; flex-shrink: 0; } + .place-thumb { object-fit: cover; } + .place-thumb-fallback { + display: flex; align-items: center; justify-content: center; + background: color-mix(in srgb, var(--cat) 14%, var(--paper)); color: var(--cat); + } + .pdf-no-photos .place-thumb, .pdf-no-photos .place-thumb-fallback { display: none; } + .place-info { flex: 1; min-width: 0; } + .place-name-row { display: flex; align-items: flex-start; gap: 8px; } + .place-name { flex: 1; font-size: calc(12px * var(--t)); font-weight: 600; line-height: 1.3; letter-spacing: -0.005em; } + .cat-badge { + display: inline-flex; align-items: center; gap: 4px; white-space: nowrap; flex-shrink: 0; + font-family: var(--num); font-size: calc(7.5px * var(--t)); font-weight: 600; + border-radius: 99px; padding: 3px 8px; + background: color-mix(in srgb, var(--cat) 13%, var(--paper)); + color: color-mix(in srgb, var(--cat) 78%, var(--ink)); + } + .facts { display: flex; flex-wrap: wrap; gap: 4px; margin-block-start: 5px; } + .chip { + display: inline-flex; align-items: center; gap: 4px; white-space: nowrap; + font-family: var(--num); font-size: calc(8px * var(--t)); font-weight: 500; color: var(--ink-2); + background: var(--wash); border-radius: 99px; padding: 2px 8px; + } + .chip svg { color: var(--ink-4); } + .chip-rating { color: var(--gold); } + .chip-rating svg { color: var(--gold); fill: var(--gold); } + .chip-tag { background: color-mix(in srgb, var(--tag) 12%, var(--paper)); color: color-mix(in srgb, var(--tag) 75%, var(--ink)); } + .chip-tag::before { content: ''; width: 6px; height: 6px; border-radius: 50%; background: var(--tag); } + .code-chip { + display: inline-flex; align-items: center; gap: 4px; white-space: nowrap; + font-family: var(--num); font-size: calc(8px * var(--t)); font-weight: 600; letter-spacing: 0.04em; + color: var(--ink); background: var(--wash-2); border-radius: 6px; padding: 2px 7px; + } + .code-chip svg { color: var(--ink-3); } + .info-row { display: flex; align-items: flex-start; gap: 5px; margin-block-start: 4px; } + .info-row svg { color: var(--ink-4); margin-block-start: 1px; } + .info-text { font-size: calc(8.5px * var(--t)); color: var(--ink-2); line-height: 1.5; min-width: 0; } + .info-text.muted { color: var(--ink-3); } + .info-spacer { display: none; } + .coords { font-family: var(--num); color: var(--ink-4); font-size: calc(8px * var(--t)); } + .pdf-no-coords .coords { display: none; } + .place-text { margin-block-start: 5px; font-size: calc(9px * var(--t)); color: var(--ink-2); line-height: 1.55; } + .place-text .info-row { margin: 0; } + .place-text .info-text { font-size: inherit; color: inherit; } + .place-note { + margin-block-start: 6px; padding: 6px 9px; border-radius: 9px; background: var(--wash); + font-size: calc(8.5px * var(--t)); color: var(--ink-2); + } + .place-note .info-row { margin: 0; } + .place-note .info-text { color: inherit; } + .details { display: flex; flex-wrap: wrap; gap: 3px 12px; margin-block-start: 6px; } + .detail { display: inline-flex; align-items: center; gap: 4px; font-size: calc(8px * var(--t)); color: var(--ink-3); } + .detail svg { color: var(--ink-4); } + .pdf-no-details .details { display: none; } + ${PDF_MARKDOWN_CSS} + + /* ── Bookings and notes ──────────────────────────────────── */ + .note-card { + display: flex; gap: 10px; align-items: flex-start; padding: 9px 11px; border-radius: 14px; + break-inside: avoid; background: var(--wash); + } + .booking-card { + background: color-mix(in srgb, var(--kind) 6%, var(--paper)); + border: 1px solid color-mix(in srgb, var(--kind) 20%, var(--paper)); + } + .note-icon { + width: 26px; height: 26px; border-radius: 8px; flex-shrink: 0; + display: flex; align-items: center; justify-content: center; color: var(--ink-3); background: var(--paper); + } + .booking-card .note-icon { background: var(--kind); color: var(--paper); } + .note-tinted { border-inline-start: 3px solid var(--note); } + .note-tinted .note-icon { color: var(--note); } + .note-body { flex: 1; min-width: 0; } + .note-kicker { font-family: var(--num); font-size: calc(7.5px * var(--t)); font-weight: 600; letter-spacing: 0.12em; text-transform: uppercase; color: var(--kind, var(--ink-3)); } + .note-text { font-size: calc(9.5px * var(--t)); color: var(--ink); line-height: 1.5; } + .booking-card .note-text { font-size: calc(11px * var(--t)); font-weight: 600; line-height: 1.35; } + .note-time { font-size: calc(8.5px * var(--t)); color: var(--ink-3); margin-block-start: 2px; } + .note-line { display: flex; flex-wrap: wrap; align-items: center; gap: 4px; margin-block-start: 4px; } + .note-line .route { font-family: var(--num); font-size: calc(9px * var(--t)); font-weight: 600; color: var(--ink); margin-inline-end: 2px; } + .booking-card .chip { background: var(--paper); } + .note-extra { display: flex; flex-wrap: wrap; gap: 4px; margin-block-start: 5px; } + .transport-note { font-style: italic; white-space: pre-line; } + .pdf-no-transport-notes .transport-note { display: none; } + + /* ── Plugin sections ─────────────────────────────────────── */ + .plugin-sections { padding: 2mm var(--gutter) 4mm; } + .plugin-section { margin-block-end: 6mm; break-inside: avoid; } + .plugin-section-title { font-size: calc(13px * var(--t)); font-weight: 600; margin-block-end: 2mm; padding-block-end: 2mm; border-block-end: 1px solid var(--hair); } + .plugin-section-text { font-size: calc(9.5px * var(--t)); color: var(--ink-2); line-height: 1.55; margin-block-end: 5px; } + .plugin-section-table { width: 100%; border-collapse: collapse; margin-block-start: 6px; } + .plugin-section-table th { font-family: var(--num); font-size: calc(7.5px * var(--t)); font-weight: 600; color: var(--ink-4); text-transform: uppercase; letter-spacing: 0.1em; text-align: start; padding: 4px 8px; border-block-end: 1px solid var(--hair); } + .plugin-section-table td { font-size: calc(9px * var(--t)); color: var(--ink-2); padding: 4px 8px; border-block-end: 1px solid var(--wash-2); } + + .doc-end { display: flex; align-items: center; justify-content: center; gap: 6px; padding: 8mm 0 4mm; color: var(--ink-4); font-size: 7.5px; letter-spacing: 0.06em; } + .doc-end img { height: 10px; opacity: 0.55; } +`; +} diff --git a/shared/src/i18n/ar/pdf.ts b/shared/src/i18n/ar/pdf.ts index 3687a1617..b405401d3 100644 --- a/shared/src/i18n/ar/pdf.ts +++ b/shared/src/i18n/ar/pdf.ts @@ -15,5 +15,13 @@ const pdf: TranslationStrings = { 'pdf.mapTitle': 'نظرة عامة على المسار', 'pdf.distanceLabel': 'المسافة', 'pdf.mapCredit': 'حدود الدول: geoBoundaries (CC BY 4.0)', + 'pdf.showOverview': 'نظرة عامة', + 'pdf.showPhotos': 'الصور', + 'pdf.showDetails': 'التواصل وساعات العمل', + 'pdf.atAGlance': 'لمحة سريعة', + 'pdf.bookings': 'الحجوزات والإقامات', + 'pdf.day': 'اليوم', + 'pdf.stay': 'الإقامة', + 'pdf.plan': 'الخطة', }; export default pdf; diff --git a/shared/src/i18n/az/pdf.ts b/shared/src/i18n/az/pdf.ts index f3dec3e9b..94b9fc378 100644 --- a/shared/src/i18n/az/pdf.ts +++ b/shared/src/i18n/az/pdf.ts @@ -15,6 +15,14 @@ const pdf: TranslationStrings = { 'pdf.mapTitle': 'Marşrutun icmalı', 'pdf.distanceLabel': 'Məsafə', 'pdf.mapCredit': 'Ölkə sərhədləri: geoBoundaries (CC BY 4.0)', + 'pdf.showOverview': 'İcmal', + 'pdf.showPhotos': 'Fotolar', + 'pdf.showDetails': 'Əlaqə və iş saatları', + 'pdf.atAGlance': 'Bir baxışda', + 'pdf.bookings': 'Rezervasiyalar və yerləşmə', + 'pdf.day': 'Gün', + 'pdf.stay': 'Yerləşmə', + 'pdf.plan': 'Plan', // same-as-en }; export default pdf; diff --git a/shared/src/i18n/br/pdf.ts b/shared/src/i18n/br/pdf.ts index a79a28772..b4709e224 100644 --- a/shared/src/i18n/br/pdf.ts +++ b/shared/src/i18n/br/pdf.ts @@ -15,5 +15,13 @@ const pdf: TranslationStrings = { 'pdf.mapTitle': 'Visão geral da rota', 'pdf.distanceLabel': 'Distância', 'pdf.mapCredit': 'Contornos dos países: geoBoundaries (CC BY 4.0)', + 'pdf.showOverview': 'Visão geral', + 'pdf.showPhotos': 'Fotos', + 'pdf.showDetails': 'Contato e horários', + 'pdf.atAGlance': 'Em resumo', + 'pdf.bookings': 'Reservas e hospedagens', + 'pdf.day': 'Dia', + 'pdf.stay': 'Hospedagem', + 'pdf.plan': 'Plano', }; export default pdf; diff --git a/shared/src/i18n/ca/pdf.ts b/shared/src/i18n/ca/pdf.ts index e809be988..b512dfdcc 100644 --- a/shared/src/i18n/ca/pdf.ts +++ b/shared/src/i18n/ca/pdf.ts @@ -15,5 +15,13 @@ const pdf: TranslationStrings = { 'pdf.mapTitle': 'Resum de la ruta', 'pdf.distanceLabel': 'Distància', 'pdf.mapCredit': 'Contorns dels països: geoBoundaries (CC BY 4.0)', + 'pdf.showOverview': 'Resum', + 'pdf.showPhotos': 'Fotos', + 'pdf.showDetails': 'Contacte i horaris', + 'pdf.atAGlance': 'D\'un cop d\'ull', + 'pdf.bookings': 'Reserves i allotjaments', + 'pdf.day': 'Dia', + 'pdf.stay': 'Allotjament', + 'pdf.plan': 'Pla', }; export default pdf; diff --git a/shared/src/i18n/cs/pdf.ts b/shared/src/i18n/cs/pdf.ts index 66238e842..11c59763c 100644 --- a/shared/src/i18n/cs/pdf.ts +++ b/shared/src/i18n/cs/pdf.ts @@ -15,5 +15,13 @@ const pdf: TranslationStrings = { 'pdf.mapTitle': 'Přehled trasy', 'pdf.distanceLabel': 'Vzdálenost', 'pdf.mapCredit': 'Obrysy zemí: geoBoundaries (CC BY 4.0)', + 'pdf.showOverview': 'Přehled', + 'pdf.showPhotos': 'Fotky', + 'pdf.showDetails': 'Kontakt a otevírací doba', + 'pdf.atAGlance': 'Na první pohled', + 'pdf.bookings': 'Rezervace a ubytování', + 'pdf.day': 'Den', + 'pdf.stay': 'Ubytování', + 'pdf.plan': 'Plán', }; export default pdf; diff --git a/shared/src/i18n/de/pdf.ts b/shared/src/i18n/de/pdf.ts index ad98fe06d..922d32747 100644 --- a/shared/src/i18n/de/pdf.ts +++ b/shared/src/i18n/de/pdf.ts @@ -15,5 +15,13 @@ const pdf: TranslationStrings = { 'pdf.mapTitle': 'Routenübersicht', 'pdf.distanceLabel': 'Strecke', 'pdf.mapCredit': 'Ländergrenzen: geoBoundaries (CC BY 4.0)', + 'pdf.showOverview': 'Übersicht', + 'pdf.showPhotos': 'Fotos', + 'pdf.showDetails': 'Kontakt & Öffnungszeiten', + 'pdf.atAGlance': 'Auf einen Blick', + 'pdf.bookings': 'Buchungen & Unterkünfte', + 'pdf.day': 'Tag', + 'pdf.stay': 'Unterkunft', + 'pdf.plan': 'Plan', // same-as-en }; export default pdf; diff --git a/shared/src/i18n/en/pdf.ts b/shared/src/i18n/en/pdf.ts index cb8877806..fd6452c3b 100644 --- a/shared/src/i18n/en/pdf.ts +++ b/shared/src/i18n/en/pdf.ts @@ -15,5 +15,13 @@ const pdf: TranslationStrings = { 'pdf.mapTitle': 'Route overview', 'pdf.distanceLabel': 'Distance', 'pdf.mapCredit': 'Country outlines: geoBoundaries (CC BY 4.0)', + 'pdf.showOverview': 'Overview', + 'pdf.showPhotos': 'Photos', + 'pdf.showDetails': 'Contact & hours', + 'pdf.atAGlance': 'At a glance', + 'pdf.bookings': 'Bookings & stays', + 'pdf.day': 'Day', + 'pdf.stay': 'Stay', + 'pdf.plan': 'Plan', }; export default pdf; diff --git a/shared/src/i18n/es/pdf.ts b/shared/src/i18n/es/pdf.ts index cd8385373..912109a7b 100644 --- a/shared/src/i18n/es/pdf.ts +++ b/shared/src/i18n/es/pdf.ts @@ -15,5 +15,13 @@ const pdf: TranslationStrings = { 'pdf.mapTitle': 'Resumen de la ruta', 'pdf.distanceLabel': 'Distancia', 'pdf.mapCredit': 'Contornos de países: geoBoundaries (CC BY 4.0)', + 'pdf.showOverview': 'Resumen', + 'pdf.showPhotos': 'Fotos', + 'pdf.showDetails': 'Contacto y horarios', + 'pdf.atAGlance': 'De un vistazo', + 'pdf.bookings': 'Reservas y alojamientos', + 'pdf.day': 'Día', + 'pdf.stay': 'Alojamiento', + 'pdf.plan': 'Plan', // same-as-en }; export default pdf; diff --git a/shared/src/i18n/et/pdf.ts b/shared/src/i18n/et/pdf.ts index 8d20ae48e..91d38ceaa 100644 --- a/shared/src/i18n/et/pdf.ts +++ b/shared/src/i18n/et/pdf.ts @@ -15,5 +15,13 @@ const pdf: TranslationStrings = { 'pdf.mapTitle': 'Marsruudi ülevaade', 'pdf.distanceLabel': 'Vahemaa', 'pdf.mapCredit': 'Riigipiirid: geoBoundaries (CC BY 4.0)', + 'pdf.showOverview': 'Ülevaade', + 'pdf.showPhotos': 'Fotod', + 'pdf.showDetails': 'Kontakt ja lahtiolekuajad', + 'pdf.atAGlance': 'Ühe pilguga', + 'pdf.bookings': 'Broneeringud ja majutus', + 'pdf.day': 'Päev', + 'pdf.stay': 'Majutus', + 'pdf.plan': 'Plaan', }; export default pdf; diff --git a/shared/src/i18n/fr/pdf.ts b/shared/src/i18n/fr/pdf.ts index 5a381a7a2..8ad82bd94 100644 --- a/shared/src/i18n/fr/pdf.ts +++ b/shared/src/i18n/fr/pdf.ts @@ -15,5 +15,13 @@ const pdf: TranslationStrings = { 'pdf.mapTitle': "Aperçu de l'itinéraire", 'pdf.distanceLabel': 'Distance', // same-as-en 'pdf.mapCredit': 'Contours des pays : geoBoundaries (CC BY 4.0)', + 'pdf.showOverview': 'Aperçu', + 'pdf.showPhotos': 'Photos', // same-as-en + 'pdf.showDetails': 'Contact et horaires', + 'pdf.atAGlance': 'En un coup d\'œil', + 'pdf.bookings': 'Réservations et hébergements', + 'pdf.day': 'Jour', + 'pdf.stay': 'Hébergement', + 'pdf.plan': 'Programme', }; export default pdf; diff --git a/shared/src/i18n/gr/pdf.ts b/shared/src/i18n/gr/pdf.ts index 3facd2355..fc34a980c 100644 --- a/shared/src/i18n/gr/pdf.ts +++ b/shared/src/i18n/gr/pdf.ts @@ -15,5 +15,13 @@ const pdf: TranslationStrings = { 'pdf.mapTitle': 'Επισκόπηση διαδρομής', 'pdf.distanceLabel': 'Απόσταση', 'pdf.mapCredit': 'Περιγράμματα χωρών: geoBoundaries (CC BY 4.0)', + 'pdf.showOverview': 'Επισκόπηση', + 'pdf.showPhotos': 'Φωτογραφίες', + 'pdf.showDetails': 'Επικοινωνία και ωράριο', + 'pdf.atAGlance': 'Με μια ματιά', + 'pdf.bookings': 'Κρατήσεις και διαμονή', + 'pdf.day': 'Ημέρα', + 'pdf.stay': 'Διαμονή', + 'pdf.plan': 'Πρόγραμμα', }; export default pdf; diff --git a/shared/src/i18n/he/pdf.ts b/shared/src/i18n/he/pdf.ts index 993b459d7..2ab248582 100644 --- a/shared/src/i18n/he/pdf.ts +++ b/shared/src/i18n/he/pdf.ts @@ -15,6 +15,14 @@ const pdf: TranslationStrings = { 'pdf.mapTitle': 'סקירת המסלול', 'pdf.distanceLabel': 'מרחק', 'pdf.mapCredit': 'גבולות מדינות: geoBoundaries ‏(CC BY 4.0)', + 'pdf.showOverview': 'סקירה', + 'pdf.showPhotos': 'תמונות', + 'pdf.showDetails': 'פרטי קשר ושעות פתיחה', + 'pdf.atAGlance': 'במבט חטוף', + 'pdf.bookings': 'הזמנות ולינה', + 'pdf.day': 'יום', + 'pdf.stay': 'לינה', + 'pdf.plan': 'תוכנית', }; export default pdf; diff --git a/shared/src/i18n/hu/pdf.ts b/shared/src/i18n/hu/pdf.ts index 40950a31d..3940dd2aa 100644 --- a/shared/src/i18n/hu/pdf.ts +++ b/shared/src/i18n/hu/pdf.ts @@ -15,5 +15,13 @@ const pdf: TranslationStrings = { 'pdf.mapTitle': 'Útvonal áttekintése', 'pdf.distanceLabel': 'Távolság', 'pdf.mapCredit': 'Országhatárok: geoBoundaries (CC BY 4.0)', + 'pdf.showOverview': 'Áttekintés', + 'pdf.showPhotos': 'Fotók', + 'pdf.showDetails': 'Elérhetőség és nyitvatartás', + 'pdf.atAGlance': 'Egy pillantásra', + 'pdf.bookings': 'Foglalások és szállások', + 'pdf.day': 'Nap', + 'pdf.stay': 'Szállás', + 'pdf.plan': 'Program', }; export default pdf; diff --git a/shared/src/i18n/id/pdf.ts b/shared/src/i18n/id/pdf.ts index 74617a97b..d90e60c32 100644 --- a/shared/src/i18n/id/pdf.ts +++ b/shared/src/i18n/id/pdf.ts @@ -15,5 +15,13 @@ const pdf: TranslationStrings = { 'pdf.mapTitle': 'Ringkasan rute', 'pdf.distanceLabel': 'Jarak', 'pdf.mapCredit': 'Garis batas negara: geoBoundaries (CC BY 4.0)', + 'pdf.showOverview': 'Ringkasan', + 'pdf.showPhotos': 'Foto', + 'pdf.showDetails': 'Kontak & jam buka', + 'pdf.atAGlance': 'Sekilas', + 'pdf.bookings': 'Pemesanan & penginapan', + 'pdf.day': 'Hari', + 'pdf.stay': 'Penginapan', + 'pdf.plan': 'Rencana', }; export default pdf; diff --git a/shared/src/i18n/it/pdf.ts b/shared/src/i18n/it/pdf.ts index 17d6e7c60..af27a5afc 100644 --- a/shared/src/i18n/it/pdf.ts +++ b/shared/src/i18n/it/pdf.ts @@ -15,5 +15,13 @@ const pdf: TranslationStrings = { 'pdf.mapTitle': 'Panoramica del percorso', 'pdf.distanceLabel': 'Distanza', 'pdf.mapCredit': 'Confini dei paesi: geoBoundaries (CC BY 4.0)', + 'pdf.showOverview': 'Panoramica', + 'pdf.showPhotos': 'Foto', + 'pdf.showDetails': 'Contatti e orari', + 'pdf.atAGlance': 'In sintesi', + 'pdf.bookings': 'Prenotazioni e alloggi', + 'pdf.day': 'Giorno', + 'pdf.stay': 'Alloggio', + 'pdf.plan': 'Programma', }; export default pdf; diff --git a/shared/src/i18n/ja/pdf.ts b/shared/src/i18n/ja/pdf.ts index f1ca038e8..1cbcb9b52 100644 --- a/shared/src/i18n/ja/pdf.ts +++ b/shared/src/i18n/ja/pdf.ts @@ -15,5 +15,13 @@ const pdf: TranslationStrings = { 'pdf.mapTitle': 'ルート概要', 'pdf.distanceLabel': '距離', 'pdf.mapCredit': '国境線: geoBoundaries (CC BY 4.0)', + 'pdf.showOverview': '概要', + 'pdf.showPhotos': '写真', + 'pdf.showDetails': '連絡先と営業時間', + 'pdf.atAGlance': '一覧', + 'pdf.bookings': '予約と宿泊', + 'pdf.day': '日目', + 'pdf.stay': '宿泊', + 'pdf.plan': '予定', }; export default pdf; diff --git a/shared/src/i18n/ko/pdf.ts b/shared/src/i18n/ko/pdf.ts index 4b8c7ac42..6875287e7 100644 --- a/shared/src/i18n/ko/pdf.ts +++ b/shared/src/i18n/ko/pdf.ts @@ -15,5 +15,13 @@ const pdf: TranslationStrings = { 'pdf.mapTitle': '경로 개요', 'pdf.distanceLabel': '거리', 'pdf.mapCredit': '국가 윤곽: geoBoundaries (CC BY 4.0)', + 'pdf.showOverview': '개요', + 'pdf.showPhotos': '사진', + 'pdf.showDetails': '연락처 및 영업시간', + 'pdf.atAGlance': '한눈에 보기', + 'pdf.bookings': '예약 및 숙소', + 'pdf.day': '일차', + 'pdf.stay': '숙소', + 'pdf.plan': '일정', }; export default pdf; diff --git a/shared/src/i18n/nl/pdf.ts b/shared/src/i18n/nl/pdf.ts index 15e3d2214..0171d418a 100644 --- a/shared/src/i18n/nl/pdf.ts +++ b/shared/src/i18n/nl/pdf.ts @@ -15,5 +15,13 @@ const pdf: TranslationStrings = { 'pdf.mapTitle': 'Routeoverzicht', 'pdf.distanceLabel': 'Afstand', 'pdf.mapCredit': 'Landcontouren: geoBoundaries (CC BY 4.0)', + 'pdf.showOverview': 'Overzicht', + 'pdf.showPhotos': 'Foto\'s', + 'pdf.showDetails': 'Contact en openingstijden', + 'pdf.atAGlance': 'In één oogopslag', + 'pdf.bookings': 'Boekingen en verblijven', + 'pdf.day': 'Dag', + 'pdf.stay': 'Verblijf', + 'pdf.plan': 'Planning', }; export default pdf; diff --git a/shared/src/i18n/pl/pdf.ts b/shared/src/i18n/pl/pdf.ts index cc9fa85d5..9f51c52d2 100644 --- a/shared/src/i18n/pl/pdf.ts +++ b/shared/src/i18n/pl/pdf.ts @@ -15,5 +15,13 @@ const pdf: TranslationStrings = { 'pdf.mapTitle': 'Przegląd trasy', 'pdf.distanceLabel': 'Dystans', 'pdf.mapCredit': 'Kontury krajów: geoBoundaries (CC BY 4.0)', + 'pdf.showOverview': 'Przegląd', + 'pdf.showPhotos': 'Zdjęcia', + 'pdf.showDetails': 'Kontakt i godziny otwarcia', + 'pdf.atAGlance': 'W skrócie', + 'pdf.bookings': 'Rezerwacje i noclegi', + 'pdf.day': 'Dzień', + 'pdf.stay': 'Nocleg', + 'pdf.plan': 'Plan', // same-as-en }; export default pdf; diff --git a/shared/src/i18n/ru/pdf.ts b/shared/src/i18n/ru/pdf.ts index c2571be80..9fa259d6c 100644 --- a/shared/src/i18n/ru/pdf.ts +++ b/shared/src/i18n/ru/pdf.ts @@ -15,5 +15,13 @@ const pdf: TranslationStrings = { 'pdf.mapTitle': 'Обзор маршрута', 'pdf.distanceLabel': 'Расстояние', 'pdf.mapCredit': 'Контуры стран: geoBoundaries (CC BY 4.0)', + 'pdf.showOverview': 'Обзор', + 'pdf.showPhotos': 'Фото', + 'pdf.showDetails': 'Контакты и часы работы', + 'pdf.atAGlance': 'Коротко', + 'pdf.bookings': 'Бронирования и жильё', + 'pdf.day': 'День', + 'pdf.stay': 'Жильё', + 'pdf.plan': 'План', }; export default pdf; diff --git a/shared/src/i18n/sk/pdf.ts b/shared/src/i18n/sk/pdf.ts index 3feb9101f..4435d06f4 100644 --- a/shared/src/i18n/sk/pdf.ts +++ b/shared/src/i18n/sk/pdf.ts @@ -15,5 +15,13 @@ const pdf: TranslationStrings = { 'pdf.mapTitle': 'Prehľad trasy', 'pdf.distanceLabel': 'Vzdialenosť', 'pdf.mapCredit': 'Obrysy krajín: geoBoundaries (CC BY 4.0)', + 'pdf.showOverview': 'Prehľad', + 'pdf.showPhotos': 'Fotky', + 'pdf.showDetails': 'Kontakt a otváracie hodiny', + 'pdf.atAGlance': 'Na prvý pohľad', + 'pdf.bookings': 'Rezervácie a ubytovanie', + 'pdf.day': 'Deň', + 'pdf.stay': 'Ubytovanie', + 'pdf.plan': 'Plán', }; export default pdf; diff --git a/shared/src/i18n/sv/pdf.ts b/shared/src/i18n/sv/pdf.ts index 8b4395762..8701a0995 100644 --- a/shared/src/i18n/sv/pdf.ts +++ b/shared/src/i18n/sv/pdf.ts @@ -15,5 +15,13 @@ const pdf: TranslationStrings = { 'pdf.mapTitle': 'Ruttöversikt', 'pdf.distanceLabel': 'Sträcka', 'pdf.mapCredit': 'Landskonturer: geoBoundaries (CC BY 4.0)', + 'pdf.showOverview': 'Översikt', + 'pdf.showPhotos': 'Foton', + 'pdf.showDetails': 'Kontakt och öppettider', + 'pdf.atAGlance': 'I korthet', + 'pdf.bookings': 'Bokningar och boenden', + 'pdf.day': 'Dag', + 'pdf.stay': 'Boende', + 'pdf.plan': 'Plan', // same-as-en }; export default pdf; diff --git a/shared/src/i18n/th/pdf.ts b/shared/src/i18n/th/pdf.ts index 17dd96e9c..2f1acfc72 100644 --- a/shared/src/i18n/th/pdf.ts +++ b/shared/src/i18n/th/pdf.ts @@ -14,5 +14,13 @@ const pdf: TranslationStrings = { 'pdf.mapTitle': 'ภาพรวมเส้นทาง', 'pdf.distanceLabel': 'ระยะทาง', 'pdf.mapCredit': 'ขอบเขตประเทศ: geoBoundaries (CC BY 4.0)', + 'pdf.showOverview': 'ภาพรวม', + 'pdf.showPhotos': 'รูปภาพ', + 'pdf.showDetails': 'ติดต่อและเวลาทำการ', + 'pdf.atAGlance': 'สรุปโดยย่อ', + 'pdf.bookings': 'การจองและที่พัก', + 'pdf.day': 'วัน', + 'pdf.stay': 'ที่พัก', + 'pdf.plan': 'แผน', }; export default pdf; diff --git a/shared/src/i18n/tr/pdf.ts b/shared/src/i18n/tr/pdf.ts index 5b47bacc5..a723e863c 100644 --- a/shared/src/i18n/tr/pdf.ts +++ b/shared/src/i18n/tr/pdf.ts @@ -15,5 +15,13 @@ const pdf: TranslationStrings = { 'pdf.mapTitle': 'Rota genel görünümü', 'pdf.distanceLabel': 'Mesafe', 'pdf.mapCredit': 'Ülke sınırları: geoBoundaries (CC BY 4.0)', + 'pdf.showOverview': 'Genel bakış', + 'pdf.showPhotos': 'Fotoğraflar', + 'pdf.showDetails': 'İletişim ve çalışma saatleri', + 'pdf.atAGlance': 'Bir bakışta', + 'pdf.bookings': 'Rezervasyonlar ve konaklamalar', + 'pdf.day': 'Gün', + 'pdf.stay': 'Konaklama', + 'pdf.plan': 'Program', }; export default pdf; diff --git a/shared/src/i18n/uk/pdf.ts b/shared/src/i18n/uk/pdf.ts index 46440928a..b4da7dab4 100644 --- a/shared/src/i18n/uk/pdf.ts +++ b/shared/src/i18n/uk/pdf.ts @@ -15,5 +15,13 @@ const pdf: TranslationStrings = { 'pdf.mapTitle': 'Огляд маршруту', 'pdf.distanceLabel': 'Відстань', 'pdf.mapCredit': 'Контури країн: geoBoundaries (CC BY 4.0)', + 'pdf.showOverview': 'Огляд', + 'pdf.showPhotos': 'Фото', + 'pdf.showDetails': 'Контакти та години роботи', + 'pdf.atAGlance': 'Коротко', + 'pdf.bookings': 'Бронювання та житло', + 'pdf.day': 'День', + 'pdf.stay': 'Житло', + 'pdf.plan': 'План', }; export default pdf; diff --git a/shared/src/i18n/vi/pdf.ts b/shared/src/i18n/vi/pdf.ts index ed68eeab4..e583db5ef 100644 --- a/shared/src/i18n/vi/pdf.ts +++ b/shared/src/i18n/vi/pdf.ts @@ -15,5 +15,13 @@ const pdf: TranslationStrings = { 'pdf.mapTitle': 'Tổng quan lộ trình', 'pdf.distanceLabel': 'Quãng đường', 'pdf.mapCredit': 'Đường viền quốc gia: geoBoundaries (CC BY 4.0)', + 'pdf.showOverview': 'Tổng quan', + 'pdf.showPhotos': 'Ảnh', + 'pdf.showDetails': 'Liên hệ và giờ mở cửa', + 'pdf.atAGlance': 'Tóm tắt nhanh', + 'pdf.bookings': 'Đặt chỗ và lưu trú', + 'pdf.day': 'Ngày', + 'pdf.stay': 'Lưu trú', + 'pdf.plan': 'Kế hoạch', }; export default pdf; diff --git a/shared/src/i18n/zh-TW/pdf.ts b/shared/src/i18n/zh-TW/pdf.ts index 0a5420d00..31a7992bb 100644 --- a/shared/src/i18n/zh-TW/pdf.ts +++ b/shared/src/i18n/zh-TW/pdf.ts @@ -14,5 +14,13 @@ const pdf: TranslationStrings = { 'pdf.mapTitle': '路線總覽', 'pdf.distanceLabel': '距離', 'pdf.mapCredit': '國家輪廓:geoBoundaries (CC BY 4.0)', + 'pdf.showOverview': '概覽', + 'pdf.showPhotos': '照片', + 'pdf.showDetails': '聯絡方式與營業時間', + 'pdf.atAGlance': '一覽', + 'pdf.bookings': '預訂與住宿', + 'pdf.day': '天', + 'pdf.stay': '住宿', + 'pdf.plan': '行程', }; export default pdf; diff --git a/shared/src/i18n/zh/pdf.ts b/shared/src/i18n/zh/pdf.ts index 655666a9c..0543780d4 100644 --- a/shared/src/i18n/zh/pdf.ts +++ b/shared/src/i18n/zh/pdf.ts @@ -14,5 +14,13 @@ const pdf: TranslationStrings = { 'pdf.mapTitle': '路线总览', 'pdf.distanceLabel': '距离', 'pdf.mapCredit': '国家轮廓:geoBoundaries (CC BY 4.0)', + 'pdf.showOverview': '概览', + 'pdf.showPhotos': '照片', + 'pdf.showDetails': '联系方式和营业时间', + 'pdf.atAGlance': '一览', + 'pdf.bookings': '预订与住宿', + 'pdf.day': '天', + 'pdf.stay': '住宿', + 'pdf.plan': '行程', }; export default pdf;