mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-11-23 13:23:04 +00:00
Compare commits
16 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 965b519f23 | |||
| 3ec7cc73b2 | |||
| 493571c559 | |||
| 4212fcdfc8 | |||
| 28f750f7c4 | |||
| 8c9cf4a80c | |||
| b33d592325 | |||
| 590b174dd1 | |||
| 2a833c4ba9 | |||
| a5de1bc52d | |||
| 1b20214a7f | |||
| 3e8496dce6 | |||
| ea1b75e639 | |||
| c0f6551cf4 | |||
| 1fdf74e7f2 | |||
| c7de823c78 |
@@ -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")),
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -121,6 +121,9 @@ class TrekBridgeViewController: CAPBridgeViewController {
|
||||
right: max(0, safe.right - (window.bounds.maxX - frame.maxX))
|
||||
)
|
||||
let corner = cornerElement(in: frame, window: window)
|
||||
if corner != .zero, cornerWindowSizes.insert(sizeKey(window.bounds.size)).inserted {
|
||||
setNeedsStatusBarAppearanceUpdate()
|
||||
}
|
||||
if !force, insets == publishedSafeArea, corner == publishedCorner { return }
|
||||
publishedSafeArea = insets
|
||||
publishedCorner = corner
|
||||
@@ -139,15 +142,36 @@ class TrekBridgeViewController: CAPBridgeViewController {
|
||||
|
||||
private var publishedCorner: UIEdgeInsets?
|
||||
|
||||
// MARK: - The status bar beside a corner element
|
||||
|
||||
/// The window sizes on which a corner element was seen. On an iPhone Duo
|
||||
/// that element is the status capsule, so the app hides the status bar
|
||||
/// there to take the capsule away; whatever still covers the corner stays
|
||||
/// in the safe area the page keeps clear of. A size stays in the set
|
||||
/// once seen: with the bar hidden the next measure may find no corner, and
|
||||
/// showing the bar again would bring the capsule back and start over. The
|
||||
/// folded and the unfolded display differ in size, so each keeps its own
|
||||
/// answer, and a device without such an element never hides its bar.
|
||||
private var cornerWindowSizes = Set<String>()
|
||||
|
||||
private func sizeKey(_ size: CGSize) -> String {
|
||||
"\(Int(size.width.rounded()))x\(Int(size.height.rounded()))"
|
||||
}
|
||||
|
||||
override var prefersStatusBarHidden: Bool {
|
||||
if super.prefersStatusBarHidden { return true }
|
||||
guard let size = view.window?.bounds.size else { return false }
|
||||
return cornerWindowSizes.contains(sizeKey(size))
|
||||
}
|
||||
|
||||
/// An element in a top corner of the screen, such as the status capsule of
|
||||
/// an iPhone Duo: how far down it reaches (top) and how wide it is on its
|
||||
/// side (left/right), in the web view's coordinates; zero where there is
|
||||
/// none. iOS 26 tells a corner apart from a whole edge: the safe area with
|
||||
/// the corner avoided vertically reaches lower than the one avoiding it
|
||||
/// horizontally, which in turn is wider on the corner's side. The page puts
|
||||
/// its top bar beside the element and starts its content below it, using
|
||||
/// the full width (mobile.css), instead of giving up a strip of the whole
|
||||
/// height.
|
||||
/// horizontally, which in turn is wider on the corner's side. The page
|
||||
/// counts it into its safe area (mobile.css): upright its content starts
|
||||
/// below the element, on a wide window it leaves the element's side free.
|
||||
private func cornerElement(in frame: CGRect, window: UIWindow) -> UIEdgeInsets {
|
||||
guard #available(iOS 26.0, *) else { return .zero }
|
||||
let vertical = view.edgeInsets(for: .safeArea(cornerAdaptation: .vertical))
|
||||
|
||||
@@ -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)] };
|
||||
}
|
||||
@@ -14,7 +14,6 @@ import { useNativeCapabilities } from '../native/capabilities'
|
||||
import { isNativeIos } from '../native/platform'
|
||||
import { useWindowFold } from '../native/windowFold'
|
||||
import './mobile.css'
|
||||
import './corner.css'
|
||||
|
||||
interface MobileShellProps {
|
||||
isPhone: boolean
|
||||
|
||||
@@ -48,7 +48,7 @@ export default function MImageViewer({
|
||||
type="button"
|
||||
onClick={onClose}
|
||||
aria-label={t('collab.chat.closeImage')}
|
||||
className="m-corner-beside absolute end-4 top-[calc(var(--m-safe-top,12px)+4px)] z-10 flex h-10 w-10 items-center justify-center rounded-full bg-[color:var(--m-viewer-btn)] text-[color:var(--m-viewer-ink)]"
|
||||
className="m-safe-row absolute end-4 top-[calc(var(--m-safe-top,12px)+4px)] z-10 flex h-10 w-10 items-center justify-center rounded-full bg-[color:var(--m-viewer-btn)] text-[color:var(--m-viewer-ink)]"
|
||||
>
|
||||
<X size={20} strokeWidth={2} />
|
||||
</button>
|
||||
|
||||
@@ -89,7 +89,7 @@ export function MSectionList({
|
||||
* width on both screens.
|
||||
*/
|
||||
export const SECTION_SCREEN =
|
||||
'm-corner-flow px-4 pb-[calc(var(--bottom-nav-h,84px)+16px)] pt-[var(--m-safe-top,12px)] wide:mx-auto wide:max-w-[1040px] wide:px-6 split:grid split:max-w-[1240px] split:grid-cols-[260px_minmax(0,1fr)] split:items-start split:gap-8';
|
||||
'px-4 pb-[calc(var(--bottom-nav-h,84px)+16px)] pt-[var(--m-safe-top,12px)] wide:mx-auto wide:max-w-[1040px] wide:px-6 split:grid split:max-w-[1240px] split:grid-cols-[260px_minmax(0,1fr)] split:items-start split:gap-8';
|
||||
|
||||
interface MSectionNavProps {
|
||||
title: string;
|
||||
|
||||
@@ -86,11 +86,11 @@ type MSheetWideAnchor = 'center' | 'rail-foot'
|
||||
* docked sheet just above the dock; neither lies across the dock.
|
||||
*/
|
||||
const REGION: Record<MSheetVariant, string> = {
|
||||
card: 'inset-x-[14px] top-[max(var(--m-safe-top,12px),var(--m-corner-clear,0px))] bottom-[calc(var(--bottom-nav-h,84px)+12px)] justify-center',
|
||||
card: 'inset-x-[14px] top-[var(--m-safe-top,12px)] bottom-[calc(var(--bottom-nav-h,84px)+12px)] justify-center',
|
||||
// On a phone on its side the gap it keeps at the top would leave it a strip
|
||||
// of a few rows, so there it may rise nearly to the top.
|
||||
bottom:
|
||||
'inset-x-4 top-[max(calc(var(--m-safe-top,12px)+56px),var(--m-corner-clear,0px))] bottom-[calc(var(--bottom-nav-h,84px)+16px)] justify-end short:top-[calc(var(--m-safe-top,12px)+8px)]',
|
||||
'inset-x-4 top-[calc(var(--m-safe-top,12px)+56px)] bottom-[calc(var(--bottom-nav-h,84px)+16px)] justify-end short:top-[calc(var(--m-safe-top,12px)+8px)]',
|
||||
drawer: 'start-0 top-0 bottom-0 w-[78%] max-w-[320px]',
|
||||
}
|
||||
|
||||
@@ -109,15 +109,15 @@ const WIDE_REGION: Record<MSheetWideAnchor, string> = {
|
||||
// A form on a window as short as a phone on its side: a sheet the window's
|
||||
// full height, over the dock, as wide as a form reads well and no wider.
|
||||
const SHORT_FORM_REGION =
|
||||
'short:inset-x-4 short:top-[max(env(safe-area-inset-top,0px),8px)] short:bottom-0 short:items-center short:justify-stretch'
|
||||
'short:inset-x-4 short:top-[max(var(--m-safe-t,0px),8px)] short:bottom-0 short:items-center short:justify-stretch'
|
||||
const SHORT_FORM_BOX = 'short:max-w-[640px] short:flex-1'
|
||||
|
||||
/** The region the sheet stands in, on a phone and on a wide window. */
|
||||
function regionClass(variant: MSheetVariant, anchor: MSheetWideAnchor = 'center', form = false): string {
|
||||
const base = 'pointer-events-none absolute flex flex-col'
|
||||
if (variant === 'drawer') return `${base} ${REGION.drawer}`
|
||||
// m-corner-side: on a wide window the sheet keeps off a corner element's side (a Duo's status capsule).
|
||||
return `${base} m-corner-side ${REGION[variant]} ${WIDE_REGION[anchor]}${form ? ` ${SHORT_FORM_REGION}` : ''}`
|
||||
// m-safe-trail: on a wide window the sheet keeps off the trailing side's safe area (a Duo's status capsule).
|
||||
return `${base} m-safe-trail ${REGION[variant]} ${WIDE_REGION[anchor]}${form ? ` ${SHORT_FORM_REGION}` : ''}`
|
||||
}
|
||||
|
||||
/** The sheet's own box inside the region: its width, and the arrow when it has one. */
|
||||
|
||||
@@ -1,31 +0,0 @@
|
||||
/* ── An element in a top corner (an iPhone Duo's status capsule) ──────────────
|
||||
Beside mobile.css, which holds the variables these read (--m-corner-*).
|
||||
For the screens that place their own controls rather than sit in .m-page
|
||||
(the trip, its map). Every variable is 0 without such an element, so these
|
||||
change nothing on any other device.
|
||||
m-corner-beside: a control row in the corner's height ends before it.
|
||||
m-corner-side: a layer that fills the page ends before the corner's side on
|
||||
a wide window (--m-corner-side-*, 0 upright, where content starts below the
|
||||
corner through --m-corner-clear instead).
|
||||
The element sits where the hardware puts it, whatever the reading
|
||||
direction, so right to left swaps the two sides back. */
|
||||
.m-corner-beside {
|
||||
margin-inline: var(--m-corner-l-gap, 0px) var(--m-corner-r-gap, 0px);
|
||||
}
|
||||
html[dir='rtl'] .m-corner-beside {
|
||||
margin-inline: var(--m-corner-r-gap, 0px) var(--m-corner-l-gap, 0px);
|
||||
}
|
||||
.m-corner-side {
|
||||
margin-inline: var(--m-corner-side-l, 0px) var(--m-corner-side-r, 0px);
|
||||
}
|
||||
html[dir='rtl'] .m-corner-side {
|
||||
margin-inline: var(--m-corner-side-r, 0px) var(--m-corner-side-l, 0px);
|
||||
}
|
||||
/* m-corner-beside-in: m-corner-beside for a row inside .m-page, upright only
|
||||
(on a wide window the page itself already ends before the corner). */
|
||||
.m-corner-beside-in {
|
||||
margin-inline: var(--m-corner-in-l, 0px) var(--m-corner-in-r, 0px);
|
||||
}
|
||||
html[dir='rtl'] .m-corner-beside-in {
|
||||
margin-inline: var(--m-corner-in-r, 0px) var(--m-corner-in-l, 0px);
|
||||
}
|
||||
@@ -66,43 +66,26 @@
|
||||
* publishSafeArea) is a floor under env(): where a release lays the web view
|
||||
* out below the status bar, WebKit reports 0 while a camera in a corner still
|
||||
* reaches into the page. In a browser the variables are unset: env() alone. */
|
||||
--m-safe-t: max(env(safe-area-inset-top, 0px), var(--trek-native-safe-top, 0px));
|
||||
--m-safe-l: max(env(safe-area-inset-left, 0px), var(--trek-native-safe-left, 0px));
|
||||
--m-safe-r: max(env(safe-area-inset-right, 0px), var(--trek-native-safe-right, 0px));
|
||||
--m-safe-top: calc(var(--m-safe-t) + 12px);
|
||||
--m-raw-t: max(env(safe-area-inset-top, 0px), var(--trek-native-safe-top, 0px));
|
||||
--m-raw-l: max(env(safe-area-inset-left, 0px), var(--trek-native-safe-left, 0px));
|
||||
--m-raw-r: max(env(safe-area-inset-right, 0px), var(--trek-native-safe-right, 0px));
|
||||
/* An element in a top corner of the screen, such as an iPhone Duo's status
|
||||
* capsule, as the iOS app measures it (TrekBridgeViewController
|
||||
* cornerElement): how far down it reaches and how wide it is on its side.
|
||||
* The floating bars stand beside it; the page keeps the side's full width
|
||||
* and starts below it, instead of giving up a strip of the whole height to
|
||||
* an inset that only exists in the corner. 0 everywhere else. */
|
||||
--m-corner-b: var(--trek-native-corner-bottom, 0px);
|
||||
--m-bar-l: max(var(--m-safe-l), var(--trek-native-corner-left, 0px));
|
||||
--m-bar-r: max(var(--m-safe-r), var(--trek-native-corner-right, 0px));
|
||||
--m-page-l: max(0px, var(--m-safe-l) - var(--trek-native-corner-left, 0px));
|
||||
--m-page-r: max(0px, var(--m-safe-r) - var(--trek-native-corner-right, 0px));
|
||||
/* A bar's side inset plus a little air: next to a Duo's status capsule a
|
||||
* bar that ends exactly at the inset reads as touching it. Without an inset
|
||||
* cornerElement), counts as safe area like a notch, so every screen keeps
|
||||
* clear of it without knowing it is there. Upright the top inset reaches
|
||||
* below it and the sides keep their full width (iOS reports the element as
|
||||
* a side inset too, which is taken back out); on a wide window its side is
|
||||
* given up over the whole height instead (below), where a band across the
|
||||
* top would cost a quarter of the height. 0 on every other device. */
|
||||
--m-safe-t: max(var(--m-raw-t), var(--trek-native-corner-bottom, 0px));
|
||||
--m-safe-l: max(0px, var(--m-raw-l) - var(--trek-native-corner-left, 0px));
|
||||
--m-safe-r: max(0px, var(--m-raw-r) - var(--trek-native-corner-right, 0px));
|
||||
--m-safe-top: calc(var(--m-safe-t) + 12px);
|
||||
/* A side inset plus a little air, for a bar beside it: a bar that ends
|
||||
* exactly at the inset reads as touching what is there. Without an inset
|
||||
* the air is 0 too (min() of 0 and 8px). */
|
||||
--m-safe-l-gap: calc(var(--m-bar-l) + min(var(--m-bar-l), 8px));
|
||||
--m-safe-r-gap: calc(var(--m-bar-r) + min(var(--m-bar-r), 8px));
|
||||
/* The corner element alone, with the same air, for the screens that place
|
||||
* their own controls (the trip, the map): a control row in the corner's
|
||||
* height ends this far from the screen's side (m-corner-beside). Physical
|
||||
* sides, as the element is: right to left does not move it. */
|
||||
--m-corner-l-gap: calc(var(--trek-native-corner-left, 0px) + min(var(--trek-native-corner-left, 0px), 8px));
|
||||
--m-corner-r-gap: calc(var(--trek-native-corner-right, 0px) + min(var(--trek-native-corner-right, 0px), 8px));
|
||||
/* Where the content of a screen that places its own scroll body begins at
|
||||
* the latest, so its first row is not under the corner element: just below
|
||||
* it (m-corner-below). Upright that is the cheaper way round; on a wide
|
||||
* window the page gives up the corner's side instead (below). 0 elsewhere. */
|
||||
--m-corner-clear: calc(var(--m-corner-b) + min(var(--m-corner-b), 10px));
|
||||
--m-corner-side-l: 0px;
|
||||
--m-corner-side-r: 0px;
|
||||
/* The same air for a control row inside .m-page, which on a wide window has
|
||||
* already given up the corner's side (m-corner-beside-in). */
|
||||
--m-corner-in-l: var(--m-corner-l-gap);
|
||||
--m-corner-in-r: var(--m-corner-r-gap);
|
||||
--m-safe-l-gap: calc(var(--m-safe-l) + min(var(--m-safe-l), 8px));
|
||||
--m-safe-r-gap: calc(var(--m-safe-r) + min(var(--m-safe-r), 8px));
|
||||
/* The navigation rail's share of the leading edge (wide windows only), what
|
||||
* every full-width fixed bar and the page column start after. */
|
||||
--m-rail-w: 0px;
|
||||
@@ -115,21 +98,15 @@
|
||||
* reads the same values as the shell. */
|
||||
html:has(.m-shell[data-size='wide'], .m-shell[data-size='split']) .m-root {
|
||||
--bottom-nav-h: env(safe-area-inset-bottom, 0px);
|
||||
--m-rail-w: calc(var(--m-bar-l) + 100px);
|
||||
--m-rail-w: calc(var(--m-safe-l) + 100px);
|
||||
/* A wide window gives up the corner element's side over the whole height,
|
||||
* as an iPhone on its side does for its camera: on an unfolded Duo lifting
|
||||
* every page below the status capsule cost a quarter of the height. The
|
||||
* rail already takes the leading side, so only the trailing side's corner
|
||||
* counts here. */
|
||||
--m-corner-clear: 0px;
|
||||
--m-corner-side-r: var(--m-corner-r-gap);
|
||||
--m-corner-in-l: 0px;
|
||||
--m-corner-in-r: 0px;
|
||||
* as an iPhone on its side does for its camera, and keeps the top as it is. */
|
||||
--m-safe-t: var(--m-raw-t);
|
||||
--m-safe-l: max(var(--m-raw-l), var(--trek-native-corner-left, 0px));
|
||||
--m-safe-r: max(var(--m-raw-r), var(--trek-native-corner-right, 0px));
|
||||
}
|
||||
html[dir='rtl']:has(.m-shell[data-size='wide'], .m-shell[data-size='split']) .m-root {
|
||||
--m-rail-w: calc(var(--m-bar-r) + 100px);
|
||||
--m-corner-side-l: var(--m-corner-l-gap);
|
||||
--m-corner-side-r: 0px;
|
||||
--m-rail-w: calc(var(--m-safe-r) + 100px);
|
||||
}
|
||||
|
||||
.dark .m-root {
|
||||
@@ -649,40 +626,43 @@ html[dir='rtl']:has(.m-shell[data-size='wide'], .m-shell[data-size='split']) .m-
|
||||
html[dir='rtl']:has(.m-shell[data-size='wide'], .m-shell[data-size='split']) .m-span-x {
|
||||
inset-inline-end: var(--m-safe-l-gap, 0px);
|
||||
}
|
||||
/* A control row or button a screen places by itself (m-safe-row: the trip's
|
||||
top row, the map's controls, a viewer's close button, a dropdown) keeps
|
||||
clear of the sides' safe area like the bars above: both sides on a phone,
|
||||
the trailing side on a wide window, where the rail holds the leading one.
|
||||
A layer that fills the window (m-safe-trail: a sheet, the assistant, the
|
||||
trip's pane and map) does the same on a wide window only; on a phone its
|
||||
own insets keep it off the sides. On an unfolded Duo that trailing side is
|
||||
the status capsule's. */
|
||||
html:not(:has(.m-shell[data-size='wide'], .m-shell[data-size='split'])) .m-safe-row {
|
||||
margin-inline: var(--m-safe-l-gap, 0px) var(--m-safe-r-gap, 0px);
|
||||
}
|
||||
html[dir='rtl']:not(:has(.m-shell[data-size='wide'], .m-shell[data-size='split'])) .m-safe-row {
|
||||
margin-inline: var(--m-safe-r-gap, 0px) var(--m-safe-l-gap, 0px);
|
||||
}
|
||||
html:has(.m-shell[data-size='wide'], .m-shell[data-size='split']) :is(.m-safe-row, .m-safe-trail) {
|
||||
margin-inline-end: var(--m-safe-r-gap, 0px);
|
||||
}
|
||||
html[dir='rtl']:has(.m-shell[data-size='wide'], .m-shell[data-size='split']) :is(.m-safe-row, .m-safe-trail) {
|
||||
margin-inline-end: var(--m-safe-l-gap, 0px);
|
||||
}
|
||||
/* The page itself keeps clear of the sides' safe area, as iOS asks of every
|
||||
app, and starts below an element in a top corner: on a Duo the status
|
||||
capsule ran over the cards under the top bar (TestFlight feedback). The
|
||||
padding lifts the content only by what the capsule reaches below the top
|
||||
bar's row (about 70px under the top clearance), so with no corner element
|
||||
it is 0. Margins, so the rail's wide:ps on the same element stays; fixed
|
||||
layers are the window's and keep their own rules. The rail already takes
|
||||
the leading inset on a wide window. */
|
||||
app. Margins, so the rail's wide:ps on the same element stays; fixed layers
|
||||
are the window's and keep their own rules. On a wide window the rail takes
|
||||
the leading inset, so the page starts at the rail and ends before the
|
||||
trailing inset. */
|
||||
.m-page {
|
||||
margin-inline: var(--m-page-l, 0px) var(--m-page-r, 0px);
|
||||
padding-top: max(0px, calc(var(--m-corner-clear, 0px) + 2px - var(--m-safe-top, 12px) - 70px));
|
||||
margin-inline: var(--m-safe-l, 0px) var(--m-safe-r, 0px);
|
||||
}
|
||||
html[dir='rtl'] .m-page {
|
||||
margin-inline: var(--m-page-r, 0px) var(--m-page-l, 0px);
|
||||
margin-inline: var(--m-safe-r, 0px) var(--m-safe-l, 0px);
|
||||
}
|
||||
/* The lift above counts on a floating top bar over the page. A screen whose
|
||||
first row is part of the page (m-corner-flow: settings, administration,
|
||||
collections) is lifted until that row starts below the corner element; one
|
||||
that keeps clear of it by itself (m-corner-own: a map under its own bars, a
|
||||
calendar under its own header) is not lifted at all. */
|
||||
.m-page:has(.m-corner-flow) {
|
||||
padding-top: max(0px, calc(var(--m-corner-clear, 0px) - var(--m-safe-top, 12px)));
|
||||
}
|
||||
.m-page:has(.m-corner-own) {
|
||||
padding-top: 0;
|
||||
}
|
||||
/* On a wide window the page starts at the top and ends before the corner
|
||||
element instead (--m-corner-side-*, 0 without one). */
|
||||
html:has(.m-shell[data-size='wide'], .m-shell[data-size='split']) .m-page {
|
||||
margin-inline-start: 0;
|
||||
margin-inline-end: max(var(--m-page-r, 0px), var(--m-corner-side-r, 0px));
|
||||
margin-inline-end: var(--m-safe-r-gap, 0px);
|
||||
}
|
||||
html[dir='rtl']:has(.m-shell[data-size='wide'], .m-shell[data-size='split']) .m-page {
|
||||
margin-inline-end: max(var(--m-page-l, 0px), var(--m-corner-side-l, 0px));
|
||||
margin-inline-end: var(--m-safe-l-gap, 0px);
|
||||
}
|
||||
/* A screen whose background is a map reaches under the rail: the map runs to
|
||||
the window's edge and the rail floats over it like the top controls do. Its
|
||||
@@ -786,7 +766,7 @@ html:has(.m-shell) [data-desktop-navbar] {
|
||||
html:has(.m-shell) [data-plugin-page] {
|
||||
--plugin-page-h: calc(100dvh - var(--bottom-nav-h, 0px));
|
||||
box-sizing: border-box;
|
||||
padding-top: env(safe-area-inset-top, 0px);
|
||||
padding-top: var(--m-safe-t, env(safe-area-inset-top, 0px));
|
||||
padding-inline-start: var(--m-rail-w, 0px);
|
||||
}
|
||||
html:has(.m-shell) .leaflet-control-zoom {
|
||||
|
||||
@@ -122,7 +122,7 @@ export default function MAtlas() {
|
||||
return (
|
||||
// h-dvh, not h-full: the shell stopped providing a definite height (#1809)
|
||||
// and a map on a percentage of an auto-height parent collapses to zero.
|
||||
<div ref={rootRef} className="m-bleed m-corner-own relative h-dvh overflow-hidden">
|
||||
<div ref={rootRef} className="m-bleed relative h-dvh overflow-hidden">
|
||||
<div ref={mapRef} className="absolute inset-0 z-[1] bg-[color:var(--m-mapb)] [&_.leaflet-control-zoom]:hidden" />
|
||||
{/* Region hover tooltip — positioned imperatively by useAtlas. */}
|
||||
<div
|
||||
|
||||
@@ -50,7 +50,7 @@ export default function MAtlasSearch({
|
||||
const q = query.trim().toLowerCase()
|
||||
const rows = q ? options.filter((o) => o.label.toLowerCase().includes(q)).slice(0, 6) : suggestions
|
||||
|
||||
const scrimCls = 'm-fade-in fixed inset-0 z-[70] flex flex-col bg-[rgba(16,16,19,.28)] px-[18px] pt-[max(calc(var(--m-safe-top,12px)+12px),var(--m-corner-clear,0px))] backdrop-blur-[22px] backdrop-saturate-[1.6] wide:pt-[calc(var(--m-safe-top,12px)+72px)] wide:[&>*]:mx-auto wide:[&>*]:w-full wide:[&>*]:max-w-[640px]' // theme-lint-disable — fixed scrim value from the design
|
||||
const scrimCls = 'm-fade-in fixed inset-0 z-[70] flex flex-col bg-[rgba(16,16,19,.28)] px-[18px] pt-[calc(var(--m-safe-top,12px)+12px)] backdrop-blur-[22px] backdrop-saturate-[1.6] wide:pt-[calc(var(--m-safe-top,12px)+72px)] wide:[&>*]:mx-auto wide:[&>*]:w-full wide:[&>*]:max-w-[640px]' // theme-lint-disable — fixed scrim value from the design
|
||||
|
||||
return (
|
||||
<div
|
||||
|
||||
@@ -220,7 +220,7 @@ export default function MCollections() {
|
||||
// Map view fills the viewport like the trip and journal maps do (#2104);
|
||||
// h-dvh because the shell owns no scroll container (#1809). List view
|
||||
// keeps the document as the scroller.
|
||||
className={`m-corner-flow px-4 pb-[calc(var(--bottom-nav-h,84px)+12px)] pt-[var(--m-safe-top,12px)] wide:px-6 split:grid split:grid-cols-[260px_minmax(0,1fr)] split:gap-8 ${c.view === 'map' ? 'flex h-dvh flex-col overflow-hidden' : 'wide:mx-auto wide:max-w-[1040px] split:max-w-[1240px] split:items-start'}`}
|
||||
className={`px-4 pb-[calc(var(--bottom-nav-h,84px)+12px)] pt-[var(--m-safe-top,12px)] wide:px-6 split:grid split:grid-cols-[260px_minmax(0,1fr)] split:gap-8 ${c.view === 'map' ? 'flex h-dvh flex-col overflow-hidden' : 'wide:mx-auto wide:max-w-[1040px] split:max-w-[1240px] split:items-start'}`}
|
||||
>
|
||||
{split && (
|
||||
<nav
|
||||
|
||||
@@ -66,7 +66,7 @@ export default function MUserMenu({ open, onClose }: MUserMenuProps): React.Reac
|
||||
}
|
||||
|
||||
return (
|
||||
<MDropdownPanel open={open} onClose={onClose} className="m-corner-beside end-4 top-[calc(var(--m-safe-top,12px)+68px)]">
|
||||
<MDropdownPanel open={open} onClose={onClose} className="m-safe-row end-4 top-[calc(var(--m-safe-top,12px)+68px)]">
|
||||
<div className="flex items-center gap-[10px] p-[10px_10px_12px]">
|
||||
<span className="flex h-10 w-10 flex-none items-center justify-center overflow-hidden rounded-full bg-[image:linear-gradient(135deg,#6A6A74,#1A1A1E)] text-[0.9375rem] font-bold text-white">
|
||||
{user?.avatar_url
|
||||
|
||||
@@ -346,7 +346,7 @@ export default function MJourneyDetail({ journeyId, embedded = false }: JourneyD
|
||||
return (
|
||||
// h-dvh, not h-full: the shell stopped providing a definite height (#1809)
|
||||
// and a map on a percentage of an auto-height parent collapses to zero.
|
||||
<div ref={rootRef} className="m-bleed m-corner-own relative h-dvh overflow-hidden" style={headSlot ? IN_SHELL_ROW : undefined}>
|
||||
<div ref={rootRef} className="m-bleed relative h-dvh overflow-hidden" style={headSlot ? IN_SHELL_ROW : undefined}>
|
||||
{/* Integrated map — always mounted, the gallery overlays it. Beside the feed
|
||||
it begins where the feed ends, so its controls and its framing stay in
|
||||
the part that can be seen. */}
|
||||
@@ -358,7 +358,7 @@ export default function MJourneyDetail({ journeyId, embedded = false }: JourneyD
|
||||
ref={mapRef}
|
||||
layers={mapLayers}
|
||||
hideLayerControl
|
||||
controlsTop="max(calc(var(--m-safe-top, 12px) + 50px), var(--m-corner-clear, 0px))"
|
||||
controlsTop="calc(var(--m-safe-top, 12px) + 50px)"
|
||||
// Its satellite switch sits in the bar above, beside the menu.
|
||||
baseLayer={mapBase}
|
||||
onOpenEntry={handleMarkerClick}
|
||||
@@ -382,7 +382,7 @@ export default function MJourneyDetail({ journeyId, embedded = false }: JourneyD
|
||||
|
||||
{/* Gallery tab overlay */}
|
||||
{view === 'gallery' && (
|
||||
<div className="m-span-x absolute inset-y-0 z-[5] overflow-y-auto bg-[color:var(--m-bg)] bg-[image:var(--m-scr)] px-4 pt-[max(calc(var(--m-safe-top,12px)+56px),var(--m-corner-clear,0px))] pb-[calc(var(--bottom-nav-h,84px)+16px)] wide:px-6">
|
||||
<div className="m-span-x absolute inset-y-0 z-[5] overflow-y-auto bg-[color:var(--m-bg)] bg-[image:var(--m-scr)] px-4 pt-[calc(var(--m-safe-top,12px)+56px)] pb-[calc(var(--bottom-nav-h,84px)+16px)] wide:px-6">
|
||||
{gallery.length === 0 ? (
|
||||
<div className="flex min-h-full flex-col items-center justify-center px-8 py-10 text-center">
|
||||
<MDancingTrek scene="journey" className="mb-2" />
|
||||
@@ -849,7 +849,7 @@ export default function MJourneyDetail({ journeyId, embedded = false }: JourneyD
|
||||
* With the header in the shell's row, what the screen measures from its top
|
||||
* starts right under that row instead of under a row of its own.
|
||||
*/
|
||||
const IN_SHELL_ROW = { '--m-safe-top': 'calc(env(safe-area-inset-top, 0px) + 6px)' } as CSSProperties
|
||||
const IN_SHELL_ROW = { '--m-safe-top': 'calc(var(--m-safe-t, env(safe-area-inset-top, 0px)) + 6px)' } as CSSProperties
|
||||
|
||||
/** The header row: on the screen, or in the trip shell's top row when the journal is a trip tab. */
|
||||
function HeaderFrame({ slot, feed, children }: { slot: HTMLElement | null; feed: boolean; children: ReactNode }) {
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { useEffect, useLayoutEffect, useRef, useState, type ComponentType } from 'react'
|
||||
import { useEffect, useLayoutEffect, useRef, useState, type ComponentType, type ReactNode } from 'react'
|
||||
import { findFocusDayId, findTodayDayId } from '../../../components/Planner/today'
|
||||
import { takeResumeDay } from '../../../utils/resumeRoute'
|
||||
import {
|
||||
@@ -573,6 +573,13 @@ export default function MTripShell({
|
||||
// one is open, otherwise the page column after the rail.
|
||||
const chromeSpan = paneOpen ? 'split:end-auto split:w-[calc(var(--trip-pane)-32px)]' : ''
|
||||
const paneBox = 'absolute inset-y-0 start-0 end-0 wide:start-[var(--m-rail-w)] split:end-auto split:w-[var(--trip-pane)]'
|
||||
// A pane over the map. Its content keeps off the trailing side's safe area where the pane
|
||||
// reaches that side (a wide window; beside the map in split it ends long before).
|
||||
const pane = (layer: string, content: ReactNode) => (
|
||||
<div className={`${paneBox} ${layer} bg-[color:var(--m-bg)] bg-[image:var(--m-scr)] split:border-e split:border-[color:var(--m-rowbr)]`}>
|
||||
<div className={split ? 'relative h-full' : 'm-safe-trail relative h-full'}>{content}</div>
|
||||
</div>
|
||||
)
|
||||
// Where the map begins. Beside an open pane, after it; while the map is the
|
||||
// whole screen it runs under the floating rail to the window's edge, with its
|
||||
// controls kept clear of the rail (--trip-map-inset); behind a full-width
|
||||
@@ -604,26 +611,14 @@ export default function MTripShell({
|
||||
<div className="absolute inset-y-0 end-0 start-[var(--trip-map-start)] transition-[inset-inline-start] duration-300 ease-out motion-reduce:transition-none">
|
||||
<MapArea planner={planner} shell={shell} />
|
||||
</div>
|
||||
{trTab === 'plan' && view === 'plan' && mode !== 'browse' && (
|
||||
<div className={`${paneBox} z-10 bg-[color:var(--m-bg)] bg-[image:var(--m-scr)] split:border-e split:border-[color:var(--m-rowbr)]`}>
|
||||
<PlanTimeline planner={planner} shell={shell} />
|
||||
</div>
|
||||
)}
|
||||
{trTab === 'plan' && mode === 'browse' && (
|
||||
<div className={`${paneBox} z-30 bg-[color:var(--m-bg)] bg-[image:var(--m-scr)] split:border-e split:border-[color:var(--m-rowbr)]`}>
|
||||
<PlacesBrowser planner={planner} shell={shell} />
|
||||
</div>
|
||||
)}
|
||||
{trTab === 'plan' && view === 'plan' && mode !== 'browse' && pane('z-10', <PlanTimeline planner={planner} shell={shell} />)}
|
||||
{trTab === 'plan' && mode === 'browse' && pane('z-30', <PlacesBrowser planner={planner} shell={shell} />)}
|
||||
{/*
|
||||
The stage lives at z-20, below the day chips at z-25, which is the whole
|
||||
of the stage picker: the chips belong to the shell and were only ever
|
||||
hidden because non-plan panels cover them at z-30.
|
||||
*/}
|
||||
{trTab === 'roadtrip' && rtView === 'list' && (
|
||||
<div className={`${paneBox} z-20 bg-[color:var(--m-bg)] bg-[image:var(--m-scr)] split:border-e split:border-[color:var(--m-rowbr)]`}>
|
||||
<TabPanel planner={planner} shell={shell} tab={trTab} />
|
||||
</div>
|
||||
)}
|
||||
{trTab === 'roadtrip' && rtView === 'list' && pane('z-20', <TabPanel planner={planner} shell={shell} tab={trTab} />)}
|
||||
{trTab === 'roadtrip' && rtView === 'map' && (
|
||||
// The stage's bars keep to the page column while the map runs under the rail.
|
||||
<div className="pointer-events-none absolute inset-0 wide:start-[var(--m-rail-w)]">
|
||||
@@ -634,7 +629,7 @@ export default function MTripShell({
|
||||
)}
|
||||
{!MAP_TABS.has(trTab) && (
|
||||
<div className="absolute inset-0 z-30 bg-[color:var(--m-bg)] bg-[image:var(--m-scr)] wide:start-[var(--m-rail-w)]">
|
||||
<div className="m-corner-side relative h-full">
|
||||
<div className="m-safe-trail relative h-full">
|
||||
<TabPanel planner={planner} shell={shell} tab={trTab} />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -68,7 +68,7 @@ export function GlassSegment({ children, activeKey }: { children: ReactNode; act
|
||||
* The box of the trip's floating rows (the top controls, the day chips): the page's width after
|
||||
* the rail, beside an element in a top corner such as a Duo's status capsule (mobile.css).
|
||||
*/
|
||||
export const CHROME_ROW = 'm-corner-beside absolute end-4 start-[calc(var(--m-rail-w,0px)+16px)]';
|
||||
export const CHROME_ROW = 'm-safe-row absolute end-4 start-[calc(var(--m-rail-w,0px)+16px)]';
|
||||
|
||||
/** A phone's header group: after the back button (transports, bookings), or centred on the bar (costs, files). */
|
||||
export const ROW_AFTER_BACK = 'absolute start-[52px] end-2 justify-center';
|
||||
|
||||
@@ -216,10 +216,10 @@ export function AssistantScreen({ tripId, tripTitle, hidden, hops, onOpenTripCha
|
||||
hidden={hidden}
|
||||
tabIndex={-1}
|
||||
onKeyDown={(e) => keepTabInside(e, sectionRef.current)}
|
||||
className={`m-corner-side fixed inset-0 z-[var(--z-bar)] ${hidden ? 'hidden' : 'flex'} m-panel-in flex-col bg-[var(--m-bg)] bg-[image:var(--m-scr)] text-m-ink outline-none wide:inset-auto wide:bottom-3 wide:end-3 wide:top-3 wide:w-[min(500px,calc(100vw-var(--m-rail-w,0px)-24px))] wide:overflow-hidden wide:rounded-[28px] wide:border wide:border-[color:var(--m-shbr)] wide:shadow-modal`}
|
||||
className={`m-safe-trail fixed inset-0 z-[var(--z-bar)] ${hidden ? 'hidden' : 'flex'} m-panel-in flex-col bg-[var(--m-bg)] bg-[image:var(--m-scr)] text-m-ink outline-none wide:inset-auto wide:bottom-3 wide:end-3 wide:top-3 wide:w-[min(500px,calc(100vw-var(--m-rail-w,0px)-24px))] wide:overflow-hidden wide:rounded-[28px] wide:border wide:border-[color:var(--m-shbr)] wide:shadow-modal`}
|
||||
style={{ paddingBottom: `max(env(safe-area-inset-bottom, 0px), ${keyboard}px)` }}
|
||||
>
|
||||
<header className="m-corner-beside-in flex flex-none items-center gap-2 px-4 pb-2 pt-[var(--m-safe-top,12px)] wide:pt-3">
|
||||
<header className="flex flex-none items-center gap-2 px-4 pb-2 pt-[var(--m-safe-top,12px)] wide:pt-3">
|
||||
<MIconBtn ariaLabel={t('common.back')} onClick={close}>
|
||||
<ChevronLeft size={19} strokeWidth={2.2} />
|
||||
</MIconBtn>
|
||||
@@ -256,7 +256,7 @@ export function AssistantScreen({ tripId, tripTitle, hidden, hops, onOpenTripCha
|
||||
<MDropdownPanel
|
||||
open={panel === 'history'}
|
||||
onClose={() => setPanel(null)}
|
||||
className="m-corner-beside-in end-4 top-[calc(var(--m-safe-top,12px)+48px)] max-h-[60vh] overflow-y-auto"
|
||||
className="end-4 top-[calc(var(--m-safe-top,12px)+48px)] max-h-[60vh] overflow-y-auto"
|
||||
>
|
||||
<MListRow icon={Plus} label={t('assistant.history.new')} onClick={() => pick(thread.newThread)} />
|
||||
{threads.length === 0 ? (
|
||||
@@ -285,7 +285,7 @@ export function AssistantScreen({ tripId, tripTitle, hidden, hops, onOpenTripCha
|
||||
<MDropdownPanel
|
||||
open={panel === 'menu'}
|
||||
onClose={() => setPanel(null)}
|
||||
className="m-corner-beside-in end-4 top-[calc(var(--m-safe-top,12px)+48px)]"
|
||||
className="end-4 top-[calc(var(--m-safe-top,12px)+48px)]"
|
||||
>
|
||||
{tripChat && (
|
||||
<MListRow
|
||||
|
||||
@@ -473,7 +473,7 @@ export default function MMapArea({ planner, shell }: MMapAreaProps) {
|
||||
<div
|
||||
// Beside the trip's pane nothing lies over the map, so the bar takes the
|
||||
// top edge, level with the pane's own top row.
|
||||
className={`m-corner-beside pointer-events-none absolute end-4 start-[calc(var(--trip-map-inset,0px)+16px)] z-[25] flex flex-col items-center gap-2 ${
|
||||
className={`m-safe-row pointer-events-none absolute end-4 start-[calc(var(--trip-map-inset,0px)+16px)] z-[25] flex flex-col items-center gap-2 ${
|
||||
shell.paneOpen ? 'top-[var(--m-safe-top,12px)]' : 'top-[calc(var(--m-safe-top,12px)+96px)]'
|
||||
}`}
|
||||
>
|
||||
|
||||
@@ -118,7 +118,7 @@ export default function MPlacesBrowser({ planner, shell }: MPlacesBrowserProps)
|
||||
|
||||
return (
|
||||
<div className="flex h-full flex-col">
|
||||
<div className="min-h-0 flex-1 overflow-x-hidden overflow-y-auto px-4 pb-[calc(var(--bottom-nav-h,84px)+22px)] pt-[max(calc(var(--m-safe-top,12px)+58px),var(--m-corner-clear,0px))]">
|
||||
<div className="min-h-0 flex-1 overflow-x-hidden overflow-y-auto px-4 pb-[calc(var(--bottom-nav-h,84px)+22px)] pt-[calc(var(--m-safe-top,12px)+58px)]">
|
||||
{/* ── Places/Tours, the filter chips and Import (Add sits in the search row
|
||||
below to free space). The switch has a row of its own, except where the
|
||||
screen is short (a phone on its side): there it shares the chips' row,
|
||||
|
||||
@@ -212,7 +212,7 @@ function PlanDayPage({ planner, shell, dayId: pageDayId, active, editing, legMen
|
||||
Beside the map the card is the pane and runs down to that line, as the
|
||||
places list does; across the page it is as tall as its day, so a short
|
||||
day leaves no empty card under it. */}
|
||||
<div className="absolute inset-x-4 flex flex-col gap-3 top-[max(calc(var(--m-safe-top,12px)+102px),var(--m-corner-clear,0px))] bottom-[calc(env(safe-area-inset-bottom,0px)+90px)] wide:bottom-[calc(env(safe-area-inset-bottom,0px)+12px)]">
|
||||
<div className="absolute inset-x-4 flex flex-col gap-3 top-[calc(var(--m-safe-top,12px)+102px)] bottom-[calc(env(safe-area-inset-bottom,0px)+90px)] wide:bottom-[calc(env(safe-area-inset-bottom,0px)+12px)]">
|
||||
{!editing && <UpNextCard tl={tl} t={t} onOpen={openPlace} />}
|
||||
{editing && <EditHeader tl={tl} planner={planner} shell={shell} />}
|
||||
|
||||
|
||||
@@ -64,7 +64,7 @@ export default function MRoadtripTab({ planner, shell }: MTripTabPanelProps) {
|
||||
// fall back to the trip's first routed day, which is not the one on screen, and every
|
||||
// distance it answered with would be measured against a road nobody is looking at.
|
||||
const searchBar = stage && (
|
||||
<div className="m-corner-beside pointer-events-auto absolute inset-x-4 top-[calc(var(--m-safe-top,12px)+96px)] z-[26]">
|
||||
<div className="m-safe-row pointer-events-auto absolute inset-x-4 top-[calc(var(--m-safe-top,12px)+96px)] z-[26]">
|
||||
<MRtCorridorBar planner={planner} corridor={corridor} onOpen={() => shell.openSheet('rtsearch')} />
|
||||
</div>
|
||||
)
|
||||
@@ -197,7 +197,7 @@ function RoadtripStagePage({ planner, shell, dayId: pageDayId, alts, chrome }: O
|
||||
return (
|
||||
<div
|
||||
className={`absolute inset-0 overflow-x-hidden overflow-y-auto overscroll-y-contain px-4 pb-[calc(var(--bottom-nav-h,84px)+22px)] ${
|
||||
stage ? 'pt-[max(calc(var(--m-safe-top,12px)+150px),var(--m-corner-clear,0px))]' : 'pt-[max(calc(var(--m-safe-top,12px)+102px),var(--m-corner-clear,0px))]'
|
||||
stage ? 'pt-[calc(var(--m-safe-top,12px)+150px)]' : 'pt-[calc(var(--m-safe-top,12px)+102px)]'
|
||||
}`}
|
||||
>
|
||||
<UndatedRides rides={undated} t={t} onOpen={openBooking} />
|
||||
|
||||
@@ -91,7 +91,7 @@ export default function MCollabChat({ planner }: MCollabChatProps) {
|
||||
|
||||
return (
|
||||
<div
|
||||
className="flex h-full flex-col px-4 pb-[var(--bottom-nav-h,84px)] pt-[max(calc(var(--m-safe-top,12px)+58px),var(--m-corner-clear,0px))] wide:mx-auto wide:w-full wide:max-w-[808px] wide:px-6 wide:pb-[calc(var(--bottom-nav-h,0px)+12px)]"
|
||||
className="flex h-full flex-col px-4 pb-[var(--bottom-nav-h,84px)] pt-[calc(var(--m-safe-top,12px)+58px)] wide:mx-auto wide:w-full wide:max-w-[808px] wide:px-6 wide:pb-[calc(var(--bottom-nav-h,0px)+12px)]"
|
||||
style={keyboard > 0 ? { paddingBottom: keyboard + 8 } : undefined}
|
||||
>
|
||||
{loading ? (
|
||||
|
||||
@@ -74,7 +74,7 @@ function CollabPanel({ planner, tab }: { planner: MTabScreenProps['planner']; ta
|
||||
if (tab === 'chat') {
|
||||
if (!planner.collabFeatures.chat) {
|
||||
return (
|
||||
<div className="flex h-full flex-col px-4 pb-[var(--bottom-nav-h,84px)] pt-[max(calc(var(--m-safe-top,12px)+58px),var(--m-corner-clear,0px))]">
|
||||
<div className="flex h-full flex-col px-4 pb-[var(--bottom-nav-h,84px)] pt-[calc(var(--m-safe-top,12px)+58px)]">
|
||||
<CollabDisabledNotice icon={MessageCircle} label={label} />
|
||||
</div>
|
||||
)
|
||||
|
||||
@@ -265,12 +265,12 @@ export default function MFilesTab({ planner, shell }: MTabScreenProps) {
|
||||
if (split && picked) {
|
||||
return (
|
||||
<div className="flex h-full">
|
||||
<div className="min-h-0 min-w-0 flex-1 overflow-y-auto overflow-x-hidden pb-[calc(var(--bottom-nav-h,84px)+22px)] pe-3 ps-6 pt-[max(calc(var(--m-safe-top,12px)+58px),var(--m-corner-clear,0px))]">
|
||||
<div className="min-h-0 min-w-0 flex-1 overflow-y-auto overflow-x-hidden pb-[calc(var(--bottom-nav-h,84px)+22px)] pe-3 ps-6 pt-[calc(var(--m-safe-top,12px)+58px)]">
|
||||
{body}
|
||||
</div>
|
||||
<aside
|
||||
aria-label={t('common.preview')}
|
||||
className="m-pane-trail min-h-0 flex-none overflow-y-auto overflow-x-hidden border-s border-[color:var(--m-rowbr)] px-5 pb-[calc(var(--bottom-nav-h,84px)+22px)] pt-[max(calc(var(--m-safe-top,12px)+58px),var(--m-corner-clear,0px))]"
|
||||
className="m-pane-trail min-h-0 flex-none overflow-y-auto overflow-x-hidden border-s border-[color:var(--m-rowbr)] px-5 pb-[calc(var(--bottom-nav-h,84px)+22px)] pt-[calc(var(--m-safe-top,12px)+58px)]"
|
||||
>
|
||||
<FilePreviewPane
|
||||
file={picked}
|
||||
|
||||
@@ -37,7 +37,7 @@ export default function MTripTabPanel({ planner, shell, tab }: MTripTabPanelProp
|
||||
if (tab.startsWith('plugin:')) {
|
||||
return (
|
||||
<div
|
||||
className="absolute inset-0 pt-[max(calc(var(--m-safe-top,12px)+58px),var(--m-corner-clear,0px))] pb-[calc(var(--bottom-nav-h,84px)+22px)]"
|
||||
className="absolute inset-0 pt-[calc(var(--m-safe-top,12px)+58px)] pb-[calc(var(--bottom-nav-h,84px)+22px)]"
|
||||
>
|
||||
<PluginFrame
|
||||
pluginId={tab.slice('plugin:'.length)}
|
||||
@@ -78,7 +78,7 @@ export default function MTripTabPanel({ planner, shell, tab }: MTripTabPanelProp
|
||||
// below the trip's floating top controls: its bars measure from --m-safe-top.
|
||||
case 'journal':
|
||||
return planner.journalId == null ? null : (
|
||||
<div className="absolute inset-0 overflow-hidden [--m-safe-top:calc(env(safe-area-inset-top,0px)+62px)]">
|
||||
<div className="absolute inset-0 overflow-hidden [--m-safe-top:calc(var(--m-safe-t,env(safe-area-inset-top,0px))+62px)]">
|
||||
<MJourneyDetail journeyId={planner.journalId} embedded />
|
||||
</div>
|
||||
)
|
||||
|
||||
@@ -33,8 +33,8 @@ export function TabScroller({ children, wide = 'readable' }: { children: ReactNo
|
||||
}
|
||||
|
||||
/** The room a tab's scroll body keeps clear: the floating top controls above, the dock (or the home indicator) below. */
|
||||
const TAB_INSETS = 'px-4 pb-[calc(var(--bottom-nav-h,84px)+22px)] pt-[max(calc(var(--m-safe-top,12px)+58px),var(--m-corner-clear,0px))] wide:px-6'
|
||||
const PANE_INSETS = 'pb-[calc(var(--bottom-nav-h,84px)+22px)] pt-[max(calc(var(--m-safe-top,12px)+58px),var(--m-corner-clear,0px))]'
|
||||
const TAB_INSETS = 'px-4 pb-[calc(var(--bottom-nav-h,84px)+22px)] pt-[calc(var(--m-safe-top,12px)+58px)] wide:px-6'
|
||||
const PANE_INSETS = 'pb-[calc(var(--bottom-nav-h,84px)+22px)] pt-[calc(var(--m-safe-top,12px)+58px)]'
|
||||
|
||||
/**
|
||||
* The cards of a list tab (transports, bookings, tasks, polls): one column on a
|
||||
|
||||
@@ -91,9 +91,9 @@ export default function MVacay() {
|
||||
|
||||
return (
|
||||
// h-dvh, not h-full: the shell stopped providing a definite height (#1809).
|
||||
<div className="m-corner-own relative h-dvh">
|
||||
<div className="relative h-dvh">
|
||||
{/* Header, beside a corner element (a Duo's status capsule) upright */}
|
||||
<div className="m-corner-beside-in absolute inset-x-4 z-[5] flex items-center gap-2 top-[var(--m-safe-top,12px)]">
|
||||
<div className="absolute inset-x-4 z-[5] flex items-center gap-2 top-[var(--m-safe-top,12px)]">
|
||||
<MIconBtn onClick={() => v.setSheet('invite')} ariaLabel={t('vacay.inviteUser')}>
|
||||
<UserPlus size={16} strokeWidth={2} className="text-m-muted" />
|
||||
</MIconBtn>
|
||||
@@ -115,7 +115,7 @@ export default function MVacay() {
|
||||
</div>
|
||||
|
||||
{/* Scroll container */}
|
||||
<div className={`absolute inset-0 overflow-y-auto px-4 pt-[max(calc(var(--m-safe-top,12px)+44px),var(--m-corner-clear,0px))] pb-[calc(var(--bottom-nav-h,84px)+12px)] ${edit ? 'wide:pb-[calc(env(safe-area-inset-bottom,0px)+84px)]' : ''}`}>
|
||||
<div className={`absolute inset-0 overflow-y-auto px-4 pt-[calc(var(--m-safe-top,12px)+44px)] pb-[calc(var(--bottom-nav-h,84px)+12px)] ${edit ? 'wide:pb-[calc(env(safe-area-inset-bottom,0px)+84px)]' : ''}`}>
|
||||
{/* Selected person card */}
|
||||
{v.selectedUser && stat && (
|
||||
<div className="mt-2 flex items-center gap-3 rounded-[18px] border border-[color:var(--m-gbr)] bg-[color:var(--m-glass)] px-[14px] py-[9px]">
|
||||
|
||||
@@ -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:
|
||||
|
||||
@@ -507,7 +507,7 @@ describe('MSheet', () => {
|
||||
<span>body</span>
|
||||
</MSheet>,
|
||||
);
|
||||
expect(region().className).toContain('top-[max(var(--m-safe-top,12px),var(--m-corner-clear,0px))]');
|
||||
expect(region().className).toContain('top-[var(--m-safe-top,12px)]');
|
||||
expect(region().className).toContain('bottom-[calc(var(--bottom-nav-h,84px)+12px)]');
|
||||
expect(panel().className).toContain('max-h-full');
|
||||
});
|
||||
|
||||
@@ -52,12 +52,15 @@ describe('MGlassBar', () => {
|
||||
describe('safe area in the touch shell', () => {
|
||||
// jsdom applies no stylesheet and has no env(), so the rules are read from source.
|
||||
const css = readFileSync(resolve(root, 'src/mobile/mobile.css'), 'utf8');
|
||||
const wideRoot = "html:has(.m-shell[data-size='wide'], .m-shell[data-size='split']) .m-root {";
|
||||
const rtlWideRoot = "html[dir='rtl']:has(.m-shell[data-size='wide'], .m-shell[data-size='split']) .m-root {";
|
||||
const block = (selector: string) => css.split(selector)[1]?.split('}')[0] ?? '';
|
||||
|
||||
it('FE-MOB-CHROME-004: the top clearance takes env() with the measurement of the app as a floor, never in its place', () => {
|
||||
expect(css).toContain('--m-safe-t: max(env(safe-area-inset-top, 0px), var(--trek-native-safe-top, 0px));');
|
||||
it('FE-MOB-CHROME-004: the insets take env() with the measurement of the app as a floor, never in its place', () => {
|
||||
expect(css).toContain('--m-raw-t: max(env(safe-area-inset-top, 0px), var(--trek-native-safe-top, 0px));');
|
||||
expect(css).toContain('--m-raw-l: max(env(safe-area-inset-left, 0px), var(--trek-native-safe-left, 0px));');
|
||||
expect(css).toContain('--m-raw-r: max(env(safe-area-inset-right, 0px), var(--trek-native-safe-right, 0px));');
|
||||
expect(css).toContain('--m-safe-top: calc(var(--m-safe-t) + 12px);');
|
||||
expect(css).toContain('--m-safe-l: max(env(safe-area-inset-left, 0px), var(--trek-native-safe-left, 0px));');
|
||||
expect(css).toContain('--m-safe-r: max(env(safe-area-inset-right, 0px), var(--trek-native-safe-right, 0px));');
|
||||
});
|
||||
|
||||
it('FE-MOB-CHROME-005: without the rail the floating bars keep clear of a side inset, such as a camera in a corner', () => {
|
||||
@@ -74,92 +77,66 @@ describe('safe area in the touch shell', () => {
|
||||
});
|
||||
|
||||
it('FE-MOB-CHROME-006: a side inset gets a little air, and none where there is no inset', () => {
|
||||
expect(css).toContain('--m-safe-r-gap: calc(var(--m-bar-r) + min(var(--m-bar-r), 8px));');
|
||||
expect(css).toContain('--m-safe-l-gap: calc(var(--m-bar-l) + min(var(--m-bar-l), 8px));');
|
||||
expect(css).toContain('--m-safe-r-gap: calc(var(--m-safe-r) + min(var(--m-safe-r), 8px));');
|
||||
expect(css).toContain('--m-safe-l-gap: calc(var(--m-safe-l) + min(var(--m-safe-l), 8px));');
|
||||
});
|
||||
|
||||
it('FE-MOB-CHROME-007: on a wide window the bars end before the trailing inset, by their box, not a margin', () => {
|
||||
const wide = "html:has(.m-shell[data-size='wide'], .m-shell[data-size='split']) .m-bar-x {";
|
||||
expect(css.split(wide)[1]?.split('}')[0] ?? '').toContain(
|
||||
'inset-inline-end: calc(16px + var(--m-safe-r-gap, 0px));'
|
||||
);
|
||||
expect(block(wide)).toContain('inset-inline-end: calc(16px + var(--m-safe-r-gap, 0px));');
|
||||
const rtl = `html[dir='rtl']:has(.m-shell[data-size='wide'], .m-shell[data-size='split']) .m-bar-x {`;
|
||||
expect(css.split(rtl)[1]?.split('}')[0] ?? '').toContain(
|
||||
'inset-inline-end: calc(16px + var(--m-safe-l-gap, 0px));'
|
||||
);
|
||||
expect(block(rtl)).toContain('inset-inline-end: calc(16px + var(--m-safe-l-gap, 0px));');
|
||||
});
|
||||
|
||||
it('FE-MOB-CHROME-008: the page keeps clear of the side insets, the leading one left to the rail on a wide window', () => {
|
||||
expect(css.split('\n.m-page {')[1]?.split('}')[0] ?? '').toContain(
|
||||
'margin-inline: var(--m-page-l, 0px) var(--m-page-r, 0px);'
|
||||
);
|
||||
expect(css.split("html[dir='rtl'] .m-page {")[1]?.split('}')[0] ?? '').toContain(
|
||||
'margin-inline: var(--m-page-r, 0px) var(--m-page-l, 0px);'
|
||||
);
|
||||
const wide = "html:has(.m-shell[data-size='wide'], .m-shell[data-size='split']) .m-page {";
|
||||
expect(css.split(wide)[1]?.split('}')[0] ?? '').toContain('margin-inline-start: 0;');
|
||||
expect(block('\n.m-page {')).toContain('margin-inline: var(--m-safe-l, 0px) var(--m-safe-r, 0px);');
|
||||
expect(block('\n.m-page {')).not.toContain('padding-top');
|
||||
expect(block("html[dir='rtl'] .m-page {")).toContain('margin-inline: var(--m-safe-r, 0px) var(--m-safe-l, 0px);');
|
||||
const wide = block("html:has(.m-shell[data-size='wide'], .m-shell[data-size='split']) .m-page {");
|
||||
expect(wide).toContain('margin-inline-start: 0;');
|
||||
expect(wide).toContain('margin-inline-end: var(--m-safe-r-gap, 0px);');
|
||||
const rtlWide = block("html[dir='rtl']:has(.m-shell[data-size='wide'], .m-shell[data-size='split']) .m-page {");
|
||||
expect(rtlWide).toContain('margin-inline-end: var(--m-safe-l-gap, 0px);');
|
||||
});
|
||||
|
||||
it('FE-MOB-CHROME-009: an element in a top corner moves the bars beside it and the page below it, not a whole strip aside', () => {
|
||||
// The bars avoid the wider of the side inset and the corner element.
|
||||
expect(css).toContain('--m-bar-r: max(var(--m-safe-r), var(--trek-native-corner-right, 0px));');
|
||||
expect(css).toContain('--m-bar-l: max(var(--m-safe-l), var(--trek-native-corner-left, 0px));');
|
||||
// The page gives the corner's width back and starts below the corner instead.
|
||||
expect(css).toContain('--m-page-r: max(0px, var(--m-safe-r) - var(--trek-native-corner-right, 0px));');
|
||||
expect(css).toContain('--m-page-l: max(0px, var(--m-safe-l) - var(--trek-native-corner-left, 0px));');
|
||||
expect(css.split('\n.m-page {')[1]?.split('}')[0] ?? '').toContain(
|
||||
'padding-top: max(0px, calc(var(--m-corner-clear, 0px) + 2px - var(--m-safe-top, 12px) - 70px));'
|
||||
);
|
||||
expect(css).toContain('--m-corner-clear: calc(var(--m-corner-b) + min(var(--m-corner-b), 10px));');
|
||||
// Without a corner element (every other device, iOS before 26) nothing moves.
|
||||
expect(css).toContain('--m-corner-b: var(--trek-native-corner-bottom, 0px);');
|
||||
it('FE-MOB-CHROME-009: upright, an element in a top corner counts as top inset, and the sides keep their width', () => {
|
||||
// A Duo's status capsule: everything that clears the top clears it too.
|
||||
expect(css).toContain('--m-safe-t: max(var(--m-raw-t), var(--trek-native-corner-bottom, 0px));');
|
||||
// iOS reports it as a side inset as well; upright that width is given back.
|
||||
expect(css).toContain('--m-safe-l: max(0px, var(--m-raw-l) - var(--trek-native-corner-left, 0px));');
|
||||
expect(css).toContain('--m-safe-r: max(0px, var(--m-raw-r) - var(--trek-native-corner-right, 0px));');
|
||||
});
|
||||
|
||||
it('FE-MOB-CHROME-010: on a wide window the page ends before a corner element instead of starting below it', () => {
|
||||
const wideRoot = "html:has(.m-shell[data-size='wide'], .m-shell[data-size='split']) .m-root {";
|
||||
const block = css.split(wideRoot)[1]?.split('}')[0] ?? '';
|
||||
expect(block).toContain('--m-corner-clear: 0px;');
|
||||
expect(block).toContain('--m-corner-side-r: var(--m-corner-r-gap);');
|
||||
expect(block).toContain('--m-rail-w: calc(var(--m-bar-l) + 100px);');
|
||||
const widePage = "html:has(.m-shell[data-size='wide'], .m-shell[data-size='split']) .m-page {";
|
||||
expect(css.split(widePage)[1]?.split('}')[0] ?? '').toContain(
|
||||
'margin-inline-end: max(var(--m-page-r, 0px), var(--m-corner-side-r, 0px));'
|
||||
);
|
||||
// Right to left the rail stands on the corner's side and takes it.
|
||||
const rtlRoot = "html[dir='rtl']:has(.m-shell[data-size='wide'], .m-shell[data-size='split']) .m-root {";
|
||||
const rtl = css.split(rtlRoot)[1]?.split('}')[0] ?? '';
|
||||
expect(rtl).toContain('--m-rail-w: calc(var(--m-bar-r) + 100px);');
|
||||
expect(rtl).toContain('--m-corner-side-r: 0px;');
|
||||
it('FE-MOB-CHROME-010: on a wide window the corner element takes its side over the whole height instead', () => {
|
||||
const wide = block(wideRoot);
|
||||
expect(wide).toContain('--m-safe-t: var(--m-raw-t);');
|
||||
expect(wide).toContain('--m-safe-l: max(var(--m-raw-l), var(--trek-native-corner-left, 0px));');
|
||||
expect(wide).toContain('--m-safe-r: max(var(--m-raw-r), var(--trek-native-corner-right, 0px));');
|
||||
expect(wide).toContain('--m-rail-w: calc(var(--m-safe-l) + 100px);');
|
||||
// Right to left the rail stands on the other side and takes that inset.
|
||||
expect(block(rtlWideRoot)).toContain('--m-rail-w: calc(var(--m-safe-r) + 100px);');
|
||||
});
|
||||
|
||||
it('FE-MOB-CHROME-011: the screens that place their own controls keep them beside a corner element and their content below it', () => {
|
||||
const corner = readFileSync(resolve(root, 'src/mobile/corner.css'), 'utf8');
|
||||
expect(corner).toMatch(
|
||||
/\.m-corner-beside \{\s*margin-inline: var\(--m-corner-l-gap, 0px\) var\(--m-corner-r-gap, 0px\);/
|
||||
);
|
||||
// The element stays where the hardware has it, so right to left swaps the sides back.
|
||||
expect(corner).toMatch(
|
||||
/html\[dir='rtl'\] \.m-corner-beside \{\s*margin-inline: var\(--m-corner-r-gap, 0px\) var\(--m-corner-l-gap, 0px\);/
|
||||
);
|
||||
expect(corner).toMatch(
|
||||
/\.m-corner-side \{\s*margin-inline: var\(--m-corner-side-l, 0px\) var\(--m-corner-side-r, 0px\);/
|
||||
);
|
||||
expect(css).toMatch(/\.m-page:has\(\.m-corner-own\) \{\s*padding-top: 0;/);
|
||||
expect(readFileSync(resolve(root, 'src/mobile/MobileShell.tsx'), 'utf8')).toContain("import './corner.css'");
|
||||
it('FE-MOB-CHROME-011: rows and layers a screen places itself keep to the same insets, and no screen handles the corner on its own', () => {
|
||||
const narrowRow = "html:not(:has(.m-shell[data-size='wide'], .m-shell[data-size='split'])) .m-safe-row {";
|
||||
expect(block(narrowRow)).toContain('margin-inline: var(--m-safe-l-gap, 0px) var(--m-safe-r-gap, 0px);');
|
||||
const wideBoth =
|
||||
"html:has(.m-shell[data-size='wide'], .m-shell[data-size='split']) :is(.m-safe-row, .m-safe-trail) {";
|
||||
expect(block(wideBoth)).toContain('margin-inline-end: var(--m-safe-r-gap, 0px);');
|
||||
const src = (file: string) => readFileSync(resolve(root, 'src', file), 'utf8');
|
||||
const shell = src('mobile/screens/trip/MTripShell.tsx');
|
||||
// The top row and the day chips stand beside it, a list tab ends before it on a wide window.
|
||||
expect(src('mobile/screens/trip/MTripShellParts.tsx')).toContain("CHROME_ROW = 'm-corner-beside absolute end-4");
|
||||
expect(shell.match(/\$\{CHROME_ROW\}/g)).toHaveLength(2);
|
||||
expect(shell).toContain('<div className="m-corner-side relative h-full">');
|
||||
expect(src('mobile/screens/trip/map/MMapArea.tsx')).toContain('m-corner-beside pointer-events-none absolute end-4');
|
||||
// A list tab's first row and a docked sheet start below it.
|
||||
expect(src('mobile/screens/trip/tabs/tabChrome.tsx')).toContain(
|
||||
'pt-[max(calc(var(--m-safe-top,12px)+58px),var(--m-corner-clear,0px))]'
|
||||
);
|
||||
expect(src('mobile/components/MSheet.tsx')).toContain(
|
||||
'top-[max(calc(var(--m-safe-top,12px)+56px),var(--m-corner-clear,0px))]'
|
||||
);
|
||||
expect(src('mobile/components/MSectionNav.tsx')).toContain("'m-corner-flow px-4 ");
|
||||
expect(src('mobile/screens/trip/MTripShellParts.tsx')).toContain("CHROME_ROW = 'm-safe-row absolute end-4");
|
||||
expect(src('mobile/screens/trip/MTripShell.tsx')).toContain('<div className="m-safe-trail relative h-full">');
|
||||
expect(src('mobile/screens/trip/map/MMapArea.tsx')).toContain('m-safe-row pointer-events-none absolute end-4');
|
||||
expect(src('mobile/components/MSheet.tsx')).toContain('${base} m-safe-trail ');
|
||||
// The capsule's own measurement is read in mobile.css alone.
|
||||
expect(src('mobile/MobileShell.tsx')).not.toContain('corner.css');
|
||||
for (const file of [
|
||||
'mobile/components/MSectionNav.tsx',
|
||||
'mobile/screens/trip/tabs/tabChrome.tsx',
|
||||
'mobile/screens/journey/MJourneyDetail.tsx',
|
||||
'mobile/screens/vacay/MVacay.tsx',
|
||||
]) {
|
||||
expect(src(file)).not.toMatch(/m-corner|trek-native-corner/);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
@@ -600,7 +600,7 @@ describe('MRoadtripTab', () => {
|
||||
const scroller = container.querySelector('[class*="overflow-y-auto"]') as HTMLElement
|
||||
// 96px band plus a 44px bar plus its gap. A padding left at the old 102 would
|
||||
// put the head card's first line behind the glass.
|
||||
expect(scroller.className).toContain('pt-[max(calc(var(--m-safe-top,12px)+150px),var(--m-corner-clear,0px))]')
|
||||
expect(scroller.className).toContain('pt-[calc(var(--m-safe-top,12px)+150px)]')
|
||||
})
|
||||
it('FE-MOB-RTTAB-031: no stage, no search bar, and the chain keeps its old top', () => {
|
||||
// Without a stage the corridor falls back to the trip's first routed day, which
|
||||
@@ -610,7 +610,7 @@ describe('MRoadtripTab', () => {
|
||||
|
||||
expect(screen.queryByText('roadtrip.poi.title')).toBeNull()
|
||||
const scroller = container.querySelector('[class*="overflow-y-auto"]') as HTMLElement
|
||||
expect(scroller.className).toContain('pt-[max(calc(var(--m-safe-top,12px)+102px),var(--m-corner-clear,0px))]')
|
||||
expect(scroller.className).toContain('pt-[calc(var(--m-safe-top,12px)+102px)]')
|
||||
})
|
||||
})
|
||||
|
||||
|
||||
@@ -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)]])
|
||||
})
|
||||
})
|
||||
|
||||
+128
@@ -0,0 +1,128 @@
|
||||
import { Migration } from '@mikro-orm/migrations';
|
||||
|
||||
interface AuditRow {
|
||||
action: string;
|
||||
user_id: number | string | null;
|
||||
resource: string | null;
|
||||
details: string | null;
|
||||
}
|
||||
|
||||
interface UserEmailRow {
|
||||
id: number | string;
|
||||
email: string;
|
||||
}
|
||||
|
||||
interface AuditDetails {
|
||||
email?: unknown;
|
||||
targetUser?: unknown;
|
||||
fields?: unknown;
|
||||
}
|
||||
|
||||
/** One admin save of an account: the address it found, and whether it sent an email at all. */
|
||||
interface AdminSave {
|
||||
found: string | null;
|
||||
sentEmail: boolean;
|
||||
}
|
||||
|
||||
interface History {
|
||||
/** The addresses the account was created or registered with; null once one of them is unreadable. */
|
||||
baselines: string[] | null;
|
||||
/** The admin saves since its creation, oldest first. */
|
||||
saves: AdminSave[];
|
||||
}
|
||||
|
||||
function readDetails(details: string | null): AuditDetails {
|
||||
if (!details) return {};
|
||||
try {
|
||||
const value: unknown = JSON.parse(details);
|
||||
return value && typeof value === 'object' ? (value as AuditDetails) : {};
|
||||
} catch {
|
||||
return {};
|
||||
}
|
||||
}
|
||||
|
||||
const normalize = (email: string) => email.trim().toLowerCase();
|
||||
|
||||
/**
|
||||
* Marks an address an account set itself even when an admin saved the account
|
||||
* afterwards.
|
||||
*
|
||||
* `Migration20200101042800_an_email_the_account_typed_in_itself` and
|
||||
* `Migration20200101046480_an_address_changed_after_an_admin_made_the_account`
|
||||
* set `email_self_asserted` for an account whose address moved away from the one
|
||||
* it was registered or created with, unless an `admin.user_update` row names
|
||||
* `email`. But the edit dialog sends the email on every save, so every admin save
|
||||
* names it, a role change too, and one save of the account at any time kept the
|
||||
* flag at 0, even long after the account had moved its own address.
|
||||
*
|
||||
* Each such row also holds the address the account had when the admin saved it
|
||||
* (`targetUser`). So the history answers who set the current address: if every
|
||||
* admin save already found it, it was set before the first save, and between the
|
||||
* creation and that save only the account itself could change it. If the last
|
||||
* save that found another address sent no email, the address moved after that
|
||||
* save, again by the account itself. Either way the account is marked.
|
||||
*
|
||||
* When that last save did send an email, the admin may have typed the current
|
||||
* address in, and the rows cannot tell: the admin's new address is not logged,
|
||||
* and neither is a change the account made in its settings before 5.0.0. Such an
|
||||
* account stays as it is, the same as every account at its registered address and
|
||||
* every account with no creation row: marking it would refuse the first SSO
|
||||
* sign-in of an address an admin vouched for. Since 5.0.0 a change in the
|
||||
* settings sets the flag directly and an admin's new address clears it, so an
|
||||
* account this can still mark is one whose address moved before that.
|
||||
*
|
||||
* A creation row starts the account's history anew, so the saves of an account
|
||||
* that once held the same id do not count. An unreadable creation row or save
|
||||
* leaves the account as it is. Only accounts still at 0 are touched, and nothing
|
||||
* is ever cleared.
|
||||
*/
|
||||
export class Migration20200101046500_an_address_moved_before_an_admin_saved_the_account extends Migration {
|
||||
override name = 'Migration20200101046500_an_address_moved_before_an_admin_saved_the_account';
|
||||
|
||||
override async up(): Promise<void> {
|
||||
const rows = (await this.execute(
|
||||
`SELECT action, user_id, resource, details FROM audit_log
|
||||
WHERE action IN ('user.register', 'admin.user_create', 'admin.user_update')
|
||||
ORDER BY id`,
|
||||
)) as AuditRow[];
|
||||
|
||||
const histories = new Map<string, History>();
|
||||
for (const row of rows) {
|
||||
const details = readDetails(row.details);
|
||||
if (row.action === 'admin.user_update') {
|
||||
const history = row.resource ? histories.get(row.resource) : undefined;
|
||||
if (!history) continue;
|
||||
const found = typeof details.targetUser === 'string' ? normalize(details.targetUser) : null;
|
||||
const sentEmail = !Array.isArray(details.fields) || details.fields.includes('email');
|
||||
history.saves.push({ found, sentEmail });
|
||||
continue;
|
||||
}
|
||||
// A registration names the account in user_id, an admin's creation in resource.
|
||||
const owner = row.action === 'user.register' ? row.user_id : row.resource;
|
||||
if (owner === null) continue;
|
||||
const id = String(owner);
|
||||
const before = histories.get(id)?.baselines;
|
||||
const baselines =
|
||||
typeof details.email === 'string' && before !== null ? [...(before ?? []), normalize(details.email)] : null;
|
||||
histories.set(id, { baselines, saves: [] });
|
||||
}
|
||||
if (histories.size === 0) return;
|
||||
|
||||
const users = (await this.execute(
|
||||
`SELECT id, email FROM users WHERE COALESCE(is_guest, 0) = 0 AND email_self_asserted = 0`,
|
||||
)) as UserEmailRow[];
|
||||
// Queued, run after up() returns; the id comes from the database and is
|
||||
// checked to be an integer, nothing a user typed.
|
||||
for (const user of users) {
|
||||
const history = histories.get(String(user.id));
|
||||
if (!history?.baselines) continue;
|
||||
const current = normalize(user.email);
|
||||
if (history.baselines.includes(current)) continue;
|
||||
const lastOther = [...history.saves].reverse().find((save) => save.found !== current);
|
||||
if (lastOther && (lastOther.found === null || lastOther.sentEmail)) continue;
|
||||
const rowId = Number(user.id);
|
||||
if (!Number.isInteger(rowId)) continue;
|
||||
this.addSql(`UPDATE users SET email_self_asserted = 1 WHERE id = ${rowId}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
import { decodeSessionClaims } from '../auth-core/jwt-verify';
|
||||
import { setAuthCookie } from '../common/cookie';
|
||||
import { SessionsService, sessionClientFrom } from '../sessions/sessions.service';
|
||||
import { AuthService } from './auth.service';
|
||||
import { CallHandler, ExecutionContext, Injectable, NestInterceptor } from '@nestjs/common';
|
||||
|
||||
import type { Request, Response } from 'express';
|
||||
@@ -15,19 +16,23 @@ import type { Observable } from 'rxjs';
|
||||
* historical default duration).
|
||||
*
|
||||
* Cheap by construction, one write per half-life at most:
|
||||
* - `req.user` is only set after a guard ran verifyJwtAndLoadUser on this exact
|
||||
* request, which already proved the token's `pv` matches the DB and its
|
||||
* session is active, so the user id, pv and session id can be copied from
|
||||
* the decoded (not re-verified) token.
|
||||
* - Only a token past half its life is looked at again: the decoded claims
|
||||
* answer that, and every younger token costs nothing more.
|
||||
* - Such a token is verified once more, through the same check the guards use
|
||||
* (signature, expiry, `pv` against the DB, an active session), and must name
|
||||
* the user this request runs as. `req.user` alone proves nothing about the
|
||||
* cookie: a route with its own guard chain lets that chain authenticate, and
|
||||
* ApiTokenGuard does so with a public API key while the cookie beside it was
|
||||
* never checked. Renewing that cookie re-signed whatever it claimed.
|
||||
* - A request a public API key authenticated renews nothing, even beside a
|
||||
* valid cookie: the key is that request's credential, and a key must never
|
||||
* yield a browser session.
|
||||
* - A tracked token is re-signed under the same session id and the session's
|
||||
* expiry moves with it; a token from before sessions were tracked comes back
|
||||
* as a tracked session whose id is derived from that token, so the parallel
|
||||
* requests of one page load renew it into one session, not several. If the
|
||||
* session ended in between, nothing is renewed.
|
||||
* - The cookie is only renewed when it is the verified credential: extractToken
|
||||
* prefers the cookie over the Authorization header, so cookie-present +
|
||||
* req.user set means the guard verified the cookie. Bearer-only callers
|
||||
* (MCP, API clients) are never renewed.
|
||||
* - Bearer-only callers (MCP, API clients) carry no cookie and are never renewed.
|
||||
*
|
||||
* The cookie is written eagerly, before the handler runs: renewal doesn't
|
||||
* depend on the handler's outcome, and this sidesteps @Res()/streaming routes
|
||||
@@ -38,7 +43,10 @@ import type { Observable } from 'rxjs';
|
||||
*/
|
||||
@Injectable()
|
||||
export class SessionRenewalInterceptor implements NestInterceptor {
|
||||
constructor(private readonly sessions: SessionsService) {}
|
||||
constructor(
|
||||
private readonly sessions: SessionsService,
|
||||
private readonly auth: AuthService,
|
||||
) {}
|
||||
|
||||
async intercept(context: ExecutionContext, next: CallHandler): Promise<Observable<unknown>> {
|
||||
if (context.getType() === 'http') {
|
||||
@@ -51,7 +59,7 @@ export class SessionRenewalInterceptor implements NestInterceptor {
|
||||
|
||||
private async maybeRenew(req: Request & { user?: { id: number } }, res: Response): Promise<void> {
|
||||
const cookieToken: string | undefined = (req as { cookies?: Record<string, string> }).cookies?.trek_session;
|
||||
if (!req.user || !cookieToken || res.headersSent) return;
|
||||
if (!req.user || req.apiToken || !cookieToken || res.headersSent) return;
|
||||
|
||||
const claims = decodeSessionClaims(cookieToken);
|
||||
if (!claims || claims.purpose || claims.id !== req.user.id) return;
|
||||
@@ -60,6 +68,9 @@ export class SessionRenewalInterceptor implements NestInterceptor {
|
||||
const halfLife = claims.iat + (claims.exp - claims.iat) / 2;
|
||||
if (Date.now() / 1000 < halfLife) return;
|
||||
|
||||
const owner = await this.auth.verifyJwtToken(cookieToken);
|
||||
if (!owner || owner.id !== req.user.id) return;
|
||||
|
||||
const token = await this.sessions.renew(
|
||||
{ id: req.user.id, pv: claims.pv, remember: claims.remember, jti: claims.jti, token: cookieToken },
|
||||
sessionClientFrom(req),
|
||||
|
||||
@@ -12,6 +12,7 @@ import { AppSettings } from '../../src/db/entities/AppSettings.entity';
|
||||
import { AuditLog } from '../../src/db/entities/AuditLog.entity';
|
||||
import { Users } from '../../src/db/entities/Users.entity';
|
||||
import { AuthModule } from '../../src/nest/auth/auth.module';
|
||||
import { AuthService } from '../../src/nest/auth/auth.service';
|
||||
import { SessionRenewalInterceptor } from '../../src/nest/auth/session-renewal.interceptor';
|
||||
import { encrypt_api_key } from '../../src/nest/common/crypto/apiKeyCrypto';
|
||||
import { TrekExceptionFilter } from '../../src/nest/common/trek-exception.filter';
|
||||
@@ -86,7 +87,9 @@ describe('Auth e2e (real auth guard + real service + real cookie service + temp
|
||||
nest.useGlobalPipes(new ZodValidationPipe());
|
||||
// Mirror the production APP_INTERCEPTOR: sliding session renewal (#1927).
|
||||
// Inert for the harness's exp-less tokens and freshly issued logins.
|
||||
nest.useGlobalInterceptors(new SessionRenewalInterceptor(moduleRef.get(SessionsService)));
|
||||
nest.useGlobalInterceptors(
|
||||
new SessionRenewalInterceptor(moduleRef.get(SessionsService), moduleRef.get(AuthService)),
|
||||
);
|
||||
await nest.init();
|
||||
return nest;
|
||||
}
|
||||
|
||||
@@ -15,16 +15,19 @@ import { db } from '../../src/db/database';
|
||||
import { UserSessions } from '../../src/db/entities/UserSessions.entity';
|
||||
import { Users } from '../../src/db/entities/Users.entity';
|
||||
import { AuthModule } from '../../src/nest/auth/auth.module';
|
||||
import { AuthService } from '../../src/nest/auth/auth.service';
|
||||
import { SessionRenewalInterceptor } from '../../src/nest/auth/session-renewal.interceptor';
|
||||
import { encryptMfaSecret } from '../../src/nest/common/crypto/mfaCrypto';
|
||||
import { TrekExceptionFilter } from '../../src/nest/common/trek-exception.filter';
|
||||
import { ZodValidationPipe } from '../../src/nest/common/zod-validation.pipe';
|
||||
import { withRequestContext } from '../../src/nest/database/request-context';
|
||||
import { MailerService } from '../../src/nest/notifications/mailer/mailer.service';
|
||||
import { PublicApiModule } from '../../src/nest/public-api/public-api.module';
|
||||
import { SessionPurgeJob } from '../../src/nest/sessions/session-purge.job';
|
||||
import { SessionsService } from '../../src/nest/sessions/sessions.service';
|
||||
import { createUser } from '../helpers/factories';
|
||||
import { insertRow, updateRows } from '../helpers/factories/rows';
|
||||
import { makeMcpToken } from '../helpers/factories/tokens';
|
||||
import { sessionRows } from '../helpers/sessions';
|
||||
import { resetRateLimits } from '../helpers/test-db';
|
||||
import { createTestMikroOrmModule } from '../helpers/test-orm';
|
||||
@@ -71,7 +74,14 @@ describe('Sessions e2e (sign-in sessions that can be ended)', () => {
|
||||
|
||||
async function build() {
|
||||
moduleRef = await Test.createTestingModule({
|
||||
imports: [await TestUnitOfWorkModule.forRoot(db), await createTestMikroOrmModule(db), AuthModule],
|
||||
// PublicApiModule brings the one guard chain that authenticates by something
|
||||
// other than the session cookie, which the renewal must not mistake for it.
|
||||
imports: [
|
||||
await TestUnitOfWorkModule.forRoot(db),
|
||||
await createTestMikroOrmModule(db),
|
||||
AuthModule,
|
||||
PublicApiModule,
|
||||
],
|
||||
})
|
||||
.overrideProvider(MailerService)
|
||||
.useValue({ sendPasswordResetEmail })
|
||||
@@ -80,7 +90,9 @@ describe('Sessions e2e (sign-in sessions that can be ended)', () => {
|
||||
nest.use(cookieParser());
|
||||
nest.useGlobalFilters(new TrekExceptionFilter());
|
||||
nest.useGlobalPipes(new ZodValidationPipe());
|
||||
nest.useGlobalInterceptors(new SessionRenewalInterceptor(moduleRef.get(SessionsService)));
|
||||
nest.useGlobalInterceptors(
|
||||
new SessionRenewalInterceptor(moduleRef.get(SessionsService), moduleRef.get(AuthService)),
|
||||
);
|
||||
await nest.init();
|
||||
return nest;
|
||||
}
|
||||
@@ -296,6 +308,32 @@ describe('Sessions e2e (sign-in sessions that can be ended)', () => {
|
||||
]);
|
||||
}, 10000);
|
||||
|
||||
it('a public API key beside a session cookie never yields a session, whatever the cookie claims', async () => {
|
||||
const { user } = freshUser('sess-apikey');
|
||||
const key = 'trek_' + '7'.repeat(48);
|
||||
await makeMcpToken(moduleRef.get(MikroORM), user.id, {
|
||||
rawToken: key,
|
||||
token_prefix: key.slice(0, 13),
|
||||
kind: 'api',
|
||||
});
|
||||
const iat = Math.floor(Date.now() / 1000) - 60000;
|
||||
// Past half its life, naming the key's owner and no session: one signed with a
|
||||
// secret that is not the server's, and a real one.
|
||||
const forged = `trek_session=${jwt.sign({ id: user.id, pv: 0, iat }, 'not-the-server-secret', { expiresIn: 86400, algorithm: 'HS256' })}`;
|
||||
const genuine = sessionCookie(user.id, 0, { lifetime: 86400, consumed: 60000 });
|
||||
|
||||
const withKey = (cookie: string) =>
|
||||
request(server).get('/api/v1/trips').set('Authorization', `Bearer ${key}`).set('Cookie', cookie);
|
||||
for (const res of [await withKey(forged), await withKey(genuine)]) {
|
||||
expect(res.status).toBe(200);
|
||||
const set = (res.headers['set-cookie'] ?? []) as unknown as string[];
|
||||
expect(set.some((c) => c.startsWith('trek_session='))).toBe(false);
|
||||
}
|
||||
expect(await sessionRows(db as never, user.id)).toEqual([]);
|
||||
// The forged cookie opens nothing on its own either.
|
||||
expect((await me(forged)).status).toBe(401);
|
||||
}, 10000);
|
||||
|
||||
it("on a demo instance, visitors of the shared demo account neither see nor end each other's sessions", async () => {
|
||||
createUser(db as never, { username: 'demo', email: 'demo@trek.app' });
|
||||
vi.stubEnv('DEMO_MODE', 'true');
|
||||
|
||||
@@ -7,9 +7,15 @@
|
||||
* `Migration20200101046480_an_address_changed_after_an_admin_made_the_account`
|
||||
* applies the same rule to an account an admin created, whose baseline is the
|
||||
* address in the `admin.user_create` row instead of a `user.register` one.
|
||||
*
|
||||
* `Migration20200101046500_an_address_moved_before_an_admin_saved_the_account`
|
||||
* reads the address each admin save found, so a save after the account moved
|
||||
* its own address no longer keeps it at 0, while a save that may have typed the
|
||||
* current address in still does.
|
||||
*/
|
||||
import { Migration20200101042800_an_email_the_account_typed_in_itself } from '../../../src/db/migrations/Migration20200101042800_an_email_the_account_typed_in_itself';
|
||||
import { Migration20200101046480_an_address_changed_after_an_admin_made_the_account } from '../../../src/db/migrations/Migration20200101046480_an_address_changed_after_an_admin_made_the_account';
|
||||
import { Migration20200101046500_an_address_moved_before_an_admin_saved_the_account } from '../../../src/db/migrations/Migration20200101046500_an_address_moved_before_an_admin_saved_the_account';
|
||||
import {
|
||||
createMigrationOrm,
|
||||
migrateTo,
|
||||
@@ -24,6 +30,7 @@ import { describe, expect, it } from 'vitest';
|
||||
|
||||
const TARGET = 'Migration20200101042800_an_email_the_account_typed_in_itself';
|
||||
const ADMIN_MADE = 'Migration20200101046480_an_address_changed_after_an_admin_made_the_account';
|
||||
const SAVED_AFTER = 'Migration20200101046500_an_address_moved_before_an_admin_saved_the_account';
|
||||
|
||||
async function ormBeforeTarget(target = TARGET): Promise<MikroORM> {
|
||||
const orm = await createMigrationOrm();
|
||||
@@ -193,3 +200,123 @@ describe('admin-made account email migration', () => {
|
||||
}
|
||||
}, 30000);
|
||||
});
|
||||
|
||||
async function seedSaves(orm: MikroORM): Promise<void> {
|
||||
// 9 is the admin; every save below is the edit dialog's unless said otherwise,
|
||||
// which sends the email each time. 1 was made by the admin, moved its address
|
||||
// itself, and the admin changed its role afterwards; 2 the same but the save
|
||||
// came first, so the admin may have typed the new address in; 3 got its new
|
||||
// address from the admin; 4 registered, moved, and the admin saved it later;
|
||||
// 5 registered and an API save sent no email before the account moved; 6 has a
|
||||
// save whose details are broken; 7 was made under an id an earlier account
|
||||
// held, whose save does not count; 8 moved, was saved, then the admin gave it
|
||||
// another address; 10 moved with no save at all; 11 is still at the address it
|
||||
// was made with; 12 is already marked; 13 has no creation row; 14 is a guest.
|
||||
await rawExec(
|
||||
orm,
|
||||
`INSERT INTO users (id, username, email, password_hash, email_self_asserted, is_guest) VALUES
|
||||
(1, 'later', 'colleague-1@test', 'x', 0, 0),
|
||||
(2, 'earlier', 'colleague-2@test', 'x', 0, 0),
|
||||
(3, 'given', 'given-by-admin@test', 'x', 0, 0),
|
||||
(4, 'registered', 'colleague-4@test', 'x', 0, 0),
|
||||
(5, 'api', 'colleague-5@test', 'x', 0, 0),
|
||||
(6, 'broken', 'colleague-6@test', 'x', 0, 0),
|
||||
(7, 'reused', 'colleague-7@test', 'x', 0, 0),
|
||||
(8, 'regiven', 'regiven-by-admin@test', 'x', 0, 0),
|
||||
(9, 'admin', 'admin@test', 'x', 0, 0),
|
||||
(10, 'unsaved', 'colleague-10@test', 'x', 0, 0),
|
||||
(11, 'kept', 'Kept@Test', 'x', 0, 0),
|
||||
(12, 'marked', 'marked-now@test', 'x', 1, 0),
|
||||
(13, 'seeded', 'seeded-now@test', 'x', 0, 0),
|
||||
(14, 'guest', 'guest-now@test', '', 0, 1)`,
|
||||
);
|
||||
await rawExec(
|
||||
orm,
|
||||
`INSERT INTO audit_log (user_id, action, resource, details) VALUES
|
||||
(9, 'admin.user_create', '1', '{"username":"later","email":"later@test","role":"user"}'),
|
||||
(9, 'admin.user_update', '1', '{"targetUser":"colleague-1@test","fields":["username","email","role"]}'),
|
||||
(9, 'admin.user_create', '2', '{"username":"earlier","email":"earlier@test","role":"user"}'),
|
||||
(9, 'admin.user_update', '2', '{"targetUser":"earlier@test","fields":["username","email","role"]}'),
|
||||
(9, 'admin.user_create', '3', '{"username":"given","email":"given@test","role":"user"}'),
|
||||
(9, 'admin.user_update', '3', '{"targetUser":"given@test","fields":["username","email","role"]}'),
|
||||
(4, 'user.register', NULL, '{"username":"registered","email":"registered@test","role":"user"}'),
|
||||
(9, 'admin.user_update', '4', '{"targetUser":"Colleague-4@Test","fields":["username","email","role"]}'),
|
||||
(5, 'user.register', NULL, '{"username":"api","email":"api@test","role":"user"}'),
|
||||
(9, 'admin.user_update', '5', '{"targetUser":"api@test","fields":["role"]}'),
|
||||
(9, 'admin.user_create', '6', '{"username":"broken","email":"broken@test","role":"user"}'),
|
||||
(9, 'admin.user_update', '6', 'not json'),
|
||||
(9, 'admin.user_create', '7', '{"username":"gone","email":"gone@test","role":"user"}'),
|
||||
(9, 'admin.user_update', '7', '{"targetUser":"gone@test","fields":["username","email","role"]}'),
|
||||
(7, 'user.register', NULL, '{"username":"reused","email":"reused@test","role":"user"}'),
|
||||
(9, 'admin.user_create', '8', '{"username":"regiven","email":"regiven@test","role":"user"}'),
|
||||
(9, 'admin.user_update', '8', '{"targetUser":"colleague-8@test","fields":["username","email","role"]}'),
|
||||
(9, 'admin.user_update', '8', '{"targetUser":"colleague-8@test","fields":["username","email","role"]}'),
|
||||
(9, 'admin.user_create', '10', '{"username":"unsaved","email":"unsaved@test","role":"user"}'),
|
||||
(9, 'admin.user_create', '11', '{"username":"kept","email":"kept@test","role":"user"}'),
|
||||
(9, 'admin.user_update', '11', '{"targetUser":"kept@test","fields":["username","email","role"]}'),
|
||||
(12, 'user.register', NULL, '{"username":"marked","email":"marked@test","role":"user"}'),
|
||||
(9, 'admin.user_update', '13', '{"targetUser":"seeded@test","fields":["role"]}'),
|
||||
(9, 'admin.user_create', '14', '{"username":"guest","email":"guest@test","role":"user"}')`,
|
||||
);
|
||||
}
|
||||
|
||||
const SAVED_AFTER_EXPECTED = [
|
||||
{ id: 1, email_self_asserted: 1 },
|
||||
{ id: 2, email_self_asserted: 0 },
|
||||
{ id: 3, email_self_asserted: 0 },
|
||||
{ id: 4, email_self_asserted: 1 },
|
||||
{ id: 5, email_self_asserted: 1 },
|
||||
{ id: 6, email_self_asserted: 0 },
|
||||
{ id: 7, email_self_asserted: 1 },
|
||||
{ id: 8, email_self_asserted: 0 },
|
||||
{ id: 9, email_self_asserted: 0 },
|
||||
{ id: 10, email_self_asserted: 1 },
|
||||
{ id: 11, email_self_asserted: 0 },
|
||||
{ id: 12, email_self_asserted: 1 },
|
||||
{ id: 13, email_self_asserted: 0 },
|
||||
{ id: 14, email_self_asserted: 0 },
|
||||
];
|
||||
|
||||
describe('admin saves after the account moved its address', () => {
|
||||
it('EMAILSELF-MIG-006: an address no admin save can have set is marked, whatever the save sent', async () => {
|
||||
const orm = await ormBeforeTarget(SAVED_AFTER);
|
||||
try {
|
||||
await seedSaves(orm);
|
||||
await migrateTo(orm, SAVED_AFTER);
|
||||
expect(await flags(orm)).toEqual(SAVED_AFTER_EXPECTED);
|
||||
} finally {
|
||||
await orm.close(true);
|
||||
}
|
||||
}, 30000);
|
||||
|
||||
it('EMAILSELF-MIG-007: running it again changes nothing', async () => {
|
||||
const orm = await ormBeforeTarget(SAVED_AFTER);
|
||||
try {
|
||||
await seedSaves(orm);
|
||||
await migrateTo(orm, SAVED_AFTER);
|
||||
await runMigrationDirect(orm, Migration20200101046500_an_address_moved_before_an_admin_saved_the_account);
|
||||
expect(await flags(orm)).toEqual(SAVED_AFTER_EXPECTED);
|
||||
} finally {
|
||||
await orm.close(true);
|
||||
}
|
||||
}, 30000);
|
||||
|
||||
it('EMAILSELF-MIG-008: an audit log without a creation row reads no account', async () => {
|
||||
const orm = await ormBeforeTarget(SAVED_AFTER);
|
||||
try {
|
||||
await rawExec(
|
||||
orm,
|
||||
`INSERT INTO users (id, username, email, password_hash) VALUES (1, 'solo', 'solo-now@test', 'x')`,
|
||||
);
|
||||
await rawExec(
|
||||
orm,
|
||||
`INSERT INTO audit_log (user_id, action, resource, details) VALUES
|
||||
(1, 'admin.user_update', '1', '{"targetUser":"solo-now@test","fields":["role"]}')`,
|
||||
);
|
||||
await migrateTo(orm, SAVED_AFTER);
|
||||
expect(await flags(orm)).toEqual([{ id: 1, email_self_asserted: 0 }]);
|
||||
} finally {
|
||||
await orm.close(true);
|
||||
}
|
||||
}, 30000);
|
||||
});
|
||||
|
||||
@@ -116,6 +116,7 @@ const UNNUMBERED = [
|
||||
'Migration20200101046460_an_upgraded_install_gets_the_columns_its_history_skipped',
|
||||
'Migration20200101046480_an_address_changed_after_an_admin_made_the_account',
|
||||
'Migration20200101046490_a_trip_can_switch_its_own_addons',
|
||||
'Migration20200101046500_an_address_moved_before_an_admin_saved_the_account',
|
||||
];
|
||||
// The last step the positional runner ever had; planLegacyBaseline refuses a
|
||||
// schema_version past it.
|
||||
|
||||
@@ -4,8 +4,10 @@
|
||||
* lifetime. Covers the renew path (fresh token + cookie semantics per the
|
||||
* `remember` claim) and every skip condition: young token, bearer-only request,
|
||||
* unauthenticated request, purpose token, id mismatch, malformed claims,
|
||||
* headers already sent, non-http context.
|
||||
* headers already sent, non-http context, a cookie the session check refuses
|
||||
* and a request a public API key authenticated.
|
||||
*/
|
||||
import type { AuthService } from '../../../src/nest/auth/auth.service';
|
||||
import { SessionRenewalInterceptor } from '../../../src/nest/auth/session-renewal.interceptor';
|
||||
import type { SessionsService } from '../../../src/nest/sessions/sessions.service';
|
||||
import type { CallHandler, ExecutionContext } from '@nestjs/common';
|
||||
@@ -30,6 +32,7 @@ function makeRes(headersSent = false) {
|
||||
type ReqShape = {
|
||||
cookies?: Record<string, string>;
|
||||
user?: { id: number };
|
||||
apiToken?: { scopes: string[] | null };
|
||||
headers?: Record<string, string>;
|
||||
secure?: boolean;
|
||||
};
|
||||
@@ -46,10 +49,18 @@ function handler(): CallHandler & { handle: ReturnType<typeof vi.fn> } {
|
||||
return { handle: vi.fn(() => of('ok')) };
|
||||
}
|
||||
|
||||
function makeInterceptor(renewed: string | null = 'renewed.jwt') {
|
||||
/**
|
||||
* `verified` is what the session check answers for the cookie: the user its
|
||||
* token names when it is a live session, null when it is not one.
|
||||
*/
|
||||
function makeInterceptor(renewed: string | null = 'renewed.jwt', verified: { id: number } | null = { id: 1 }) {
|
||||
const renew = vi.fn().mockResolvedValue(renewed);
|
||||
const interceptor = new SessionRenewalInterceptor({ renew } as unknown as SessionsService);
|
||||
return { interceptor, renew };
|
||||
const verifyJwtToken = vi.fn().mockResolvedValue(verified);
|
||||
const interceptor = new SessionRenewalInterceptor(
|
||||
{ renew } as unknown as SessionsService,
|
||||
{ verifyJwtToken } as unknown as AuthService,
|
||||
);
|
||||
return { interceptor, renew, verifyJwtToken };
|
||||
}
|
||||
|
||||
async function run(
|
||||
@@ -65,12 +76,13 @@ async function run(
|
||||
}
|
||||
|
||||
describe('SessionRenewalInterceptor', () => {
|
||||
it('SES-RENEW-001: does not renew a token under half of its lifetime', async () => {
|
||||
const { interceptor, renew } = makeInterceptor();
|
||||
it('SES-RENEW-001: does not renew a token under half of its lifetime, nor look it up', async () => {
|
||||
const { interceptor, renew, verifyJwtToken } = makeInterceptor();
|
||||
const res = makeRes();
|
||||
const t = token({ id: 1, pv: 0 }, 86400, 1000); // ~1% consumed
|
||||
await run(interceptor, { cookies: { trek_session: t }, user: { id: 1 } }, res);
|
||||
expect(renew).not.toHaveBeenCalled();
|
||||
expect(verifyJwtToken).not.toHaveBeenCalled();
|
||||
expect(res.cookie).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
@@ -226,4 +238,37 @@ describe('SessionRenewalInterceptor', () => {
|
||||
expect(renew).toHaveBeenCalled();
|
||||
expect(res.cookie).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('SES-RENEW-014: renews no cookie the session check refuses, whoever req.user is', async () => {
|
||||
// What a route with its own guard chain can see: ApiTokenGuard set req.user from
|
||||
// a key, and the cookie beside it is unsigned, past half its life and names the
|
||||
// key's owner without a session id. Decoding it alone would re-sign it.
|
||||
const { interceptor, renew, verifyJwtToken } = makeInterceptor('renewed.jwt', null);
|
||||
const res = makeRes();
|
||||
const iat = Math.floor(Date.now() / 1000) - 60000;
|
||||
const forged = jwt.sign({ id: 1, pv: 0, iat }, 'not-the-server-secret', { expiresIn: 86400, algorithm: 'HS256' });
|
||||
await run(interceptor, { cookies: { trek_session: forged }, user: { id: 1 } }, res);
|
||||
expect(verifyJwtToken).toHaveBeenCalledWith(forged);
|
||||
expect(renew).not.toHaveBeenCalled();
|
||||
expect(res.cookie).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('SES-RENEW-015: renews no cookie whose session belongs to another user than the request', async () => {
|
||||
const { interceptor, renew } = makeInterceptor('renewed.jwt', { id: 2 });
|
||||
const res = makeRes();
|
||||
const t = token({ id: 1, pv: 0 }, 86400, 60000);
|
||||
await run(interceptor, { cookies: { trek_session: t }, user: { id: 1 } }, res);
|
||||
expect(renew).not.toHaveBeenCalled();
|
||||
expect(res.cookie).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('SES-RENEW-016: a request a public API key authenticated renews nothing, even beside a valid cookie', async () => {
|
||||
const { interceptor, renew, verifyJwtToken } = makeInterceptor();
|
||||
const res = makeRes();
|
||||
const t = token({ id: 1, pv: 0 }, 86400, 60000);
|
||||
await run(interceptor, { cookies: { trek_session: t }, user: { id: 1 }, apiToken: { scopes: null } }, res);
|
||||
expect(verifyJwtToken).not.toHaveBeenCalled();
|
||||
expect(renew).not.toHaveBeenCalled();
|
||||
expect(res.cookie).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -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