mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-11-23 13:23:04 +00:00
Compare commits
11 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 965b519f23 | |||
| 3ec7cc73b2 | |||
| 493571c559 | |||
| 4212fcdfc8 | |||
| 28f750f7c4 | |||
| 8c9cf4a80c | |||
| b33d592325 | |||
| 590b174dd1 | |||
| 2a833c4ba9 | |||
| a5de1bc52d | |||
| 1b20214a7f |
@@ -0,0 +1,60 @@
|
||||
package com.liketrek.trek;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* The log line for a page of the server that came back with an error status.
|
||||
* "HTTP 503" on the address screen cannot tell the server, a proxy in front of
|
||||
* it and something on the phone apart, so the line names the page and the
|
||||
* headers that say who answered (#3014).
|
||||
*/
|
||||
final class PageErrorLog {
|
||||
|
||||
/** The headers that name whoever answered a page, in the order they are logged. */
|
||||
private static final String[] SENDER_HEADERS = { "Server", "Via", "CF-Ray", "Content-Type" };
|
||||
|
||||
private PageErrorLog() {}
|
||||
|
||||
/**
|
||||
* For example "Page answered HTTP 503 Service Unavailable for
|
||||
* https://trek.example.com/login (server: cloudflare, cf-ray: 8f1a2b3c4d5e6f70-FRA)".
|
||||
* The address goes without its query and fragment, where a sign-in page
|
||||
* carries a challenge or a code. A header the answer did not have is left
|
||||
* out, and an answer with none of them says so: no server sends a page
|
||||
* without at least its type, so that points at something on the phone.
|
||||
*/
|
||||
static String describe(String url, int status, String reason, Map<String, String> headers) {
|
||||
StringBuilder line = new StringBuilder("Page answered HTTP ").append(status);
|
||||
if (reason != null && !reason.trim().isEmpty()) line.append(' ').append(reason.trim());
|
||||
line.append(" for ").append(withoutQuery(url));
|
||||
List<String> senders = new ArrayList<>();
|
||||
for (String name : SENDER_HEADERS) {
|
||||
String value = header(headers, name);
|
||||
if (value != null && !value.trim().isEmpty()) senders.add(name.toLowerCase(Locale.ROOT) + ": " + value.trim());
|
||||
}
|
||||
line.append(senders.isEmpty() ? " (no server headers)" : " (" + String.join(", ", senders) + ")");
|
||||
return line.toString();
|
||||
}
|
||||
|
||||
/** A header by name, whatever case the answer wrote it in. */
|
||||
private static String header(Map<String, String> headers, String name) {
|
||||
if (headers == null) return null;
|
||||
for (Map.Entry<String, String> entry : headers.entrySet()) {
|
||||
if (name.equalsIgnoreCase(entry.getKey())) return entry.getValue();
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private static String withoutQuery(String url) {
|
||||
if (url == null) return "";
|
||||
int end = url.length();
|
||||
int query = url.indexOf('?');
|
||||
if (query >= 0) end = query;
|
||||
int fragment = url.indexOf('#');
|
||||
if (fragment >= 0 && fragment < end) end = fragment;
|
||||
return url.substring(0, end);
|
||||
}
|
||||
}
|
||||
@@ -202,14 +202,23 @@ class TrekWebViewClient extends BridgeWebViewClient {
|
||||
* none, as Cloudflare does with a 403, sends the app to the address screen,
|
||||
* which says so and offers to add one. Any other 4xx page (a proxy's block
|
||||
* page, a certificate it refused) stays up with the bar and its way out, so
|
||||
* the app is never stuck on a page without TREK's UI.
|
||||
* the app is never stuck on a page without TREK's UI. Each one is logged
|
||||
* with its address and whoever answered it (PageErrorLog).
|
||||
*/
|
||||
@Override
|
||||
public void onReceivedHttpError(WebView view, WebResourceRequest request, WebResourceResponse errorResponse) {
|
||||
int status = errorResponse.getStatusCode();
|
||||
if (!request.isForMainFrame()) {
|
||||
super.onReceivedHttpError(view, request, errorResponse);
|
||||
} else if (status >= 500 || (status >= 400 && wantedCertificate(request.getUrl()))) {
|
||||
return;
|
||||
}
|
||||
Log.w("TrekShell", PageErrorLog.describe(
|
||||
request.getUrl().toString(),
|
||||
status,
|
||||
errorResponse.getReasonPhrase(),
|
||||
errorResponse.getResponseHeaders()
|
||||
));
|
||||
if (status >= 500 || (status >= 400 && wantedCertificate(request.getUrl()))) {
|
||||
TrekServerStore.setFailure(view.getContext(), "HTTP " + status);
|
||||
onUnreachable.run();
|
||||
} else if (status >= 400) {
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
package com.liketrek.trek
|
||||
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Test
|
||||
|
||||
/** The log line for a page that came back with an error status (#3014). */
|
||||
class PageErrorLogTest {
|
||||
|
||||
@Test
|
||||
fun namesThePageItsStatusAndWhoAnswered() {
|
||||
val line = PageErrorLog.describe(
|
||||
"https://trek.example.com/login?redirect=%2F#top",
|
||||
503,
|
||||
"Service Unavailable",
|
||||
mapOf(
|
||||
"server" to "cloudflare",
|
||||
"CF-RAY" to "8f1a2b3c4d5e6f70-FRA",
|
||||
"content-type" to "text/html; charset=UTF-8",
|
||||
"Set-Cookie" to "session=secret",
|
||||
),
|
||||
)
|
||||
|
||||
// Any case of a header name is read, only the naming headers are logged,
|
||||
// and the query with its sign-in state is left off.
|
||||
assertEquals(
|
||||
"Page answered HTTP 503 Service Unavailable for https://trek.example.com/login " +
|
||||
"(server: cloudflare, cf-ray: 8f1a2b3c4d5e6f70-FRA, content-type: text/html; charset=UTF-8)",
|
||||
line,
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun anAnswerWithoutHeadersSaysSo() {
|
||||
assertEquals(
|
||||
"Page answered HTTP 503 for https://trek.example.com/ (no server headers)",
|
||||
PageErrorLog.describe("https://trek.example.com/", 503, null, emptyMap()),
|
||||
)
|
||||
assertEquals(
|
||||
"Page answered HTTP 502 Bad Gateway for (no server headers)",
|
||||
PageErrorLog.describe(null, 502, "Bad Gateway", null),
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun aFragmentBeforeAQuestionMarkEndsTheAddressThere() {
|
||||
assertEquals(
|
||||
"Page answered HTTP 500 for https://trek.example.com/trips/4 (via: 1.1 proxy)",
|
||||
PageErrorLog.describe("https://trek.example.com/trips/4#a?b", 500, " ", mapOf("Via" to "1.1 proxy")),
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -3,8 +3,8 @@
|
||||
"@typescript-eslint/no-non-null-assertion": 367,
|
||||
"@typescript-eslint/no-misused-promises": 820,
|
||||
"no-console": 88,
|
||||
"complexity": 217,
|
||||
"@typescript-eslint/no-explicit-any": 143,
|
||||
"complexity": 216,
|
||||
"@typescript-eslint/no-explicit-any": 138,
|
||||
"trek/no-swallowed-catch": 126,
|
||||
"max-params": 31,
|
||||
"trek/store-without-selector": 66,
|
||||
@@ -12,7 +12,7 @@
|
||||
"react-hooks/set-state-in-effect": 189,
|
||||
"@typescript-eslint/no-floating-promises": 162,
|
||||
"react-hooks/exhaustive-deps": 113,
|
||||
"@typescript-eslint/no-unused-vars": 120,
|
||||
"@typescript-eslint/no-unused-vars": 117,
|
||||
"react-hooks/immutability": 28,
|
||||
"max-lines-per-function": 127,
|
||||
"react-hooks/static-components": 50,
|
||||
@@ -35,7 +35,7 @@
|
||||
},
|
||||
"tests": {
|
||||
"@typescript-eslint/no-explicit-any": 489,
|
||||
"@typescript-eslint/no-non-null-assertion": 1875,
|
||||
"@typescript-eslint/no-non-null-assertion": 1872,
|
||||
"@typescript-eslint/no-misused-promises": 22,
|
||||
"@typescript-eslint/no-unused-vars": 51,
|
||||
"@typescript-eslint/no-floating-promises": 33,
|
||||
|
||||
@@ -35,7 +35,6 @@
|
||||
"components/Map/nightPauseMarker.ts": 4,
|
||||
"components/Map/ratingBadge.ts": 1,
|
||||
"components/Map/switcherRow.ts": 1,
|
||||
"components/PDF/TripPDF.tsx": 7,
|
||||
"components/PDF/tripMapImage.ts": 1,
|
||||
"components/Packing/PackingListPanelBagCard.tsx": 1,
|
||||
"components/Packing/PackingListPanelCategoryGroup.tsx": 3,
|
||||
|
||||
@@ -43,7 +43,7 @@
|
||||
"src/components/Map/ReservationOverlay.test.tsx": 1,
|
||||
"src/components/Map/transitGeometry.ts": 1,
|
||||
"src/components/Map/useMarkerThumbs.ts": 1,
|
||||
"src/components/PDF/TripPDF.tsx": 38,
|
||||
"src/components/PDF/TripPDF.tsx": 1,
|
||||
"src/components/Planner/DayPlanSidebar.constants.ts": 1,
|
||||
"src/components/Planner/DayPlanSidebar.tsx": 52,
|
||||
"src/components/Planner/DayPlanSidebarNoteModal.test.tsx": 1,
|
||||
|
||||
@@ -72,7 +72,6 @@
|
||||
"components/Map/ratingBadge.ts": 2,
|
||||
"components/Map/reservationsMapbox.ts": 1,
|
||||
"components/Map/switcherRow.ts": 1,
|
||||
"components/PDF/TripPDF.tsx": 44,
|
||||
"components/Packing/PackingListPanelBagModal.tsx": 2,
|
||||
"components/Packing/PackingListPanelCategoryGroup.tsx": 5,
|
||||
"components/Packing/PackingListPanelHeader.tsx": 3,
|
||||
|
||||
@@ -245,7 +245,7 @@ describe('trip route map in the PDF', () => {
|
||||
expect(html).toContain('<svg class="trip-map-svg"')
|
||||
// Between the cover and the days, which is where it is meant to read.
|
||||
expect(html.indexOf('class="trip-map"')).toBeGreaterThan(html.indexOf('class="cover"'))
|
||||
expect(html.indexOf('class="trip-map"')).toBeLessThan(html.indexOf('class="day-section"'))
|
||||
expect(html.indexOf('class="trip-map"')).toBeLessThan(html.indexOf('class="day-section'))
|
||||
})
|
||||
|
||||
it('FE-COMP-TRIPPDF-MAP-011: prefers the real basemap when it renders', async () => {
|
||||
|
||||
@@ -37,6 +37,41 @@ function plannedStat(html: string): number | null {
|
||||
return match ? Number(match[1]) : null
|
||||
}
|
||||
|
||||
/** The days of the document, without the cover and the overview's booking list before them. */
|
||||
function daysOf(html: string): string {
|
||||
return html.slice(html.indexOf('<table class="day-section'))
|
||||
}
|
||||
|
||||
const textOf = (el: Element | null | undefined) => 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('<table class="day-section')
|
||||
expect(srcdoc).toContain('<thead class="day-header">')
|
||||
expect(srcdoc).toContain('<tbody class="day-body-group">')
|
||||
// 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('<thead class="day-header"><tr><td><div class="day-head">')
|
||||
// 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('<section class="cover cover-plain">')
|
||||
})
|
||||
|
||||
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('<section class="cover cover-plain">')
|
||||
})
|
||||
|
||||
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('<div class="cover-title">My Trip</div>')
|
||||
expect(html).toContain('<h1 class="cover-title">My Trip</h1>')
|
||||
expect(html).toContain('<div class="cover-stat-num">0</div>')
|
||||
})
|
||||
|
||||
@@ -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('<table class="day-section">')).toBeGreaterThan(-1)
|
||||
expect(html.indexOf('<table class="day-section day-first"')).toBeGreaterThan(-1)
|
||||
expect(html.match(/day-section day-break/g)).toHaveLength(1)
|
||||
expect(html).toContain('.day-first { break-before: page; }')
|
||||
expect(html).toContain('.pdf-flow .day-break { break-before: auto; }')
|
||||
})
|
||||
|
||||
it('FE-PDF-BREAK-004: turning the breaks off is remembered and shown at once', async () => {
|
||||
@@ -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('<span class="note-clock">')
|
||||
expect(html).toContain('<div class="note-time note-code">Code: ABC123</div>')
|
||||
// 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(`<img class="place-thumb" src="${JPEG}" />`)
|
||||
expect(html).toContain(`<img class="place-thumb" src="${JPEG}" alt="" />`)
|
||||
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('<img class="place-thumb" src="https://images.example.com/colosseum.jpg" />')
|
||||
expect(previewFrame().srcdoc).toContain('<img class="place-thumb" src="https://images.example.com/colosseum.jpg" alt="" />')
|
||||
})
|
||||
|
||||
it('FE-PDF-THUMB-003: a closed export dialog stops the photos and opens nothing', async () => {
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -8,13 +8,15 @@ 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 { bakePdfCover, shrinkPdfImages, STRIP_PX } from './pdfImages';
|
||||
|
||||
const origin = window.location.origin;
|
||||
const JPEG = 'data:image/jpeg;base64,c21hbGw=';
|
||||
|
||||
let bitmapSize = { width: 1200, height: 800 };
|
||||
let drawn: { width: number; height: number }[] = [];
|
||||
let drawCalls: unknown[][] = [];
|
||||
let stops: [number, string][] = [];
|
||||
let inFlight = 0;
|
||||
let mostInFlight = 0;
|
||||
|
||||
@@ -24,7 +26,11 @@ function fakeContext(this: HTMLCanvasElement, type: string) {
|
||||
return {
|
||||
fillStyle: '',
|
||||
fillRect: vi.fn(),
|
||||
drawImage: vi.fn(() => drawn.push({ width: this.width, height: this.height })),
|
||||
drawImage: vi.fn((...args: unknown[]) => {
|
||||
drawCalls.push(args);
|
||||
drawn.push({ width: this.width, height: this.height });
|
||||
}),
|
||||
createLinearGradient: vi.fn(() => ({ addColorStop: (at: number, colour: string) => stops.push([at, colour]) })),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -35,6 +41,8 @@ function imageResponse(type = 'image/jpeg') {
|
||||
beforeEach(() => {
|
||||
bitmapSize = { width: 1200, height: 800 };
|
||||
drawn = [];
|
||||
drawCalls = [];
|
||||
stops = [];
|
||||
inFlight = 0;
|
||||
mostInFlight = 0;
|
||||
vi.stubGlobal(
|
||||
@@ -64,19 +72,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 () => {
|
||||
@@ -135,3 +151,35 @@ describe('shrinkPdfImages', () => {
|
||||
expect(shrunk.has(url)).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('bakePdfCover', () => {
|
||||
it('FE-PDFIMAGES-010: the photo is cropped to the page and the shade painted into one JPEG', async () => {
|
||||
bitmapSize = { width: 4000, height: 2252 };
|
||||
const url = `${origin}/uploads/places/cover.jpg`;
|
||||
const baked = await bakePdfCover(url, [
|
||||
[0, 0.35],
|
||||
[0.92, 0.82],
|
||||
]);
|
||||
|
||||
expect(baked).toBe(JPEG);
|
||||
// Decoded at the page's height, not in full.
|
||||
expect(createImageBitmap).toHaveBeenCalledWith(expect.any(Blob), { resizeHeight: 1754, resizeQuality: 'medium' });
|
||||
// A4 at 150 dpi, the landscape photo scaled to the page height and centred.
|
||||
expect(drawn).toEqual([{ width: 1240, height: 1754 }]);
|
||||
const [, x, y, width, height] = drawCalls[0] as number[];
|
||||
expect(height).toBeCloseTo(1754, 0);
|
||||
expect(width).toBeCloseTo((4000 * 1754) / 2252, 0);
|
||||
expect(x).toBeCloseTo((1240 - width) / 2, 3);
|
||||
expect(y).toBeCloseTo(0, 3);
|
||||
expect(stops).toEqual([
|
||||
[0, 'rgba(10, 10, 14, 0.35)'],
|
||||
[0.92, 'rgba(10, 10, 14, 0.82)'],
|
||||
]);
|
||||
});
|
||||
|
||||
it('FE-PDFIMAGES-011: a cover from another origin or one that cannot be read is left to print as before', async () => {
|
||||
expect(await bakePdfCover('https://elsewhere.example/cover.jpg', [[0, 0.5]])).toBeNull();
|
||||
expect(await bakePdfCover(`${origin}/uploads/missing.jpg`, [[0, 0.5]])).toBeNull();
|
||||
expect(drawn).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -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<string>, signal?: AbortSignal): Promise<Map<string, string>> {
|
||||
export async function shrinkPdfImages(
|
||||
urls: Iterable<string>,
|
||||
signal?: AbortSignal,
|
||||
shortSide = THUMB_PX
|
||||
): Promise<Map<string, string>> {
|
||||
const shrunk = new Map<string, string>();
|
||||
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,24 @@ function canShrink(): boolean {
|
||||
return typeof createImageBitmap === 'function' && document.createElement('canvas').getContext('2d') !== null;
|
||||
}
|
||||
|
||||
async function shrinkImage(url: string, signal?: AbortSignal): Promise<string | null> {
|
||||
async function shrinkImage(url: string, shortSide: number, signal?: AbortSignal): Promise<string | null> {
|
||||
// Decoded at twice the short side, so a portrait photo still has room to shrink.
|
||||
const bitmap = await fetchBitmap(url, shortSide * 2, signal);
|
||||
if (!bitmap) return null;
|
||||
try {
|
||||
return toJpeg(bitmap, shortSide);
|
||||
} finally {
|
||||
bitmap.close();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The photo at `url` decoded at `height` pixels, or null when it cannot be had. Decoded
|
||||
* near the size it is drawn at: a 48 MP phone photo decoded in full holds about 190 MB,
|
||||
* which can end the web view on a phone. Browsers without the option decode in full and
|
||||
* the canvas scales down as before.
|
||||
*/
|
||||
async function fetchBitmap(url: string, height: number, signal?: AbortSignal): Promise<ImageBitmap | null> {
|
||||
// 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();
|
||||
@@ -73,15 +94,7 @@ async function shrinkImage(url: string, signal?: AbortSignal): Promise<string |
|
||||
if (!res.ok || Number(res.headers.get('content-length') ?? 0) > MAX_BYTES) return null;
|
||||
const blob = await res.blob();
|
||||
if (!blob.type.startsWith('image/') || blob.size > MAX_BYTES) return null;
|
||||
// Decoded near thumbnail size: a 48 MP phone photo decoded in full holds about
|
||||
// 190 MB, which can end the web view on a phone. Browsers without the option
|
||||
// decode in full and toJpeg scales down as before.
|
||||
const bitmap = await createImageBitmap(blob, { resizeHeight: DECODE_PX, resizeQuality: 'medium' });
|
||||
try {
|
||||
return toJpeg(bitmap);
|
||||
} finally {
|
||||
bitmap.close();
|
||||
}
|
||||
return await createImageBitmap(blob, { resizeHeight: height, resizeQuality: 'medium' });
|
||||
} catch {
|
||||
// Offline, timed out, aborted or undecodable: the photo prints from its URL.
|
||||
return null;
|
||||
@@ -91,9 +104,58 @@ async function shrinkImage(url: string, signal?: AbortSignal): Promise<string |
|
||||
}
|
||||
}
|
||||
|
||||
/** The bitmap with its short side at THUMB_PX, or null when it is that small already. */
|
||||
function toJpeg(bitmap: ImageBitmap): string | null {
|
||||
const scale = THUMB_PX / Math.min(bitmap.width, bitmap.height);
|
||||
/** The cover page in pixels: A4 at 150 dpi, enough for a photo behind the type. */
|
||||
const COVER_W = 1240;
|
||||
const COVER_H = 1754;
|
||||
const COVER_QUALITY = 0.82;
|
||||
|
||||
/** One stop of the shade over the cover photo: how far down the page, 0 to 1, and how dark. */
|
||||
export type ShadeStop = readonly [at: number, alpha: number];
|
||||
|
||||
/**
|
||||
* The cover photo cropped to the page with its shade painted in, as one JPEG at print
|
||||
* size. A page-sized photo under a translucent gradient is composited again by every
|
||||
* viewer on every redraw, which made the first pages stutter in the preview and in the
|
||||
* saved file; one flat picture is drawn once. Null for a photo from another origin or
|
||||
* one that cannot be read: the cover then prints the photo and the shade as before.
|
||||
*/
|
||||
export async function bakePdfCover(
|
||||
url: string,
|
||||
shade: readonly ShadeStop[],
|
||||
signal?: AbortSignal
|
||||
): Promise<string | null> {
|
||||
if (!isSameOrigin(url) || !canShrink()) return null;
|
||||
const bitmap = await fetchBitmap(url, COVER_H, signal);
|
||||
if (!bitmap) return null;
|
||||
try {
|
||||
const canvas = document.createElement('canvas');
|
||||
canvas.width = COVER_W;
|
||||
canvas.height = COVER_H;
|
||||
const ctx = canvas.getContext('2d');
|
||||
if (!ctx) return null;
|
||||
// Cropped the way background-size: cover crops it, around the middle.
|
||||
const scale = Math.max(COVER_W / bitmap.width, COVER_H / bitmap.height);
|
||||
const width = bitmap.width * scale;
|
||||
const height = bitmap.height * scale;
|
||||
ctx.drawImage(bitmap, (COVER_W - width) / 2, (COVER_H - height) / 2, width, height);
|
||||
const gradient = ctx.createLinearGradient(0, 0, 0, COVER_H);
|
||||
for (const [at, alpha] of shade) gradient.addColorStop(at, `rgba(10, 10, 14, ${alpha})`);
|
||||
ctx.fillStyle = gradient;
|
||||
ctx.fillRect(0, 0, COVER_W, COVER_H);
|
||||
const baked = canvas.toDataURL('image/jpeg', COVER_QUALITY);
|
||||
return baked.startsWith('data:image/jpeg') ? baked : null;
|
||||
} catch {
|
||||
// A canvas the browser will not draw or encode (out of memory on a phone, say):
|
||||
// the cover then prints the photo and its shade as separate layers, as before.
|
||||
return null;
|
||||
} finally {
|
||||
bitmap.close();
|
||||
}
|
||||
}
|
||||
|
||||
/** The bitmap with its short side at `shortSide`, or null when it is that small already. */
|
||||
function toJpeg(bitmap: ImageBitmap, shortSide: number): string | null {
|
||||
const scale = shortSide / Math.min(bitmap.width, bitmap.height);
|
||||
if (!Number.isFinite(scale) || scale >= 1) return null;
|
||||
const canvas = document.createElement('canvas');
|
||||
canvas.width = Math.max(1, Math.round(bitmap.width * scale));
|
||||
|
||||
@@ -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<PdfPreviewOptions> = {}) {
|
||||
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<HTMLIFrameElement>('#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);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -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 = `
|
||||
<span style="font-size:13px;font-weight:600;color:var(--text-primary);min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap">${escapeHtml(title)}</span>
|
||||
<div style="display:flex;align-items:center;justify-content:flex-end;flex-wrap:wrap;gap:8px">
|
||||
${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)}
|
||||
<div style="display:flex;align-items:center;justify-content:flex-end;gap:8px">
|
||||
${save.html}
|
||||
<button type="button" id="pdf-close-btn" style="background:none;border:none;cursor:pointer;color:var(--text-faint);display:flex;padding:4px;border-radius:6px">
|
||||
<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>
|
||||
@@ -115,6 +131,23 @@ export function openPdfPreview({
|
||||
</div>
|
||||
`;
|
||||
|
||||
// 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),
|
||||
'<span aria-hidden="true" style="width:1px;align-self:stretch;background:var(--border-primary)"></span>',
|
||||
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 <body>, 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);
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { buildTripMapSvg } from './tripMapSvg'
|
||||
import { buildTripMapSvg, drawnPoints } from './tripMapSvg'
|
||||
import type { TripOverviewDay } from '../Map/tripRouteGeometry'
|
||||
|
||||
const day = (over: Partial<TripOverviewDay> = {}): TripOverviewDay => ({
|
||||
@@ -78,3 +78,25 @@ describe('buildTripMapSvg', () => {
|
||||
expect(svg).toContain('width="720"')
|
||||
})
|
||||
})
|
||||
|
||||
// A routed road carries a point every few metres; drawn as it came, a trip map held
|
||||
// tens of thousands of them and stuttered in every viewer.
|
||||
describe('drawnPoints', () => {
|
||||
// One degree is one map pixel, so the tolerance reads in degrees here.
|
||||
const flat = (lat: number, lng: number): [number, number] => [lng, -lat]
|
||||
|
||||
it('FE-PDF-MAPSVG-020: a dense straight road keeps only its ends', () => {
|
||||
const road = Array.from({ length: 5000 }, (_, i) => [0, i / 10] as [number, number])
|
||||
expect(drawnPoints(road, flat)).toBe('0,0 499.9,0')
|
||||
})
|
||||
|
||||
it('FE-PDF-MAPSVG-021: a turn is kept, a wobble under the tolerance is not', () => {
|
||||
const road: [number, number][] = [[0, 0], [-0.1, 50], [0, 100], [-60, 100], [-0.2, 100.1]]
|
||||
expect(drawnPoints(road, flat)).toBe('0,0 100,0 100,60 100.1,0.2')
|
||||
})
|
||||
|
||||
it('FE-PDF-MAPSVG-022: points that round onto the same pixel are drawn once', () => {
|
||||
const road: [number, number][] = [[0, 0], [0, 0.01], [0, 0.02], [0, 0.04]]
|
||||
expect(drawnPoints(road, flat)).toBe('0,0')
|
||||
})
|
||||
})
|
||||
|
||||
@@ -125,6 +125,55 @@ export interface RouteOverlayOptions {
|
||||
formatDistance: (km: number) => string
|
||||
}
|
||||
|
||||
/** How far, in map pixels, a point may sit off the line its neighbours make before it is kept. */
|
||||
const SIMPLIFY_TOLERANCE = 0.35
|
||||
|
||||
/**
|
||||
* A run projected onto the map and thinned for drawing. A routed road carries a point
|
||||
* every few metres: at the scale of a trip map that is tens of thousands of points, most
|
||||
* rounding onto the same pixel, each drawn twice (casing and line) and drawn again by
|
||||
* every viewer on every scroll, which made the page stutter. Points that round onto the
|
||||
* one before are dropped, then every point closer than SIMPLIFY_TOLERANCE to the line
|
||||
* through the points kept around it (Douglas-Peucker). The shape on paper is the same.
|
||||
*/
|
||||
export function drawnPoints(line: [number, number][], project: (lat: number, lng: number) => [number, number]): string {
|
||||
const round = (n: number) => Math.round(n * 10) / 10
|
||||
const pts: [number, number][] = []
|
||||
for (const [lat, lng] of line) {
|
||||
const [x, y] = project(lat, lng)
|
||||
const point: [number, number] = [round(x), round(y)]
|
||||
const prev = pts[pts.length - 1]
|
||||
if (!prev || prev[0] !== point[0] || prev[1] !== point[1]) pts.push(point)
|
||||
}
|
||||
const keep = new Uint8Array(pts.length)
|
||||
keep[0] = 1
|
||||
keep[pts.length - 1] = 1
|
||||
const ranges: [number, number][] = [[0, pts.length - 1]]
|
||||
for (let range = ranges.pop(); range; range = ranges.pop()) {
|
||||
const [from, to] = range
|
||||
if (to - from < 2) continue
|
||||
const [ax, ay] = pts[from]
|
||||
const [bx, by] = pts[to]
|
||||
const dx = bx - ax
|
||||
const dy = by - ay
|
||||
const length = Math.hypot(dx, dy)
|
||||
let farthest = -1
|
||||
let distance = 0
|
||||
for (let i = from + 1; i < to; i++) {
|
||||
const [px, py] = pts[i]
|
||||
const d = length === 0 ? Math.hypot(px - ax, py - ay) : Math.abs(dy * px - dx * py + bx * ay - by * ax) / length
|
||||
if (d > distance) {
|
||||
distance = d
|
||||
farthest = i
|
||||
}
|
||||
}
|
||||
if (farthest < 0 || distance <= SIMPLIFY_TOLERANCE) continue
|
||||
keep[farthest] = 1
|
||||
ranges.push([from, farthest], [farthest, to])
|
||||
}
|
||||
return pts.filter((_, i) => keep[i]).map(p => p.join(',')).join(' ')
|
||||
}
|
||||
|
||||
/**
|
||||
* The routes, their stops and the scale bar — everything drawn *over* the ground.
|
||||
*
|
||||
@@ -138,7 +187,7 @@ export function buildRouteOverlay(days: TripOverviewDay[], opts: RouteOverlayOpt
|
||||
const drawn = days.filter(d => [...d.lines, ...(d.tourLines ?? [])].some(line => line.length > 1))
|
||||
|
||||
const routes = drawn.flatMap(day => day.lines.filter(l => l.length > 1).map(line => {
|
||||
const pts = line.map(([lat, lng]) => project(lat, lng).map(round).join(',')).join(' ')
|
||||
const pts = drawnPoints(line, project)
|
||||
// The day's own darkened casing rather than a flat white one: it is what keeps a
|
||||
// warm colour readable over water and forest, and it matches what the map draws.
|
||||
return `<polyline points="${pts}" fill="none" stroke="${strokeColour(day.color.casing)}" stroke-width="5.5" stroke-linecap="round" stroke-linejoin="round"/>`
|
||||
@@ -147,7 +196,7 @@ export function buildRouteOverlay(days: TripOverviewDay[], opts: RouteOverlayOpt
|
||||
|
||||
// Where each run starts and ends — the stops, rather than every vertex of the road.
|
||||
const tours = drawn.flatMap(day => (day.tourLines ?? []).filter(line => line.length > 1).map(line => {
|
||||
const pts = line.map(([lat, lng]) => project(lat, lng).map(round).join(',')).join(' ')
|
||||
const pts = drawnPoints(line, project)
|
||||
return `<polyline points="${pts}" fill="none" stroke="#ffffff" stroke-width="5" stroke-linecap="round" stroke-linejoin="round"/>`
|
||||
+ `<polyline points="${pts}" fill="none" stroke="#14805e" stroke-width="2.8" stroke-linecap="round" stroke-linejoin="round"/>`
|
||||
}))
|
||||
|
||||
@@ -0,0 +1,264 @@
|
||||
/**
|
||||
* 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([
|
||||
{ closed: false, open: '08:00', close: '18:00' },
|
||||
{ closed: false, open: '08:00', close: '18:00' },
|
||||
{ closed: false, open: '09:00', close: '17:30' },
|
||||
{ closed: true },
|
||||
{ closed: false, open: '08:00', close: '18:00' },
|
||||
{ closed: false, open: '08:00', close: '18:00' },
|
||||
{ closed: false, 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> = {}): 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) => `<p>${text}</p>`,
|
||||
...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<string, unknown> = {}): 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('<p>Wooden **stage** over the hill</p>');
|
||||
});
|
||||
|
||||
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: '<img src=x onerror=alert(1)>',
|
||||
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(['<img src=x onerror=alert(1)>']);
|
||||
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 <tickets>',
|
||||
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 <tickets>']);
|
||||
// The note's time field is its free second line, kept in the card, not a clock.
|
||||
expect(texts(tinted, '.note-time')).toEqual(['08:00']);
|
||||
expect(tinted.querySelector('.tl-start')).toBeNull();
|
||||
|
||||
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('.note-time')).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-lbl')).toEqual(['pdf.day']);
|
||||
expect(texts(doc, '.day-tag-num')).toEqual(['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 <one>' },
|
||||
{ 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 <one>', 'Stage']);
|
||||
expect([...doc.querySelectorAll('img')].map((img) => img.getAttribute('src'))).toEqual([
|
||||
'https://a.example/1.jpg',
|
||||
'https://a.example/2.jpg',
|
||||
]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,434 @@
|
||||
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, string | number>) => 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<number, Place>;
|
||||
/** 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<string, unknown> {
|
||||
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<string, unknown>) : {};
|
||||
} 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 `<div class="tl-time">${start ? `<span class="tl-start">${escHtml(start)}</span>` : ''}${
|
||||
end ? `<span class="tl-end">${escHtml(end)}</span>` : ''
|
||||
}</div>`;
|
||||
}
|
||||
|
||||
function item(kind: string, time: string, marker: string, body: string, style = ''): string {
|
||||
return `<li class="tl-item tl-${kind}"${style ? ` style="${style}"` : ''}>${time}<div class="tl-rail"><span class="tl-marker">${marker}</span></div><div class="tl-body">${body}</div></li>`;
|
||||
}
|
||||
|
||||
// ── 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;
|
||||
// Each key spelled out, so the key check can follow every branch to its string.
|
||||
const start = phase === 'start';
|
||||
const end = phase === 'end';
|
||||
if (r.type === 'flight') return tr(`reservations.span.${start ? 'departure' : end ? 'arrival' : 'inTransit'}`);
|
||||
if (r.type === 'car') return tr(`reservations.span.${start ? 'pickup' : 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.${start ? 'dropOff' : end ? 'pickup' : 'ongoing'}`);
|
||||
return tr(`reservations.span.${start ? 'start' : end ? '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 `<div class="note-line">${l.route ? `<span class="route">${escHtml(l.route)}</span>` : ''}${
|
||||
l.people ? `<span class="chip">${glyph('people', 9)}${escHtml(l.people)}</span>` : ''
|
||||
}${l.facts
|
||||
.map((fact) => `<span class="chip">${escHtml(fact)}</span>`)
|
||||
.join('')}${l.code ? `<span class="code-chip">${glyph('key', 9)}${escHtml(l.code)}</span>` : ''}</div>`;
|
||||
}
|
||||
|
||||
/** 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' ? tr('reservations.confirmed') : r.status === 'pending' ? tr('reservations.pending') : '';
|
||||
const tint = hexColour(bookingTint(r.type), NEUTRAL);
|
||||
|
||||
const extras = [
|
||||
r.confirmation_number
|
||||
? `<span class="code-chip note-code">${glyph('key', 9)}${escHtml(r.confirmation_number)}</span>`
|
||||
: '',
|
||||
status ? `<span class="chip">${escHtml(status)}</span>` : '',
|
||||
].filter(Boolean);
|
||||
|
||||
const card = `<div class="note-card booking-card">
|
||||
<span class="note-icon">${bookingIcon(r.type)}</span>
|
||||
<div class="note-body">
|
||||
${span ? `<div class="note-kicker">${escHtml(span)}</div>` : ''}
|
||||
<div class="note-text">${escHtml(r.title)}</div>
|
||||
${bookingLines(r, tr).map(bookingLineHtml).join('')}
|
||||
${location ? `<div class="note-time">${escHtml(location)}</div>` : ''}
|
||||
${extras.length ? `<div class="note-extra">${extras.join('')}</div>` : ''}
|
||||
${note ? `<div class="note-time transport-note">${escHtml(note)}</div>` : ''}
|
||||
</div>
|
||||
</div>`;
|
||||
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, '') : '';
|
||||
// A note's `time` is the free line the day plan prints under its text, not a clock,
|
||||
// so it stays in the card and the time column stays empty.
|
||||
const subtitle = typeof note.time === 'string' ? note.time.trim() : '';
|
||||
const card = `<div class="note-card${colour ? ' note-tinted' : ''}"${colour ? ` style="--note:${colour}"` : ''}>
|
||||
<span class="note-icon">${noteIcon(note.icon)}</span>
|
||||
<div class="note-body"><div class="note-text">${escHtml(note.text)}</div>${
|
||||
subtitle ? `<div class="note-time">${escHtml(subtitle)}</div>` : ''
|
||||
}</div>
|
||||
</div>`;
|
||||
return item('note', timeColumn('', ''), '', card);
|
||||
}
|
||||
|
||||
// ── Places ────────────────────────────────────────────────────────────────
|
||||
|
||||
/** The day's opening hours of a place, Monday first like the stored week; null when unknown. */
|
||||
function hoursOnDay(place: Partial<Place>, 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<Place>, ctx: PdfDayContext): string[] {
|
||||
const facts: string[] = [];
|
||||
const duration = durationLabel(place.duration_minutes);
|
||||
if (duration) facts.push(`<span class="chip">${glyph('duration', 9)}${escHtml(duration)}</span>`);
|
||||
const price = Number(place.price);
|
||||
if (Number.isFinite(price) && price > 0) {
|
||||
facts.push(
|
||||
`<span class="chip chip-green">${glyph('price', 9)}${escHtml(formatMoney(price, place.currency || ctx.tripCurrency, ctx.locale || 'en'))}</span>`
|
||||
);
|
||||
}
|
||||
if (typeof place.rating_avg === 'number' && place.rating_avg > 0) {
|
||||
const count = place.rating_count ? ` (${place.rating_count})` : '';
|
||||
facts.push(`<span class="chip chip-rating">${glyph('star', 9)}${place.rating_avg.toFixed(1)}${count}</span>`);
|
||||
}
|
||||
for (const tag of place.tags || []) {
|
||||
if (!tag.name) continue;
|
||||
facts.push(
|
||||
`<span class="chip chip-tag" style="--tag:${hexColour(tag.color, NEUTRAL)}">${escHtml(tag.name)}</span>`
|
||||
);
|
||||
}
|
||||
return facts;
|
||||
}
|
||||
|
||||
function placeDetails(
|
||||
place: Assignment['place'] & Partial<Place>,
|
||||
assignment: Assignment,
|
||||
day: Day,
|
||||
ctx: PdfDayContext
|
||||
): string[] {
|
||||
const details: string[] = [];
|
||||
const hours = hoursOnDay(place, day, ctx);
|
||||
if (hours)
|
||||
details.push(
|
||||
`<span class="detail">${glyph('hours', 9)}${escHtml(ctx.tr('inspector.openingHours'))} ${escHtml(hours)}</span>`
|
||||
);
|
||||
if (place.phone) details.push(`<span class="detail">${glyph('phone', 9)}${escHtml(place.phone)}</span>`);
|
||||
if (place.website)
|
||||
details.push(`<span class="detail">${glyph('web', 9)}${escHtml(websiteHost(place.website))}</span>`);
|
||||
if (place.email) details.push(`<span class="detail">${glyph('mail', 9)}${escHtml(place.email)}</span>`);
|
||||
const people = (assignment.participants || []).map((p) => p.username).filter(Boolean);
|
||||
if (people.length) {
|
||||
details.push(
|
||||
`<span class="detail">${glyph('people', 9)}${escHtml(ctx.tr('inspector.participants'))}: ${escHtml(people.join(', '))}</span>`
|
||||
);
|
||||
}
|
||||
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<Place> = {
|
||||
...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
|
||||
? `<img class="place-thumb" src="${escHtml(photo)}" alt="" />`
|
||||
: `<div class="place-thumb-fallback">${categoryIcon(category?.icon)}</div>`;
|
||||
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 = `<div class="place-card" style="--cat:${catColour}">
|
||||
${media}
|
||||
<div class="place-info">
|
||||
<div class="place-name-row">
|
||||
<span class="place-name">${escHtml(place.name)}</span>
|
||||
${category ? `<span class="cat-badge">${escHtml(category.name)}</span>` : ''}
|
||||
</div>
|
||||
${facts.length ? `<div class="facts">${facts.join('')}</div>` : ''}
|
||||
${place.address ? `<div class="info-row">${glyph('pin')}<span class="info-text">${escHtml(place.address)}</span></div>` : ''}
|
||||
${
|
||||
hasPosition
|
||||
? `<div class="info-row coords">${glyph('coords')}<span class="info-text muted">${Number(place.lat).toFixed(5)}, ${Number(place.lng).toFixed(5)}</span></div>`
|
||||
: ''
|
||||
}
|
||||
${place.description ? `<div class="place-text">${ctx.markdown(place.description)}</div>` : ''}
|
||||
${notes.map((note) => `<div class="place-note">${ctx.markdown(note)}</div>`).join('')}
|
||||
${details.length ? `<div class="details">${details.join('')}</div>` : ''}
|
||||
</div>
|
||||
</div>`;
|
||||
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 = `<span class="stay-media">${photo ? `<img src="${escHtml(photo)}" alt="" />` : glyph(isCheckOut ? 'checkOut' : isCheckIn ? 'checkIn' : 'bed', 16)}</span>`;
|
||||
if (!isCheckIn && !isCheckOut) {
|
||||
return `<div class="day-accommodation stay-quiet">${media}<div class="stay-main">
|
||||
<div class="stay-kicker">${escHtml(ctx.tr('reservations.meta.linkAccommodation'))}</div>
|
||||
<div class="stay-name">${escHtml(name)}</div>
|
||||
</div></div>`;
|
||||
}
|
||||
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
|
||||
? `<span class="code-chip">${glyph('key', 9)}${escHtml(stay.confirmation)}</span>`
|
||||
: '',
|
||||
].filter(Boolean);
|
||||
return `<div class="day-accommodation">${media}<div class="stay-main">
|
||||
<div class="stay-kicker">${escHtml(label)}${time ? ` <span class="num">${escHtml(time)}</span>` : ''}</div>
|
||||
<div class="stay-name">${escHtml(name)}</div>
|
||||
${stay.place_address ? `<div class="stay-line">${escHtml(stay.place_address)}</div>` : ''}
|
||||
${stay.notes ? `<div class="stay-line">${escHtml(stay.notes)}</div>` : ''}
|
||||
${extras.length ? `<div class="stay-extra">${extras.join('')}</div>` : ''}
|
||||
</div></div>`;
|
||||
});
|
||||
return `<div class="day-accommodations${stays.length === 1 ? ' single' : ''}">${cards.join('')}</div>`;
|
||||
}
|
||||
|
||||
// ── Header ────────────────────────────────────────────────────────────────
|
||||
|
||||
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 ? `<span class="meta-pill">${glyph('pin', 9)}${facts.stops}</span>` : '',
|
||||
facts.distance ? `<span class="meta-pill">${glyph('route', 9)}${escHtml(facts.distance)}</span>` : '',
|
||||
facts.cost ? `<span class="day-cost">${glyph('price', 9)}${facts.cost}</span>` : '',
|
||||
].filter(Boolean);
|
||||
return `<div class="day-head">
|
||||
<span class="day-tag"><span class="day-tag-lbl">${escHtml(ctx.tr('pdf.day'))}</span><span class="day-tag-num">${n}</span></span>
|
||||
<div class="day-head-main">
|
||||
${day.date ? `<div class="day-date">${escHtml(shortDate(day.date, ctx.locale))}</div>` : ''}
|
||||
<div class="day-title">${escHtml(day.title || ctx.tr('dayplan.dayN', { n }))}</div>
|
||||
</div>
|
||||
${pills.length ? `<div class="day-meta">${pills.join('')}</div>` : ''}
|
||||
</div>`;
|
||||
}
|
||||
|
||||
// ── Photo strip ───────────────────────────────────────────────────────────
|
||||
|
||||
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 `<div class="day-strip day-strip-${photos.length}">${photos
|
||||
.map(
|
||||
(p) =>
|
||||
`<figure class="day-strip-photo"><img src="${escHtml(p.url)}" alt="" /><figcaption class="glass-label">${escHtml(p.caption)}</figcaption></figure>`
|
||||
)
|
||||
.join('')}</div>`;
|
||||
}
|
||||
@@ -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, '>').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;
|
||||
}
|
||||
}
|
||||
@@ -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<string, LucideIcon>;
|
||||
|
||||
type PdfGlyph = keyof typeof GLYPHS;
|
||||
|
||||
export function glyph(name: PdfGlyph, size = 10): string {
|
||||
return iconSvg(GLYPHS[name], size);
|
||||
}
|
||||
|
||||
const NOTE_ICONS: Record<string, LucideIcon> = {
|
||||
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<string, LucideIcon> = {
|
||||
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<string, string> = {
|
||||
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);
|
||||
}
|
||||
@@ -0,0 +1,196 @@
|
||||
/**
|
||||
* FE-PDFOVERVIEW-001 to FE-PDFOVERVIEW-005: the trip PDF's cover and overview pages,
|
||||
* built from the figures the export hands them.
|
||||
*/
|
||||
import { describe, expect, it } from 'vitest';
|
||||
|
||||
import { coverHtml, coverRouteSvg, glanceHtml, ledgerHtml, type GlanceRow, type LedgerRow } from './tripPdfOverview';
|
||||
|
||||
const tr = (key: string) => key;
|
||||
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('coverHtml', () => {
|
||||
const base = {
|
||||
title: 'Autumn <in> Japan',
|
||||
description: 'Temples and trains',
|
||||
range: '1 November – 22 November 2026',
|
||||
logo: 'https://trek.example/logo-light.svg',
|
||||
stats: [
|
||||
{ value: '22', label: 'days' },
|
||||
{ value: '1,234 km', label: 'pdf.distanceLabel' },
|
||||
],
|
||||
route: [],
|
||||
ribbon: [],
|
||||
ribbonEnds: null,
|
||||
tr,
|
||||
};
|
||||
|
||||
it('FE-PDFOVERVIEW-001: the photo, the escaped title, the dates and a tile per figure', () => {
|
||||
const doc = parse(coverHtml({ ...base, image: 'https://cdn.example/cover.jpg' }));
|
||||
|
||||
expect(doc.querySelector('section')?.className).toBe('cover');
|
||||
expect(doc.querySelector('.cover-bg')?.getAttribute('style')).toBe(
|
||||
"background-image:url('https://cdn.example/cover.jpg')"
|
||||
);
|
||||
expect(texts(doc, '.cover-title')).toEqual(['Autumn <in> Japan']);
|
||||
expect(texts(doc, '.cover-dates')).toEqual(['1 November – 22 November 2026']);
|
||||
expect(texts(doc, '.cover-desc')).toEqual(['Temples and trains']);
|
||||
expect(texts(doc, '.cover-stat-num')).toEqual(['22', '1,234 km']);
|
||||
expect(texts(doc, '.cover-top .eyebrow')).toEqual(['pdf.travelPlan']);
|
||||
});
|
||||
|
||||
it('FE-PDFOVERVIEW-002: without a photo the cover is plain, and a hostile url cannot leave url()', () => {
|
||||
const plain = parse(coverHtml({ ...base, image: null, description: null, range: null }));
|
||||
expect(plain.querySelector('section')?.className).toBe('cover cover-plain');
|
||||
expect(plain.querySelector('.cover-bg')?.hasAttribute('style')).toBe(false);
|
||||
expect(plain.querySelector('.cover-desc')).toBeNull();
|
||||
expect(plain.querySelector('.cover-dates')).toBeNull();
|
||||
|
||||
const hostile = parse(coverHtml({ ...base, image: "https://a/x.jpg');background:url('https://b/leak.jpg" }));
|
||||
const style = hostile.querySelector('.cover-bg')?.getAttribute('style') ?? '';
|
||||
expect(style.match(/url\(/g)).toHaveLength(1);
|
||||
expect(style).not.toContain("');");
|
||||
});
|
||||
});
|
||||
|
||||
describe('the cover route and day band', () => {
|
||||
const base = { title: 'Japan', description: null, range: null, image: null, logo: null, stats: [], tr };
|
||||
|
||||
it('FE-PDFOVERVIEW-006: the route is drawn day by day in its colours, the band has a segment per day', () => {
|
||||
const doc = parse(
|
||||
coverHtml({
|
||||
...base,
|
||||
route: [
|
||||
{
|
||||
colour: '#ff0000',
|
||||
lines: [
|
||||
[
|
||||
[35.68, 139.76],
|
||||
[35.0, 135.77],
|
||||
],
|
||||
],
|
||||
},
|
||||
{
|
||||
colour: '#00ff00',
|
||||
lines: [
|
||||
[
|
||||
[35.0, 135.77],
|
||||
[34.69, 135.5],
|
||||
],
|
||||
],
|
||||
},
|
||||
],
|
||||
ribbon: ['#ff0000', '#00ff00', '#0000ff'],
|
||||
ribbonEnds: ['Sun, Nov 1', 'Tue, Nov 3'],
|
||||
})
|
||||
);
|
||||
|
||||
const coloured = [...doc.querySelectorAll('.cover-route-svg path[stroke]')].map((p) => p.getAttribute('stroke'));
|
||||
expect(coloured).toEqual(['#ff0000', '#00ff00']);
|
||||
expect(doc.querySelectorAll('.cover-route-glow path')).toHaveLength(2);
|
||||
expect(texts(doc, '.cover-route-lbl')).toEqual(['pdf.mapTitle']);
|
||||
expect(doc.querySelectorAll('.cover-ribbon span')).toHaveLength(3);
|
||||
expect(texts(doc, '.cover-ribbon-ends span')).toEqual(['Sun, Nov 1', 'Tue, Nov 3']);
|
||||
// Every point lands inside the drawing.
|
||||
const numbers = [...doc.querySelectorAll('.cover-route-svg path[stroke]')].flatMap((p) =>
|
||||
(p.getAttribute('d') ?? '').split(/[ML ]/).filter(Boolean).map(Number)
|
||||
);
|
||||
for (const n of numbers) expect(n).toBeGreaterThanOrEqual(0);
|
||||
for (const n of numbers) expect(n).toBeLessThanOrEqual(240);
|
||||
});
|
||||
|
||||
it('FE-PDFOVERVIEW-007: nothing routed, one point or one spot draws no card, one day no band', () => {
|
||||
expect(coverRouteSvg([])).toBe('');
|
||||
expect(coverRouteSvg([{ colour: '#ff0000', lines: [[[1, 1]]] }])).toBe('');
|
||||
expect(
|
||||
coverRouteSvg([
|
||||
{
|
||||
colour: '#ff0000',
|
||||
lines: [
|
||||
[
|
||||
[1, 1],
|
||||
[1, 1],
|
||||
],
|
||||
],
|
||||
},
|
||||
])
|
||||
).toBe('');
|
||||
|
||||
const doc = parse(coverHtml({ ...base, route: [], ribbon: ['#ff0000'], ribbonEnds: null }));
|
||||
expect(doc.querySelector('.cover-route')).toBeNull();
|
||||
expect(doc.querySelector('.cover-ribbon')).toBeNull();
|
||||
});
|
||||
|
||||
it('FE-PDFOVERVIEW-008: a long road is thinned to a drawable number of points', () => {
|
||||
const road = Array.from({ length: 20000 }, (_, i) => [45 + i / 20000, 7 + i / 10000] as [number, number]);
|
||||
const svg = coverRouteSvg([{ colour: '#ff0000', lines: [road] }]);
|
||||
const d = /<path d="([^"]+)" stroke=/.exec(svg)?.[1] ?? '';
|
||||
expect(d.split('L').length).toBeLessThanOrEqual(1700);
|
||||
});
|
||||
});
|
||||
|
||||
describe('glanceHtml', () => {
|
||||
const row = (over: Partial<GlanceRow> = {}): GlanceRow => ({
|
||||
number: 1,
|
||||
colour: '#0a84ff',
|
||||
date: 'Sun, Nov 1',
|
||||
title: 'Tokyo',
|
||||
stops: 3,
|
||||
stay: 'Hotel Gracery',
|
||||
cost: null,
|
||||
...over,
|
||||
});
|
||||
|
||||
it('FE-PDFOVERVIEW-003: one row per day in its colour, the cost column only when a day has one', () => {
|
||||
const without = parse(glanceHtml([row(), row({ number: 2, stops: 0 })], tr));
|
||||
expect(texts(without, 'thead th')).toEqual(['pdf.day', 'common.date', 'pdf.plan', 'pdf.stay', '']);
|
||||
expect(texts(without, 'tbody tr:first-child td')).toEqual(['1', 'Sun, Nov 1', 'Tokyo', 'Hotel Gracery', '3']);
|
||||
// A day without stops leaves the cell empty rather than printing a zero.
|
||||
expect(texts(without, 'tbody tr:last-child td').slice(-1)[0]).toBe('');
|
||||
expect(without.querySelector('tbody tr')?.getAttribute('style')).toBe('--day:#0a84ff');
|
||||
|
||||
const withCost = parse(glanceHtml([row(), row({ number: 2, cost: '¥3,000' })], tr));
|
||||
expect(texts(withCost, 'thead th').slice(-1)[0]).toBe('pdf.costLabel');
|
||||
expect(texts(withCost, 'tbody tr:last-child td').slice(-1)[0]).toBe('¥3,000');
|
||||
|
||||
expect(glanceHtml([], tr)).toBe('');
|
||||
});
|
||||
});
|
||||
|
||||
describe('ledgerHtml', () => {
|
||||
it('FE-PDFOVERVIEW-004: each booking and stay with its date and the code to show', () => {
|
||||
const rows: LedgerRow[] = [
|
||||
{
|
||||
icon: '<svg></svg>',
|
||||
tint: '#3b82f6',
|
||||
title: 'LH716 <FRA>',
|
||||
sub: '<span>FRA → HND</span>',
|
||||
when: 'Sat, Oct 31',
|
||||
code: 'ABC123',
|
||||
},
|
||||
{
|
||||
icon: '<svg></svg>',
|
||||
tint: '#17171c',
|
||||
title: 'Hotel Gracery',
|
||||
sub: '',
|
||||
when: 'Sun, Nov 1 – Wed, Nov 4',
|
||||
code: null,
|
||||
},
|
||||
];
|
||||
const doc = parse(ledgerHtml(rows, tr));
|
||||
|
||||
expect(texts(doc, '.sec-title')).toEqual(['pdf.bookings']);
|
||||
expect(texts(doc, '.ledger-title')).toEqual(['LH716 <FRA>', 'Hotel Gracery']);
|
||||
expect(texts(doc, '.ledger-sub')).toEqual(['FRA → HND']);
|
||||
expect(texts(doc, '.ledger-when .code-chip')).toEqual(['ABC123']);
|
||||
expect(doc.querySelectorAll('.ledger-when')[1]?.textContent).toBe('Sun, Nov 1 – Wed, Nov 4');
|
||||
expect(doc.querySelectorAll('.code-chip')).toHaveLength(1);
|
||||
expect(doc.querySelector('.ledger-row')?.getAttribute('style')).toBe('--kind:#3b82f6');
|
||||
});
|
||||
|
||||
it('FE-PDFOVERVIEW-005: a trip without bookings or stays prints no list at all', () => {
|
||||
expect(ledgerHtml([], tr)).toBe('');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,239 @@
|
||||
import type { ShadeStop } from './pdfImages';
|
||||
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, string | number>) => string;
|
||||
|
||||
export interface CoverStat {
|
||||
value: string;
|
||||
label: string;
|
||||
}
|
||||
|
||||
/** One day of the route as the cover draws it: its colour and its roads, `[lat, lng]`. */
|
||||
interface CoverRouteDay {
|
||||
colour: string;
|
||||
lines: readonly (readonly [number, number])[][];
|
||||
}
|
||||
|
||||
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;
|
||||
/** Whether the shade is already painted into `image`, so none is laid over it. */
|
||||
baked?: boolean;
|
||||
/** The light TREK logo, absolute. */
|
||||
logo: string | null;
|
||||
stats: readonly CoverStat[];
|
||||
/** The routed days, drawn as the trip's shape; empty when nothing was routed. */
|
||||
route: readonly CoverRouteDay[];
|
||||
/** Every day's colour in trip order, for the band under the title. */
|
||||
ribbon: readonly string[];
|
||||
/** The first and the last day's short date, under the band's ends. */
|
||||
ribbonEnds: readonly [string, string] | null;
|
||||
tr: Translate;
|
||||
}
|
||||
|
||||
/**
|
||||
* The shade over the cover photo, top to bottom: a little at the top for the logo, clear
|
||||
* through the middle, dark at the foot for the title and the figures. Painted into the
|
||||
* photo when the export could bake it, laid over it as a gradient when not.
|
||||
*/
|
||||
export const COVER_SHADE: readonly ShadeStop[] = [
|
||||
[0, 0.35],
|
||||
[0.22, 0],
|
||||
[0.36, 0],
|
||||
[0.92, 0.82],
|
||||
];
|
||||
|
||||
/** The cover shade as a CSS gradient, for a photo the export could not bake. */
|
||||
export function coverShadeCss(): string {
|
||||
return `linear-gradient(180deg, ${COVER_SHADE.map(([at, alpha]) => `rgba(10, 10, 14, ${alpha}) ${at * 100}%`).join(', ')})`;
|
||||
}
|
||||
|
||||
const ROUTE_W = 240;
|
||||
const ROUTE_H = 170;
|
||||
const ROUTE_PAD = 14;
|
||||
/** Points drawn at most: a road trip routes to tens of thousands, the shape needs far fewer. */
|
||||
const ROUTE_MAX_POINTS = 1600;
|
||||
|
||||
type LatLng = readonly [number, number];
|
||||
|
||||
/**
|
||||
* The trip's roads as one small drawing, each day in its colour on a soft glow, with a
|
||||
* ring where the trip starts and a dot where it ends. Projected flat with the longitude
|
||||
* scaled to the middle latitude, which is true enough at the size of a trip. Empty when
|
||||
* there is no shape to draw.
|
||||
*/
|
||||
export function coverRouteSvg(days: readonly CoverRouteDay[]): string {
|
||||
const lines = days.flatMap((d) => d.lines.filter((l) => l.length > 1).map((l) => ({ colour: d.colour, points: l })));
|
||||
const points = lines.flatMap((l) => l.points);
|
||||
if (!lines.length) return '';
|
||||
const lats = points.map((p) => p[0]);
|
||||
const midLat = (Math.min(...lats) + Math.max(...lats)) / 2;
|
||||
const k = Math.cos((midLat * Math.PI) / 180);
|
||||
const xs = points.map((p) => p[1] * k);
|
||||
const ys = points.map((p) => -p[0]);
|
||||
const minX = Math.min(...xs);
|
||||
const minY = Math.min(...ys);
|
||||
const w = Math.max(...xs) - minX;
|
||||
const h = Math.max(...ys) - minY;
|
||||
const scale = Math.min(
|
||||
w > 0 ? (ROUTE_W - 2 * ROUTE_PAD) / w : Infinity,
|
||||
h > 0 ? (ROUTE_H - 2 * ROUTE_PAD) / h : Infinity
|
||||
);
|
||||
if (!Number.isFinite(scale)) return '';
|
||||
const offX = (ROUTE_W - w * scale) / 2;
|
||||
const offY = (ROUTE_H - h * scale) / 2;
|
||||
const x = (p: LatLng) => (offX + (p[1] * k - minX) * scale).toFixed(1);
|
||||
const y = (p: LatLng) => (offY + (-p[0] - minY) * scale).toFixed(1);
|
||||
const step = Math.max(1, Math.ceil(points.length / ROUTE_MAX_POINTS));
|
||||
const path = (line: readonly LatLng[]) =>
|
||||
line
|
||||
.filter((_, i) => i % step === 0 || i === line.length - 1)
|
||||
.map((p, i) => `${i ? 'L' : 'M'}${x(p)} ${y(p)}`)
|
||||
.join('');
|
||||
const drawn = lines.map((l) => ({ colour: l.colour, d: path(l.points) }));
|
||||
const first = lines[0];
|
||||
const last = lines[lines.length - 1];
|
||||
const start = first.points[0];
|
||||
const end = last.points[last.points.length - 1];
|
||||
return `<svg class="cover-route-svg" viewBox="0 0 ${ROUTE_W} ${ROUTE_H}" preserveAspectRatio="xMidYMid meet" aria-hidden="true">
|
||||
<g class="cover-route-glow" fill="none" stroke="currentColor" stroke-width="4.6" stroke-linecap="round" stroke-linejoin="round">${drawn
|
||||
.map((l) => `<path d="${l.d}"/>`)
|
||||
.join('')}</g>
|
||||
<g fill="none" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round">${drawn
|
||||
.map((l) => `<path d="${l.d}" stroke="${l.colour}"/>`)
|
||||
.join('')}</g>
|
||||
<circle class="cover-route-start" cx="${x(start)}" cy="${y(start)}" r="4.2" stroke="${first.colour}" stroke-width="2.2"/>
|
||||
<circle class="cover-route-end" cx="${x(end)}" cy="${y(end)}" r="4.2" fill="${last.colour}" stroke-width="1.6"/>
|
||||
</svg>`;
|
||||
}
|
||||
|
||||
/** The cover: the trip's photo left bright, the title, the dates and its figures. */
|
||||
export function coverHtml({
|
||||
title,
|
||||
description,
|
||||
range,
|
||||
image,
|
||||
baked = false,
|
||||
logo,
|
||||
stats,
|
||||
route,
|
||||
ribbon,
|
||||
ribbonEnds,
|
||||
tr,
|
||||
}: CoverInput): string {
|
||||
const routeSvg = coverRouteSvg(route);
|
||||
const routeCard = routeSvg
|
||||
? `<div class="cover-route"><div class="cover-route-lbl">${escHtml(tr('pdf.mapTitle'))}</div>${routeSvg}</div>`
|
||||
: '';
|
||||
const ends = ribbonEnds
|
||||
? `<div class="cover-ribbon-ends"><span>${escHtml(ribbonEnds[0])}</span><span>${escHtml(ribbonEnds[1])}</span></div>`
|
||||
: '';
|
||||
const band =
|
||||
ribbon.length > 1
|
||||
? `<div class="cover-ribbon">${ribbon.map((c) => `<span style="background:${c}"></span>`).join('')}</div>${ends}`
|
||||
: '';
|
||||
return `<section class="cover${image ? '' : ' cover-plain'}">
|
||||
<div class="cover-bg"${image ? ` style="background-image:url('${escHtml(cssUrl(image))}')"` : ''}></div>
|
||||
${baked ? '' : '<div class="cover-shade"></div>'}
|
||||
<div class="cover-top">
|
||||
${logo ? `<img src="${escHtml(logo)}" alt="TREK" />` : '<span></span>'}
|
||||
<span class="eyebrow">${escHtml(tr('pdf.travelPlan'))}</span>
|
||||
</div>
|
||||
<div class="cover-body">
|
||||
<div class="cover-main">
|
||||
<div class="cover-head">
|
||||
${range ? `<div class="cover-dates">${escHtml(range)}</div>` : ''}
|
||||
<h1 class="cover-title">${escHtml(title)}</h1>
|
||||
${description ? `<p class="cover-desc">${escHtml(description)}</p>` : ''}
|
||||
</div>
|
||||
${routeCard}
|
||||
</div>
|
||||
${band}
|
||||
<div class="cover-stats">${stats
|
||||
.map(
|
||||
(s) =>
|
||||
`<div class="cover-stat"><div class="cover-stat-num">${escHtml(s.value)}</div><div class="cover-stat-lbl">${escHtml(s.label)}</div></div>`
|
||||
)
|
||||
.join('')}</div>
|
||||
</div>
|
||||
</section>`;
|
||||
}
|
||||
|
||||
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 `<div class="sec-block">
|
||||
<div class="sec-head"><span class="sec-title">${escHtml(tr('pdf.atAGlance'))}</span></div>
|
||||
<table class="glance">
|
||||
<thead><tr>
|
||||
<th>${escHtml(tr('pdf.day'))}</th>
|
||||
<th>${escHtml(tr('common.date'))}</th>
|
||||
<th>${escHtml(tr('pdf.plan'))}</th>
|
||||
<th>${escHtml(tr('pdf.stay'))}</th>
|
||||
<th class="glance-stops">${glyph('pin', 9)}</th>
|
||||
${withCost ? `<th class="glance-end">${escHtml(tr('pdf.costLabel'))}</th>` : ''}
|
||||
</tr></thead>
|
||||
<tbody>${rows
|
||||
.map(
|
||||
(r) => `<tr style="--day:${r.colour}">
|
||||
<td><span class="glance-day">${r.number}</span></td>
|
||||
<td class="num glance-date">${escHtml(r.date)}</td>
|
||||
<td class="glance-title">${escHtml(r.title)}</td>
|
||||
<td>${escHtml(r.stay)}</td>
|
||||
<td class="num glance-stops">${r.stops || ''}</td>
|
||||
${withCost ? `<td class="num">${r.cost ?? ''}</td>` : ''}
|
||||
</tr>`
|
||||
)
|
||||
.join('')}</tbody>
|
||||
</table>
|
||||
</div>`;
|
||||
}
|
||||
|
||||
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 `<div class="sec-block ledger-block">
|
||||
<div class="sec-head"><span class="sec-title">${escHtml(tr('pdf.bookings'))}</span></div>
|
||||
<div class="ledger">${rows
|
||||
.map(
|
||||
(r) => `<div class="ledger-row" style="--kind:${r.tint}">
|
||||
<span class="ledger-icon">${r.icon}</span>
|
||||
<div><div class="ledger-title">${escHtml(r.title)}</div>${r.sub ? `<div class="ledger-sub">${r.sub}</div>` : ''}</div>
|
||||
<div class="ledger-when">${escHtml(r.when)}${r.code ? `<div><span class="code-chip">${glyph('key', 9)}${escHtml(r.code)}</span></div>` : ''}</div>
|
||||
</div>`
|
||||
)
|
||||
.join('')}</div>
|
||||
</div>`;
|
||||
}
|
||||
@@ -0,0 +1,411 @@
|
||||
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';
|
||||
import { coverShadeCss } from './tripPdfOverview';
|
||||
|
||||
/*
|
||||
* 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 <body> (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;
|
||||
--glass: rgba(255, 255, 255, 0.13);
|
||||
--glass-edge: rgba(255, 255, 255, 0.22);
|
||||
--glass-dark: rgba(14, 14, 18, 0.42);
|
||||
--glass-tile: rgba(18, 18, 24, 0.34);
|
||||
--glass-deep: rgba(12, 12, 16, 0.5);
|
||||
--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; }
|
||||
|
||||
|
||||
/* ── 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: ${coverShadeCss()};
|
||||
}
|
||||
.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: 15mm; }
|
||||
.cover-main { display: flex; align-items: flex-end; gap: 8mm; }
|
||||
.cover-head { flex: 1; min-width: 0; }
|
||||
.cover-dates {
|
||||
display: inline-block; font-family: var(--num); font-size: 9px; font-weight: 600; letter-spacing: 0.16em;
|
||||
text-transform: uppercase; color: var(--paper); padding: 5px 11px; border-radius: 99px;
|
||||
background: var(--glass-tile); border: 1px solid var(--glass-edge);
|
||||
}
|
||||
.cover-title { font-size: 54px; font-weight: 700; line-height: 1; letter-spacing: -0.025em; margin: 5mm 0 3.5mm; }
|
||||
.cover-desc { max-width: 120mm; font-size: 12px; line-height: 1.6; color: var(--on-night); }
|
||||
.cover-route {
|
||||
flex: 0 0 66mm; padding: 9px 10px 6px; border-radius: 18px;
|
||||
background: var(--glass-deep); border: 1px solid var(--glass-edge);
|
||||
}
|
||||
.cover-route-lbl {
|
||||
font-family: var(--num); font-size: 7px; font-weight: 600; letter-spacing: 0.16em;
|
||||
text-transform: uppercase; color: var(--on-night-2);
|
||||
}
|
||||
.cover-route-svg { display: block; width: 100%; height: auto; }
|
||||
.cover-route-glow { color: var(--paper); }
|
||||
.cover-route-start { fill: var(--paper); }
|
||||
.cover-route-end { stroke: var(--paper); }
|
||||
.cover-ribbon { display: flex; gap: 2px; height: 5px; margin-block-start: 8mm; }
|
||||
.cover-ribbon span { flex: 1; border-radius: 3px; }
|
||||
.cover-ribbon-ends {
|
||||
display: flex; justify-content: space-between; margin-block-start: 5px;
|
||||
font-family: var(--num); font-size: 7.5px; font-weight: 600; letter-spacing: 0.12em;
|
||||
text-transform: uppercase; color: var(--on-night-2);
|
||||
}
|
||||
.cover-stats { display: flex; flex-wrap: wrap; gap: 8px; margin-block-start: 6mm; }
|
||||
.cover-stat {
|
||||
flex: 1 1 0; min-width: max-content;
|
||||
background: var(--glass-tile); border: 1px solid var(--glass-edge); border-radius: 16px;
|
||||
padding: 12px 14px 11px;
|
||||
}
|
||||
.cover-stat-num {
|
||||
font-family: var(--num); font-size: 19px; font-weight: 600; line-height: 1.1;
|
||||
white-space: nowrap; 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;
|
||||
}
|
||||
|
||||
/* The glass is a tinted fill, not a backdrop blur: print engines leave a blur out, and
|
||||
in the preview a blur over the full-page photo had to be redrawn on every scroll. */
|
||||
|
||||
/* ── 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; }
|
||||
.glance .glance-stops { text-align: center; }
|
||||
.glance .glance-date { text-align: start; }
|
||||
.glance th.glance-stops svg { display: inline-block; vertical-align: -1px; }
|
||||
|
||||
.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 <table>, so the browser repeats the <thead> day header on every page an
|
||||
overflowing day spills onto (#1471); CSS table-header-group on a <div> 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);
|
||||
}
|
||||
.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; white-space: pre-line; }
|
||||
.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; }
|
||||
`;
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
import { describe, it, expect, vi } from 'vitest'
|
||||
import { screen, waitFor } from '@testing-library/react'
|
||||
import { act, screen, waitFor } from '@testing-library/react'
|
||||
import { render } from '../../../tests/helpers/render'
|
||||
import userEvent from '@testing-library/user-event'
|
||||
import { useRef, useState } from 'react'
|
||||
@@ -74,6 +74,34 @@ describe('NoteFormatToolbar', () => {
|
||||
expect(field().value).toBe('already a list')
|
||||
})
|
||||
|
||||
it('FE-NOTEBAR-010: pressing the numbered list button on each new line counts up instead of repeating 1.', async () => {
|
||||
const user = userEvent.setup()
|
||||
render(<Harness />)
|
||||
const numbered = screen.getByRole('button', { name: /numbered list/i })
|
||||
select(0, 0)
|
||||
|
||||
for (const [i, item] of ['Breakfast', 'Lunch', 'Dinner'].entries()) {
|
||||
if (i > 0) await user.keyboard('{Enter}')
|
||||
await user.click(numbered)
|
||||
// The toolbar puts the caret back one frame later; typing before that
|
||||
// frame would have it jump into the middle of the word.
|
||||
await act(() => new Promise<void>(resolve => requestAnimationFrame(() => resolve())))
|
||||
await user.keyboard(item)
|
||||
}
|
||||
|
||||
expect(field().value).toBe('1. Breakfast\n2. Lunch\n3. Dinner')
|
||||
})
|
||||
|
||||
it('FE-NOTEBAR-011: a multi-line selection gets a marker on every line', async () => {
|
||||
const user = userEvent.setup()
|
||||
render(<Harness initial={'Breakfast\nLunch\nDinner'} />)
|
||||
select(0, 22)
|
||||
|
||||
await user.click(screen.getByRole('button', { name: /numbered list/i }))
|
||||
|
||||
expect(field().value).toBe('1. Breakfast\n2. Lunch\n3. Dinner')
|
||||
})
|
||||
|
||||
it('FE-NOTEBAR-005: the link button leaves a placeholder URL to type over', async () => {
|
||||
const user = userEvent.setup()
|
||||
render(<Harness initial="opening hours" />)
|
||||
|
||||
@@ -2,10 +2,11 @@ import { useRef } from 'react'
|
||||
import { Bold, Italic, Strikethrough, List, ListOrdered, Link2, Quote, Code } from 'lucide-react'
|
||||
import { useTranslation } from '../../i18n'
|
||||
import { Tooltip } from './Tooltip'
|
||||
import { toggleLineMarker, type LineMarker } from './noteLineMarker'
|
||||
|
||||
type FormatAction =
|
||||
| { type: 'wrap'; before: string; after: string }
|
||||
| { type: 'line'; prefix: string }
|
||||
| { type: 'line'; marker: LineMarker }
|
||||
|
||||
interface Props {
|
||||
/** The field being formatted. Must be mounted before a button is pressed. */
|
||||
@@ -26,9 +27,9 @@ const ACTIONS: Array<{ icon: typeof Bold; labelKey: string; action: FormatAction
|
||||
{ icon: Strikethrough, labelKey: 'notes.format.strike', action: { type: 'wrap', before: '~~', after: '~~' } },
|
||||
{ icon: Code, labelKey: 'notes.format.code', action: { type: 'wrap', before: '`', after: '`' } },
|
||||
{ icon: Link2, labelKey: 'notes.format.link', action: { type: 'wrap', before: '[', after: '](https://)' } },
|
||||
{ icon: List, labelKey: 'notes.format.list', action: { type: 'line', prefix: '- ' } },
|
||||
{ icon: ListOrdered, labelKey: 'notes.format.orderedList', action: { type: 'line', prefix: '1. ' } },
|
||||
{ icon: Quote, labelKey: 'notes.format.quote', action: { type: 'line', prefix: '> ' } },
|
||||
{ icon: List, labelKey: 'notes.format.list', action: { type: 'line', marker: 'bullet' } },
|
||||
{ icon: ListOrdered, labelKey: 'notes.format.orderedList', action: { type: 'line', marker: 'ordered' } },
|
||||
{ icon: Quote, labelKey: 'notes.format.quote', action: { type: 'line', marker: 'quote' } },
|
||||
]
|
||||
|
||||
/**
|
||||
@@ -68,13 +69,9 @@ export default function NoteFormatToolbar({ textareaRef, onChange, compact, vari
|
||||
? [start + action.before.length, end + action.before.length]
|
||||
: [start + action.before.length, start + action.before.length]
|
||||
} else {
|
||||
const lineStart = value.lastIndexOf('\n', start - 1) + 1
|
||||
const alreadyPrefixed = value.startsWith(action.prefix, lineStart)
|
||||
next = alreadyPrefixed
|
||||
? value.slice(0, lineStart) + value.slice(lineStart + action.prefix.length)
|
||||
: value.slice(0, lineStart) + action.prefix + value.slice(lineStart)
|
||||
const shift = alreadyPrefixed ? -action.prefix.length : action.prefix.length
|
||||
caret = [Math.max(lineStart, start + shift), Math.max(lineStart, end + shift)]
|
||||
const result = toggleLineMarker(value, start, end, action.marker)
|
||||
next = result.value
|
||||
caret = result.selection
|
||||
}
|
||||
|
||||
pendingSelection.current = caret
|
||||
|
||||
@@ -0,0 +1,63 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { toggleLineMarker } from './noteLineMarker';
|
||||
|
||||
describe('toggleLineMarker', () => {
|
||||
it('FE-NOTELINE-001: numbers a new item after the one above instead of starting at 1 again', () => {
|
||||
const value = '1. Breakfast\nLunch';
|
||||
expect(toggleLineMarker(value, value.length, value.length, 'ordered').value).toBe('1. Breakfast\n2. Lunch');
|
||||
});
|
||||
|
||||
it('FE-NOTELINE-002: keeps counting from whatever number the item above has', () => {
|
||||
const value = '4. Museum\nDinner';
|
||||
expect(toggleLineMarker(value, value.length, value.length, 'ordered').value).toBe('4. Museum\n5. Dinner');
|
||||
});
|
||||
|
||||
it('FE-NOTELINE-003: starts at 1 when the line above is no numbered item', () => {
|
||||
expect(toggleLineMarker('Meals\nBreakfast', 8, 8, 'ordered').value).toBe('Meals\n1. Breakfast');
|
||||
expect(toggleLineMarker('Breakfast', 0, 0, 'ordered').value).toBe('1. Breakfast');
|
||||
});
|
||||
|
||||
it('FE-NOTELINE-004: numbers every selected line in order and skips the blank ones', () => {
|
||||
const value = 'Breakfast\nLunch\n\nDinner';
|
||||
const result = toggleLineMarker(value, 0, value.length, 'ordered');
|
||||
expect(result.value).toBe('1. Breakfast\n2. Lunch\n\n3. Dinner');
|
||||
expect(result.selection).toEqual([0, result.value.length]);
|
||||
});
|
||||
|
||||
it('FE-NOTELINE-005: renumbers a selection that mixes numbered and plain lines', () => {
|
||||
const value = '1. Breakfast\n1. Lunch\nDinner';
|
||||
expect(toggleLineMarker(value, 0, value.length, 'ordered').value).toBe('1. Breakfast\n2. Lunch\n3. Dinner');
|
||||
});
|
||||
|
||||
it('FE-NOTELINE-006: removes the numbers when every selected line already has one', () => {
|
||||
const value = '1. Breakfast\n2. Lunch';
|
||||
expect(toggleLineMarker(value, 0, value.length, 'ordered').value).toBe('Breakfast\nLunch');
|
||||
});
|
||||
|
||||
it('FE-NOTELINE-007: removes the number from a single item, whatever the number is', () => {
|
||||
const result = toggleLineMarker('1. a\n12. Dinner', 10, 10, 'ordered');
|
||||
expect(result.value).toBe('1. a\nDinner');
|
||||
expect(result.selection).toEqual([6, 6]);
|
||||
});
|
||||
|
||||
it('FE-NOTELINE-008: bullets and quotes apply to each selected line, without doubling an existing marker', () => {
|
||||
const value = 'one\n- two\nthree';
|
||||
expect(toggleLineMarker(value, 0, value.length, 'bullet').value).toBe('- one\n- two\n- three');
|
||||
expect(toggleLineMarker('one\ntwo', 0, 7, 'quote').value).toBe('> one\n> two');
|
||||
});
|
||||
|
||||
it('FE-NOTELINE-009: a selection ending right after a newline leaves the next line alone', () => {
|
||||
const value = 'one\ntwo\nthree';
|
||||
expect(toggleLineMarker(value, 0, 8, 'bullet').value).toBe('- one\n- two\nthree');
|
||||
});
|
||||
|
||||
it('FE-NOTELINE-010: the caret moves with the text on a single line', () => {
|
||||
const value = 'first\nsecond';
|
||||
expect(toggleLineMarker(value, 8, 8, 'bullet')).toEqual({ value: 'first\n- second', selection: [10, 10] });
|
||||
});
|
||||
|
||||
it('FE-NOTELINE-011: an empty line still gets the marker, so a list can be started on it', () => {
|
||||
expect(toggleLineMarker('', 0, 0, 'ordered')).toEqual({ value: '1. ', selection: [3, 3] });
|
||||
expect(toggleLineMarker('1. Breakfast\n', 13, 13, 'ordered').value).toBe('1. Breakfast\n2. ');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,64 @@
|
||||
export type LineMarker = 'bullet' | 'ordered' | 'quote';
|
||||
|
||||
const PATTERN: Record<LineMarker, RegExp> = {
|
||||
bullet: /^- /,
|
||||
ordered: /^\d+\. /,
|
||||
quote: /^> /,
|
||||
};
|
||||
|
||||
const FIXED_PREFIX: Record<Exclude<LineMarker, 'ordered'>, string> = {
|
||||
bullet: '- ',
|
||||
quote: '> ',
|
||||
};
|
||||
|
||||
export interface LineMarkerResult {
|
||||
value: string;
|
||||
selection: [number, number];
|
||||
}
|
||||
|
||||
/** The number an ordered item gets when it is added right below `lineStart`'s previous line. */
|
||||
function nextNumberAt(value: string, lineStart: number): number {
|
||||
if (lineStart === 0) return 1;
|
||||
const prevStart = value.lastIndexOf('\n', lineStart - 2) + 1;
|
||||
const match = /^(\d+)\. /.exec(value.slice(prevStart, lineStart - 1));
|
||||
return match ? Number(match[1]) + 1 : 1;
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds or removes a line marker (bullet, number, quote) on every line the
|
||||
* selection touches.
|
||||
*
|
||||
* Numbers continue from the item above, so pressing the button on each new
|
||||
* line writes 1. 2. 3. instead of 1. 1. 1. Markdown renders both the same,
|
||||
* but the field is what people read while they write. A selection over several
|
||||
* lines is formatted line by line and skips the blank ones in between.
|
||||
*/
|
||||
export function toggleLineMarker(value: string, start: number, end: number, marker: LineMarker): LineMarkerResult {
|
||||
const blockStart = value.lastIndexOf('\n', start - 1) + 1;
|
||||
// A selection that ends right after a newline stops on the line above it.
|
||||
const last = end > start && value[end - 1] === '\n' ? end - 1 : end;
|
||||
const newline = value.indexOf('\n', last);
|
||||
const blockEnd = newline === -1 ? value.length : newline;
|
||||
|
||||
const lines = value.slice(blockStart, blockEnd).split('\n');
|
||||
const multi = lines.length > 1;
|
||||
const formats = (line: string) => !multi || line.trim() !== '';
|
||||
const pattern = PATTERN[marker];
|
||||
const remove = lines.some(formats) && lines.filter(formats).every((line) => pattern.test(line));
|
||||
|
||||
let number = nextNumberAt(value, blockStart);
|
||||
const next = lines.map((line) => {
|
||||
if (!formats(line)) return line;
|
||||
if (remove) return line.replace(pattern, '');
|
||||
if (marker === 'ordered') return `${number++}. ${line.replace(pattern, '')}`;
|
||||
return pattern.test(line) ? line : FIXED_PREFIX[marker] + line;
|
||||
});
|
||||
|
||||
const block = next.join('\n');
|
||||
const result = value.slice(0, blockStart) + block + value.slice(blockEnd);
|
||||
|
||||
if (multi) return { value: result, selection: [blockStart, blockStart + block.length] };
|
||||
// One line: the caret moves with the text, never in front of the line.
|
||||
const shift = block.length - (blockEnd - blockStart);
|
||||
return { value: result, selection: [Math.max(blockStart, start + shift), Math.max(blockStart, end + shift)] };
|
||||
}
|
||||
@@ -81,19 +81,30 @@ describe('hidesOnMiddleDay', () => {
|
||||
describe('getTransportRouteEndpoints', () => {
|
||||
const pickup = { role: 'from', lat: 48.1, lng: 11.5 }
|
||||
const dropoff = { role: 'to', lat: 52.5, lng: 13.4 }
|
||||
// An overnight train spanning day 1 (departure) through day 3 (arrival).
|
||||
const rental = { type: 'train', day_id: 1, end_day_id: 3, endpoints: [pickup, dropoff] }
|
||||
// A car rental spanning day 1 (pickup) through day 3 (drop-off).
|
||||
const rental = { day_id: 1, end_day_id: 3, endpoints: [pickup, dropoff] }
|
||||
const car = { ...rental, type: 'car' }
|
||||
|
||||
it('routes to the pickup only on the start day of a multi-day rental', () => {
|
||||
it('routes to the departure only on the start day of a booking spanning days', () => {
|
||||
expect(getTransportRouteEndpoints(rental, 1)).toEqual({ from: { lat: 48.1, lng: 11.5 }, to: null })
|
||||
})
|
||||
|
||||
it('routes from the drop-off only on the end day', () => {
|
||||
it('routes from the arrival only on the end day', () => {
|
||||
expect(getTransportRouteEndpoints(rental, 3)).toEqual({ from: null, to: { lat: 52.5, lng: 13.4 } })
|
||||
})
|
||||
|
||||
it('adds no waypoints on the days in between (regression for #1210)', () => {
|
||||
expect(getTransportRouteEndpoints(rental, 2)).toEqual({ from: null, to: null })
|
||||
expect(getTransportRouteEndpoints(car, 2)).toEqual({ from: null, to: null })
|
||||
})
|
||||
|
||||
it('passes a rental the traveller drives through its pickup and its return', () => {
|
||||
// The drive goes to the desk and on from it, and to the return and on from it.
|
||||
expect(getTransportRouteEndpoints(car, 1)).toEqual({ from: { lat: 48.1, lng: 11.5 }, to: { lat: 48.1, lng: 11.5 } })
|
||||
expect(getTransportRouteEndpoints(car, 3)).toEqual({ from: { lat: 52.5, lng: 13.4 }, to: { lat: 52.5, lng: 13.4 } })
|
||||
const bike = { ...rental, type: 'bicycle' }
|
||||
expect(getTransportRouteEndpoints(bike, 3)).toEqual({ from: { lat: 52.5, lng: 13.4 }, to: { lat: 52.5, lng: 13.4 } })
|
||||
})
|
||||
|
||||
it('uses both endpoints for a single-day transport', () => {
|
||||
|
||||
@@ -82,12 +82,23 @@ export function isCarrierTransport(r: { type?: string | null }): boolean {
|
||||
return !!r.type && CARRIER_TRANSPORT_TYPES.has(r.type)
|
||||
}
|
||||
|
||||
/**
|
||||
* Vehicles a traveller drives themselves. Picked up or returned on another day than the
|
||||
* booking's other end, such a booking is a stop the day's drive passes through: you get to
|
||||
* the rental desk and drive on from it, and you drive to the return and leave from there.
|
||||
* Anything else that spans days is ridden, an overnight train or bus, so the day it starts
|
||||
* only leaves from its departure and the day it ends only arrives at its destination.
|
||||
*/
|
||||
const SELF_DRIVEN_TYPES = new Set(['car', 'bicycle'])
|
||||
|
||||
/**
|
||||
* The route waypoints a transport contributes on a given day, respecting multi-day spans.
|
||||
* A car rental (or any reservation whose span covers several days) is only routed to on its
|
||||
* pickup day (the departure endpoint) and from on its drop-off day (the arrival endpoint) — on
|
||||
* the days in between you simply hold the vehicle, so it adds no waypoints and must not pull the
|
||||
* route to those points. Single-day transports contribute both endpoints.
|
||||
* A reservation whose span covers several days is routed to its departure on its first day
|
||||
* and from its arrival on its last; a rental the traveller drives (SELF_DRIVEN_TYPES) is
|
||||
* routed through its pickup and its return instead, so the drive to the rental desk, the one
|
||||
* away from it and the one to the return all show. On the days in between you simply hold
|
||||
* the vehicle, so it adds no waypoints and must not pull the route to those points.
|
||||
* Single-day transports contribute both endpoints.
|
||||
*/
|
||||
export function getTransportRouteEndpoints(
|
||||
r: any,
|
||||
@@ -111,11 +122,12 @@ export function getTransportRouteEndpoints(
|
||||
if (legIdx != null) return point(ordered[role === 'from' ? legIdx : legIdx + 1])
|
||||
return point((r.endpoints || []).find((x: { role?: string }) => x.role === role))
|
||||
}
|
||||
const passedThrough = SELF_DRIVEN_TYPES.has(r.type)
|
||||
switch (getSpanPhase(r, dayId)) {
|
||||
case 'start':
|
||||
return { from: ep('from'), to: null }
|
||||
return { from: ep('from'), to: passedThrough ? ep('from') : null }
|
||||
case 'end':
|
||||
return { from: null, to: ep('to') }
|
||||
return { from: passedThrough ? ep('to') : null, to: ep('to') }
|
||||
case 'middle':
|
||||
return { from: null, to: null }
|
||||
default:
|
||||
|
||||
@@ -11,7 +11,7 @@ import type {
|
||||
Accommodation, Assignment, Day, DayNote, Place, Reservation, RouteSegment, TranslationFn,
|
||||
} from '../../../../src/types'
|
||||
|
||||
// FE-MOB-PTLM-001 to FE-MOB-PTLM-060
|
||||
// FE-MOB-PTLM-001 to FE-MOB-PTLM-063
|
||||
|
||||
const DAYS = [
|
||||
{ id: 1, trip_id: 1, day_number: 1, date: '2026-05-01', title: null },
|
||||
@@ -900,3 +900,59 @@ describe('planTimelineModel — chronology helpers', () => {
|
||||
expect(breaksChronology([...drawn, breakfast], 2, getDisplayTimeForDay)).toBe(true)
|
||||
})
|
||||
})
|
||||
|
||||
describe('planTimelineModel: a rental car picked up or returned on the day', () => {
|
||||
// A car hired on day 1 and returned on day 2 before an evening flight home: the
|
||||
// traveller drives the car to the return desk, so that drive belongs to the day.
|
||||
const MIRADOR = { lat: 27.756, lng: -15.571 }
|
||||
const PICKUP = { lat: 27.95, lng: -15.4 }
|
||||
const RETURN = { lat: 27.92, lng: -15.38 }
|
||||
const LPA = { lat: 27.932, lng: -15.387 }
|
||||
const MUC = { lat: 48.353, lng: 11.786 }
|
||||
const endpoint = (role: 'from' | 'to', sequence: number, name: string, at: { lat: number; lng: number }) => ({
|
||||
role, sequence, name, code: null, ...at, timezone: null, local_date: null, local_time: null,
|
||||
})
|
||||
const car = (dayId: number, endDayId: number) => buildReservation({
|
||||
id: 71, type: 'car', title: 'Avis', day_id: dayId, end_day_id: endDayId,
|
||||
reservation_time: '2026-05-01T10:00', reservation_end_time: '2026-05-02T17:00',
|
||||
endpoints: [endpoint('from', 0, 'Avis pickup', PICKUP), endpoint('to', 1, 'Avis return', RETURN)],
|
||||
})
|
||||
const flightHome = buildReservation({
|
||||
id: 72, type: 'flight', title: 'Home', day_id: 2, end_day_id: 2,
|
||||
reservation_time: '2026-05-02T20:00', reservation_end_time: '2026-05-02T23:55',
|
||||
endpoints: [endpoint('from', 0, 'LPA', LPA), endpoint('to', 1, 'MUC', MUC)],
|
||||
})
|
||||
const mirador = buildAssignment({ id: 31, day_id: 2, order_index: 0, place: place(931, 'Mirador de las Dunas', MIRADOR.lat, MIRADOR.lng) })
|
||||
|
||||
const planOf = (dayId: number, dayAssignments: Assignment[], reservations: Reservation[]) => {
|
||||
const merged = getMergedItems({
|
||||
dayAssignments,
|
||||
dayNotes: [],
|
||||
dayTransports: getTransportForDay({ reservations, dayId, dayAssignmentIds: dayAssignments.map(a => a.id), days: DAYS }),
|
||||
dayId,
|
||||
})
|
||||
const runs = buildDayRouteRuns(dayId, {
|
||||
days: DAYS, assignments: { [String(dayId)]: dayAssignments }, reservations, accommodations: [], optimizeFromAccommodation: false,
|
||||
})
|
||||
return { runs, rows: buildPlanRows({ merged, reservations, routeSegments: segmentsOf(runs), dayId }) }
|
||||
}
|
||||
const at = (p: { lat: number; lng: number }): [number, number] => [p.lat, p.lng]
|
||||
|
||||
it('FE-MOB-PTLM-062: on the return day the drive from the last stop to the return desk shows and is drawn', () => {
|
||||
const { runs, rows } = planOf(2, [mirador], [car(1, 2), flightHome])
|
||||
expect(rows.map(r => r.key)).toEqual(['pl-31', 'conn-pl-31', 'tr-71', 'tr-72'])
|
||||
expect(connectors(rows).map(s => [s.from, s.to])).toEqual([[at(MIRADOR), at(RETURN)]])
|
||||
// The map draws the same drive, ending at the return desk.
|
||||
expect(runs.map(run => run.map(p => [p.lat, p.lng]))).toEqual([[at(MIRADOR), at(RETURN)]])
|
||||
})
|
||||
|
||||
it('FE-MOB-PTLM-063: on the pickup day the drive away from the rental desk shows under the booking', () => {
|
||||
const later = buildAssignment({ id: 32, day_id: 2, order_index: 0, place: place(932, 'Dunes', MIRADOR.lat, MIRADOR.lng, '12:00') })
|
||||
const pickup = buildReservation({
|
||||
...car(2, 3), reservation_time: '2026-05-02T10:00', reservation_end_time: '2026-05-03T17:00',
|
||||
})
|
||||
const { rows } = planOf(2, [later], [pickup])
|
||||
expect(rows.map(r => r.key)).toEqual(['tr-71', 'conn-tr-71', 'pl-32'])
|
||||
expect(connectors(rows).map(s => [s.from, s.to])).toEqual([[at(PICKUP), at(MIRADOR)]])
|
||||
})
|
||||
})
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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;
|
||||
|
||||
Reference in New Issue
Block a user