The most complete open-source travel planner: real-time collaboration, bookings, budgets, packing lists, journals, offline PWA, SSO and an AI-ready MCP server, with planet-wide place search and routing built in.
TypeScript budget-trackercollaborativedockeritinerarymcp-serveroffline-firstopen-sourceopenstreetmappacking-listpwareal-timeself-hostedselfhostedtraveltravel-apptravel-journaltravel-plannertripitwanderlog
fix(studio): the travel panel builds its tiles with the book engine's factories
Mauricea11c8bfaa716
diff --git a/client/scripts/eslint-baseline.json b/client/scripts/eslint-baseline.jsonindex 03c927b19..d1308f2c7 100644--- a/client/scripts/eslint-baseline.json+++ b/client/scripts/eslint-baseline.json@@ -6,7 +6,7 @@"complexity": 226,"@typescript-eslint/no-explicit-any": 146,"trek/no-swallowed-catch": 131,- "max-params": 34,+ "max-params": 33,"trek/store-without-selector": 67,"react-hooks/refs": 557,"react-hooks/set-state-in-effect": 195,@@ -14,7 +14,7 @@"react-hooks/exhaustive-deps": 116,"@typescript-eslint/no-unused-vars": 126,"react-hooks/immutability": 28,- "max-lines-per-function": 133,+ "max-lines-per-function": 132,"react-hooks/static-components": 78,"react-hooks/preserve-manual-memoization": 12,"no-useless-assignment": 7,diff --git a/client/scripts/theme-baseline.json b/client/scripts/theme-baseline.jsonindex 2ab2bac1c..74cf5cc22 100644--- a/client/scripts/theme-baseline.json+++ b/client/scripts/theme-baseline.json@@ -105,7 +105,6 @@"components/Studio/StudioInspector.tsx": 2,"components/Studio/StudioShell.tsx": 2,"components/Studio/StudioSidebar.tsx": 2,- "components/Studio/StudioTravelPanel.tsx": 1,"components/Studio/TravelElements.tsx": 5,"components/Studio/printSheets.ts": 5,"components/SystemNotices/ReleaseNoticeVisuals.tsx": 4,diff --git a/client/src/components/Studio/StudioInspector.tsx b/client/src/components/Studio/StudioInspector.tsxindex 570ba7b24..e88e52093 100644--- a/client/src/components/Studio/StudioInspector.tsx+++ b/client/src/components/Studio/StudioInspector.tsx@@ -52,6 +52,7 @@ export function StudioInspector({spreadIndex,page,stats,+ path,source,setPageNumbers,t,@@ -62,6 +63,8 @@ export function StudioInspector({setPageNumbers: (patch: Partial<BookPageNumbers>) => void/** Live journey figures, so a travel element can be brought up to date. */stats: JourneyStats | null+ /** The journey's recorded way, thinned, so a map of the whole journey can be given it again. */+ path: [number, number][][]/** The journal itself, so a bound mark can be re-set from it. */source: JourneySourcet: (k: string) => string@@ -647,7 +650,7 @@ export function StudioInspector({</>)}- <TravelInspector el={el} stats={stats} set={set} t={t} locale={locale} />+ <TravelInspector el={el} stats={stats} path={path} set={set} t={t} locale={locale} />{/*Where it sits, folded away.diff --git a/client/src/components/Studio/StudioShell.tsx b/client/src/components/Studio/StudioShell.tsxindex 5b7a0633b..2fab721b7 100644--- a/client/src/components/Studio/StudioShell.tsx+++ b/client/src/components/Studio/StudioShell.tsx@@ -2,7 +2,7 @@ import { useEffect, useRef, useState } from 'react'import { createPortal } from 'react-dom'import { useNavigate } from 'react-router'import {- ArrowLeft, BookOpen, Check, ChevronDown, ClipboardPaste, Download, Maximize2, MessageSquare, Minus, Plus,+ ArrowLeft, BookOpen, Check, ChevronDown, ClipboardPaste, Download, Maximize2, Minus, Plus,Redo2, Sparkles, Undo2,} from 'lucide-react'import { useJourneyStudio } from '../../pages/journeyStudio/useJourneyStudio'@@ -21,7 +21,7 @@ import { PeerBadges } from './PeerBadges'import { TrimField } from './TrimField'import { Tooltip } from '../shared/Tooltip'import { useStudioStore } from '../../store/studioStore'-import StudioAssistantPanel, { StudioPageStage } from './StudioAssistantPanel'+import { StudioAssistantColumn, StudioAssistantToggle, StudioPageStage } from './StudioAssistantPanel'import { useStudioAssistant, type StudioAssistant } from './useStudioAssistant'import '../../styles/dashboard.css'import '../../styles/studio.css'@@ -128,12 +128,13 @@ export default function StudioShell() {spreadIndex={s.activeSpread}page={s.page}stats={s.stats}+ path={s.path}source={s.source}setPageNumbers={s.setPageNumbers}t={s.t}locale={s.locale}/>- <AssistantColumn s={s} assistant={assistant} />+ <StudioAssistantColumn assistant={assistant} title={s.journey?.title} /></div><StudioPageStage assistant={assistant} />@@ -153,12 +154,6 @@ export default function StudioShell() {type Studio = ReturnType<typeof useJourneyStudio>-/** The chat column at the end of the body, while it is open. */-function AssistantColumn({ s, assistant }: { s: Studio; assistant: StudioAssistant }) {- if (!assistant.open) return null- return <StudioAssistantPanel assistant={assistant} title={s.journey?.title || s.t('journey.title')} />-}-function StudioBar({s, bookView, setBookView, onExport, assistant,}: {@@ -238,17 +233,7 @@ function StudioBar({<AutoLayoutButton s={s} />{/* The book's assistant, as a column beside the page; only where it can run for this user. */}- {assistant.available && (- <button type="button"- className={`st-tool ${assistant.open ? 'is-on' : ''}`}- onClick={assistant.toggle}- aria-pressed={assistant.open}- title={s.t('journey.studio.assistant.toggleHint')}- >- <MessageSquare size={14} />- <span className="st-tool-label">{s.t('journey.studio.assistant.toggle')}</span>- </button>- )}+ <StudioAssistantToggle assistant={assistant} /><button type="button"className="st-tool is-primary"onClick={onExport}diff --git a/client/src/components/Studio/StudioTravelInspector.tsx b/client/src/components/Studio/StudioTravelInspector.tsxindex 453e897a9..1e4d7d421 100644--- a/client/src/components/Studio/StudioTravelInspector.tsx+++ b/client/src/components/Studio/StudioTravelInspector.tsx@@ -3,7 +3,7 @@ import type {BookBadgeElement, BookCountriesElement, BookElement, BookListElement, BookMapElement,BookMetric, BookStatsElement, JourneyStats,} from '@trek/shared'-import { BOOK_METRICS, isStale, refreshPatch, routeFor } from '@trek/shared'+import { BOOK_METRICS, MAX_PATH_POINTS, MAX_PATH_SEGMENTS, isStale, refreshPatch } from '@trek/shared'import { Swatches } from './StudioSwatches'import { FontButtons, WeightLine } from './StudioTypeControls'import { sourceIdOf, useMapSources } from './mapSources'@@ -25,6 +25,8 @@ export interface TravelInspectorProps {el: BookElement/** Live figures, for the refresh button. Null while loading or on failure. */stats: JourneyStats | null+ /** The journey's recorded way, thinned, which a map switched back to the whole journey draws again. */+ path: [number, number][][]set: (patch: Partial<BookElement>) => voidt: (k: string) => stringlocale: string@@ -36,7 +38,7 @@ interface Props<T> {t: (k: string) => string}-export function TravelInspector({ el, stats, set, t }: TravelInspectorProps) {+export function TravelInspector({ el, stats, path, set, t }: TravelInspectorProps) {if (el.kind !== 'map' && el.kind !== 'stats' && el.kind !== 'countries'&& el.kind !== 'badge' && el.kind !== 'list'@@ -64,7 +66,7 @@ export function TravelInspector({ el, stats, set, t }: TravelInspectorProps) {</div>)}- {el.kind === 'map' && <MapProps el={el} set={set} t={t} stats={stats} />}+ {el.kind === 'map' && <MapProps el={el} set={set} t={t} stats={stats} journeyPath={path} />}{el.kind === 'stats' && <StatsProps el={el} set={set} t={t} />}{el.kind === 'countries' && <CountriesProps el={el} set={set} t={t} />}{el.kind === 'badge' && <BadgeProps el={el} set={set} t={t} />}@@ -188,7 +190,13 @@ function ListProps({ el, set, t }: Props<BookListElement>) {)}-function MapProps({ el, set, t, stats }: Props<BookMapElement> & { stats: JourneyStats | null }) {+/** A map's panel reads the journey too: its live figures, and its recorded way for a map of all of it. */+type MapPropsInput = Props<BookMapElement> & {+ stats: JourneyStats | null+ journeyPath: [number, number][][]+}++function MapProps({ el, set, t, stats, journeyPath }: MapPropsInput) {const cartoKey = useCartoApiKey()const [roadState, setRoadState] = useState<'idle' | 'busy'>('idle')const [roadDone, setRoadDone] = useState(0)@@ -248,15 +256,26 @@ function MapProps({ el, set, t, stats }: Props<BookMapElement> & { stats: Journe})),]}onPick={id => {- if (!stats) returnconst tripId = id === 0 ? null : id- const route = routeFor(stats, tripId)+ // The scope it already has: a re-cut would only drop the roads loaded for these legs.+ if (!stats || tripId === (el.tripId ?? null)) return+ /*+ * Re-cut by the engine's own refresh at the new scope, so the+ * stops and countries are what refresh_travel and a newly placed+ * map of that scope hold. The recorded way is the whole+ * journey's: a trip map draws none, as the engine places none,+ * and a map of the whole journey gets it back from the journey+ * at the engine's caps, so a switch there and back loses+ * nothing. The roads go with the old legs, since entry i is the+ * way from stop i to stop i + 1 of the route that is gone.+ */set({+ ...refreshPatch({ ...el, tripId }, stats),tripId,- countries: tripId == null- ? stats.countries.map(c => c.code)- : [...new Set(route.map(p => p.country).filter((c): c is string => !!c))],- points: route.map(p => ({ lat: p.lat, lng: p.lng, label: p.label, photoId: p.photoId ?? null })),+ path: tripId == null+ ? journeyPath.slice(0, MAX_PATH_SEGMENTS).map(seg => seg.slice(0, MAX_PATH_POINTS))+ : [],+ roads: [],} as Partial<BookElement>)}}/>diff --git a/client/src/components/Studio/StudioTravelPanel.tsx b/client/src/components/Studio/StudioTravelPanel.tsxindex 449b6549d..f17f745c3 100644--- a/client/src/components/Studio/StudioTravelPanel.tsx+++ b/client/src/components/Studio/StudioTravelPanel.tsx@@ -1,13 +1,16 @@import { useEffect, useRef, useState } from 'react'import { Check, RouteOff } from 'lucide-react'-import type { BookElement, BookMetric, BookPageSetup, JourneyStats } from '@trek/shared'-import { BOOK_METRICS, bookElementId as uid } from '@trek/shared'+import type {+ BookBadgeVariant, BookElement, BookMapScope, BookMetric, BookPageSetup, BookTravelContext, JourneyStats,+} from '@trek/shared'+import {+ BOOK_METRICS, bookBadgeValue, bookCountryName, bookElementId as uid, bookTravelBadge, bookTravelCountries,+ bookTravelMap, bookTravelSize, bookTravelStats,+} from '@trek/shared'import { useStudioStore } from '../../store/studioStore'import { PanelHead } from './StudioPanelHead'import { Section } from './StudioControls'import { TravelPreview } from './TravelPreview'-import { formatBookCoords, routeFor } from '@trek/shared'-import { useMapSources } from './mapSources'import { fetchRoads } from './roadRoute'/**@@ -61,10 +64,19 @@ type StopRow = {* the section scannable. The tile measures its own width — see TravelPreview.*/-/** Kilometres, grouped for the reader's locale. */-function formatDistance(metres: number, locale: string): string {- return `${new Intl.NumberFormat(locale, { maximumFractionDigits: 0 }).format(metres / 1000)} km`-}+/** The words a mark carries, as the book engine resolves them. */+type BadgeValue = NonNullable<ReturnType<typeof bookBadgeValue>>++/*+ * The two imagery maps, satellite first: the recommendation should not be the+ * second thing read. Their tiles and credit are the book engine's own+ * (BOOK_MAP_SOURCES), so a satellite map placed here is the one the assistant+ * places.+ */+const IMAGERY = [+ { id: 'satellite', labelKey: 'journey.studio.mapSourceSatellite' },+ { id: 'relief', labelKey: 'journey.studio.mapSourceRelief' },+] as constfunction Card({ label, onClick, children, recommended = false, title }: {label: string@@ -143,23 +155,6 @@ export function StudioTravelPanel({return { x: (W - w) / 2, y: (page.pageHeight - h) / 2, w, h }}- const mapSide = Math.min(page.pageWidth, page.pageHeight) * 0.72-- /*- * The imagery this instance can reach, so the relief card below places a map- * that already has its template and its credit rather than an empty one the- * user then has to point at a source.- *- * Asked for above the empty-state return, and not beside the card that reads- * it: a journey whose figures are still loading renders this panel once with- * no stats at all, and a hook that only runs on the second render is a hook- * count that changes between them.- */- const sources = useMapSources(- { x: 0, y: 0, w: mapSide, h: mapSide * 0.78 },- (stats?.points ?? []).map(p => ({ lat: p.lat, lng: p.lng })),- )-if (!stats) {return (<>@@ -171,11 +166,25 @@ export function StudioTravelPanel({)}- const base = {- rotation: 0, opacity: 1, locked: false,- font: 'sans' as const, color: '#1a1a1a', accent: '#111111', textScale: 1, weight: 700 as const,- stale: false,+ /*+ * What the book engine's factories read: the journey, its recorded way and+ * the words in the reader's language. Every tile below is built by the+ * factory the engine's `add` calls. Where it lands is the panel's own:+ * centred across the spread, where `add` takes the right page. Two words are+ * still the panel's too, so a mark placed here and one the assistant adds+ * can read differently: the country mark carries the name in `text`, where+ * the engine's value has it in `sub`, and the day mark says `dayWord`, where+ * the engine says `day` (the two differ in ja, ko, zh and zh-TW).+ */+ const travel: BookTravelContext = {+ locale, stats, path, entries: [],+ labels: {+ day: t('journey.studio.dayWord'), stations: t('journey.studio.stations'), summary: t('journey.studio.summary'),+ countries: t('journey.studio.countries'), distance: t('journey.studio.metric.distance'),+ pros: t('journey.editor.pros'), cons: t('journey.editor.cons'),+ },}+ const at = (size: { w: number; h: number }) => centre(size.w, size.h)/*** Country names in the reader's language, not the server's.@@ -185,29 +194,13 @@ export function StudioTravelPanel({* a German book says "Island" and an English one says "Iceland" — from one set* of codes, with no translation table to keep in step.*/- const countryName = (code: string): string => {- try {- const display = new Intl.DisplayNames([locale], { type: 'region' })- return display.of(code.toUpperCase()) || code.toUpperCase()- } catch {- return stats.countries.find(c => c.code === code)?.name || code.toUpperCase()- }- }-- const values: Record<string, number> = {- distance: stats.distance,- days: stats.days,- steps: stats.steps,- photos: stats.photos,- countries: stats.countries.length,- places: stats.places,- furthest: stats.furthest,- }+ const countryName = (code: string): string => bookCountryName(code, locale, stats)/** Each builder returns the finished element. The tile renders it and the- * click places it, so the preview and the result are the same object — there- * is no second description of what a card means.+ * click places it, so the preview and the result are the same object, and+ * the object is the engine's, so there is no second description of what a+ * card means.*//** The linked trips that actually put stops on the route. */const tripsWithRoute = (stats.trips ?? []).filter(t => t.points > 0)@@ -262,11 +255,6 @@ export function StudioTravelPanel({})}- /* Satellite first: the recommendation should not be the second thing read. */- const imagery = sources- .filter(s => s.id === 'relief' || s.id === 'satellite')- .sort((a, b) => (a.id === 'satellite' ? -1 : b.id === 'satellite' ? 1 : 0))-/*** One country, as the entry a list would have made of it.*@@ -280,90 +268,28 @@ export function StudioTravelPanel({* The name is editable afterwards, so numbering them "1. Germany",* "2. Netherlands" is typing rather than a feature.*/- const countryEl = (code: string): BookElement => ({- ...base, id: uid('co'), kind: 'countries',- frame: centre(page.pageWidth * 0.34, 34),- codes: [code], names: [countryName(code)],- layout: 'list', showOutline: true, showFlag: false, showName: true, align: 'center',- } as BookElement)-- const mapEl = (- style: 'minimal' | 'outline' | 'dark' | 'paper',- source: 'vector' | 'tiles' | 'static' = 'vector',- url = '',- attribution = '',- clip: 'rect' | 'country' = 'rect',- /** Null is the whole journey; a trip id is a map of that trip alone. */- tripId: number | null = null,- ): BookElement => {- const route = routeFor(stats, tripId)- return {- ...base, id: uid('mp'), kind: 'map',- frame: centre(mapSide, mapSide * 0.78),- style, source, tileUrl: url, attribution, zoom: null, clip, tripId,- /*- * White over a photograph, ink on paper. The accent IS the line, so this is- * how a satellite map arrives drawn the way the reference draws it, while- * the colour stays something the user can change afterwards.- */- accent: source === 'tiles' || source === 'static' ? '#ffffff' : base.accent,- showLand: true, showRoute: true, showPins: true, showLabels: false,- /*- * A map placed today gets the drawn treatment; the contract defaults to the- * plain line so that every book made before this existed opens unchanged.- * Set explicitly rather than inherited because this object is cast, not- * parsed.- */- routeStyle: 'drawn', routeArc: 'bow', routeDash: 'arcs', pinStyle: 'photo',- countries: tripId == null- ? stats.countries.map(c => c.code)- : [...new Set(route.map(p => p.country).filter((c): c is string => !!c))],- points: route.map(p => ({ lat: p.lat, lng: p.lng, label: p.label, photoId: p.photoId ?? null })),- /*- * Frozen into the element, like every other travel figure: a page that- * fetches its own route at print time is a page that changes when someone- * edits the trip, and prints empty when the export runs signed out.- */- path,- // Empty until somebody asks for the roads; see roadRoute.ts.- roads: [],- fitPadding: 0.5,- fitToCountries: true,- } as BookElement- }+ const countryEl = (code: string): BookElement =>+ bookTravelCountries(travel, { id: uid('co'), frame: at(bookTravelSize('countries', page)), codes: [code] })- /*- * A mark is placed at the size that suits what it holds.+ /**+ * A map as the engine's `add` places it, in the style the card offers.*- * One size for all six put a flag and a country name into a box built for a- * line of coordinates, which is how a small mark ends up floating inside a- * large selection rectangle. Fractions of the page, so the proportions hold- * on any format.+ * The scope is the journey or one trip. A trip map carries no recorded way:+ * the trail is the journey's, and a map fitted to it would frame the whole+ * journey around one trip and lose the bow its legs are drawn with.*/- const MARK_SIZE: Record<string, [number, number]> = {- flag: [0.25, 0.062],- date: [0.16, 0.14],- day: [0.17, 0.062],- coords: [0.36, 0.05],- country: [0.22, 0.078],- distance: [0.26, 0.066],- }+ const mapEl = (+ style: 'minimal' | 'outline' | 'dark' | 'paper',+ scope: BookMapScope = 'journey',+ source: 'vector' | 'relief' | 'satellite' = 'vector',+ ): BookElement => ({+ ...bookTravelMap(travel, stats, { id: uid('mp'), frame: at(bookTravelSize('map', page)), scope, source }),+ style,+ })- const badgeEl = (- variant: 'flag' | 'date' | 'day' | 'coords' | 'country' | 'distance',- text: string,- sub: string,- code: string | null,- style: 'plain' | 'chip' | 'outline' | 'stacked' = 'plain',- ): BookElement => {- const [fw, fh] = MARK_SIZE[variant] ?? [0.24, 0.08]- return {- ...base, id: uid('bd'), kind: 'badge', autoColor: true,- showIcon: true, showLabel: true, autoIconColor: true, iconColor: '#111111',- frame: centre(page.pageWidth * fw, page.pageHeight * fh),- variant, text, sub, code, style,- } as BookElement- }+ /** A mark at the size that suits what it holds, which is the engine's size for its variant. */+ const badgeEl = (variant: BookBadgeVariant, value: BadgeValue): BookElement =>+ bookTravelBadge({ id: uid('bd'), frame: at(bookTravelSize('badge', page, { variant })), variant, value })/*** One figure on its own.@@ -373,11 +299,8 @@ export function StudioTravelPanel({* and offering only the composition meant anyone wanting "14 DAYS" beside a* picture had to place all four and delete three.*/- const singleEl = (metric: BookMetric): BookElement => ({- ...base, id: uid('st'), kind: 'stats',- frame: centre(page.pageWidth * 0.22, page.pageHeight * 0.13),- metrics: [metric], layout: 'grid', showIcons: true, units: 'metric', values,- } as BookElement)+ const singleEl = (metric: BookMetric): BookElement =>+ bookTravelStats(stats, { id: uid('st'), frame: at(bookTravelSize('stats', page)), metrics: [metric] })/** Place a copy — the previewed element keeps its own id for React. */const place = (el: BookElement) => {@@ -411,37 +334,20 @@ export function StudioTravelPanel({}}- const first = stats.points[0] ?? null- const firstCountry = stats.countries[0] ?? null- const startDay = stats.start ? new Date(`${stats.start}T00:00:00`) : null-- const marks: { el: BookElement; label: string }[] = []- if (startDay) {- marks.push({- el: badgeEl('date', String(startDay.getDate()),- startDay.toLocaleDateString(locale, { month: 'long' }).toUpperCase(), null, 'stacked'),- label: t('journey.studio.dateMark'),- })- }- marks.push({- el: badgeEl('day', `${t('journey.studio.dayWord')} 1`, '', null, 'chip'),- label: t('journey.studio.dayMark'),- })- if (first) {- marks.push({- el: badgeEl('coords', formatBookCoords(first.lat, first.lng), first.label, null),- label: t('journey.studio.coordsMark'),- })- }- if (firstCountry) {- marks.push({- el: badgeEl('flag', '', countryName(firstCountry.code), firstCountry.code),- label: t('journey.studio.flagMark'),- })- }- marks.push({- el: badgeEl('distance', formatDistance(stats.distance, locale), t('journey.studio.metric.distance'), null, 'outline'),- label: t('journey.studio.distanceMark'),+ /*+ * The marks of the journey, with the words the engine resolves for each. A+ * mark the journey cannot fill (no start date, no stop, no country) is not+ * offered.+ */+ const marks: { el: BookElement; label: string }[] = ([+ ['date', t('journey.studio.dateMark')],+ ['day', t('journey.studio.dayMark')],+ ['coords', t('journey.studio.coordsMark')],+ ['flag', t('journey.studio.flagMark')],+ ['distance', t('journey.studio.distanceMark')],+ ] as const).flatMap(([variant, label]) => {+ const value = bookBadgeValue(travel, variant, null)+ return value ? [{ el: badgeEl(variant, value), label }] : []})return (@@ -562,7 +468,7 @@ export function StudioTravelPanel({a scale that suits a continent, and satellite is the grounditself, which is what a page about one country wants.*/}- {imagery.map(src => (+ {IMAGERY.map(src => (<Cardkey={src.id}/*@@ -578,10 +484,10 @@ export function StudioTravelPanel({label={t(src.labelKey)}recommended={src.id === 'satellite'}title={src.id === 'satellite' ? t('journey.studio.recommended') : undefined}- onClick={() => place(mapEl('minimal', 'tiles', src.url, src.attribution))}+ onClick={() => place(mapEl('minimal', 'journey', src.id))}><TravelPreview- el={mapEl('minimal', 'tiles', src.url, src.attribution)}+ el={mapEl('minimal', 'journey', src.id)}minHeight={62}maxHeight={80}/>@@ -606,7 +512,7 @@ export function StudioTravelPanel({<div className="st-section-label">{t('journey.studio.mapPerTrip')}</div><div className="st-travel-grid">{tripsWithRoute.map(trip => {- const el = mapEl('minimal', 'vector', '', '', 'rect', trip.id)+ const el = mapEl('minimal', { tripId: trip.id })return (<Cardkey={trip.id}@@ -658,7 +564,7 @@ export function StudioTravelPanel({*/}<div className="st-travel-grid" style={{ marginTop: 6 }}>{stats.countries.slice(0, 12).map(c => {- const el = badgeEl('country', countryName(c.code), '', c.code)+ const el = badgeEl('country', { text: countryName(c.code), sub: '', code: c.code })return (<Card key={`mark-${c.code}`} label={countryName(c.code)} onClick={() => place(el)}><TravelPreview el={el} minHeight={30} maxHeight={44} />diff --git a/client/tests/unit/studio/inspector.test.tsx b/client/tests/unit/studio/inspector.test.tsxindex f56f0ac1f..4c943d66d 100644--- a/client/tests/unit/studio/inspector.test.tsx+++ b/client/tests/unit/studio/inspector.test.tsx@@ -69,6 +69,7 @@ function draw(over: { page?: BookPageSetup; setPageNumbers?: (p: Partial<BookPagspreadIndex={0}page={over.page ?? setup()}stats={null}+ path={[]}source={source}setPageNumbers={over.setPageNumbers ?? (() => {})}t={(k: string) => k}diff --git a/client/tests/unit/studio/inspectorTravel.test.tsx b/client/tests/unit/studio/inspectorTravel.test.tsxindex 9fc860863..ac5232291 100644--- a/client/tests/unit/studio/inspectorTravel.test.tsx+++ b/client/tests/unit/studio/inspectorTravel.test.tsx@@ -69,7 +69,7 @@ const listEl = (over: Record<string, unknown> = {}): BookElement => bookListElem...over,}) as BookElement-function show(el: BookElement, live: JourneyStats | null = null) {+function show(el: BookElement, live: JourneyStats | null = null, trail: [number, number][][] = []) {useStudioStore.getState().load({version: 1, title: 'T', page,spreads: [{ id: 'sp1', role: 'inner', background: null, elements: [el], parked: [], entryId: null }],@@ -80,6 +80,7 @@ function show(el: BookElement, live: JourneyStats | null = null) {spreadIndex={0}page={page}stats={live}+ path={trail}source={{ entries: [], photos: [], photoEntries: {} }}setPageNumbers={() => {}}t={k => k}@@ -238,6 +239,60 @@ describe('the route map', () => {press('journey.studio.showLabels')expect(saved().showLabels).toBe(true)})++ /** A journey of two trips, so the map offers its scope at all. */+ const twoTrips: JourneyStats = journeyStatsSchema.parse({+ ...stats,+ countries: [+ { code: 'IS', name: 'Iceland', places: 2, firstVisit: '2026-01-01' },+ { code: 'PT', name: 'Portugal', places: 1, firstVisit: '2026-03-01' },+ ],+ points: [+ { lat: 64.14, lng: -21.94, label: 'Reykjavik', date: '2026-01-01', country: 'IS', tripId: 11 },+ { lat: 65.68, lng: -18.09, label: 'Akureyri', date: '2026-01-04', country: 'IS', tripId: 11 },+ { lat: 38.72, lng: -9.14, label: 'Lisboa', date: '2026-03-01', country: 'PT', tripId: 22 },+ ],+ trips: [+ { id: 11, title: 'North', start: '2026-01-01', end: '2026-01-05', points: 2 },+ { id: 22, title: 'South', start: '2026-03-01', end: '2026-03-02', points: 1 },+ ],+ })+ /** The journey's recorded way, as the Studio hands it to the inspector. */+ const trail: [number, number][][] = [[[64.14, -21.94], [38.72, -9.14]]]+ /** Roads loaded for the whole journey's legs: entry i runs from stop i to stop i + 1. */+ const roads = [[[64.14, -21.94], [64.0, -21.5], [65.68, -18.09]], null]++ /*+ * The scope switch re-cuts the map as the book engine refreshes one, so a+ * map turned into a trip map here holds what the panel or the assistant+ * would have placed for that trip: its own stops, its own countries, no+ * recorded way, since the trail is the whole journey's, and no roads, since+ * those belonged to the old legs. Switched back, the map takes the trail+ * from the journey again, so the round trip loses nothing.+ */+ it('STTRV-007: re-cuts a map to one trip as the engine does, and back to the journey with its trail', () => {+ show(mapEl({ countries: ['IS', 'PT'], path: trail, roads }), twoTrips, trail)++ pick('North')+ expect(saved()).toMatchObject({+ tripId: 11, countries: ['IS'], path: [], roads: [], stale: false,+ points: [{ label: 'Reykjavik' }, { label: 'Akureyri' }],+ })++ pick('journey.studio.mapWholeJourney')+ expect(saved()).toMatchObject({ tripId: null, countries: ['IS', 'PT'], roads: [], stale: false })+ expect(saved().path).toEqual(trail)+ expect(saved().points).toHaveLength(3)+ })++ it('STTRV-008: picking the scope a map already has writes nothing, so its loaded roads stay', () => {+ show(mapEl({ countries: ['IS', 'PT'], path: trail, roads }), twoTrips, trail)++ pick('journey.studio.mapWholeJourney')+ expect(saved()).toMatchObject({ tripId: null, path: trail, roads })+ // Still the one stop it was made with: a re-cut would have brought all three.+ expect(saved().points).toHaveLength(1)+ })})describe('the figures', () => {diff --git a/client/tests/unit/studio/travelPanelEngine.test.tsx b/client/tests/unit/studio/travelPanelEngine.test.tsxnew file mode 100644index 000000000..aabd293ed--- /dev/null+++ b/client/tests/unit/studio/travelPanelEngine.test.tsx@@ -0,0 +1,240 @@+// STTRV-001 to STTRV-006: the Travel panel places what the book engine's factories build, so a figure, a map, a+// country or a mark added by hand is the element the assistant's `add` adds. Only the frame is the panel's own:+// centred across the spread rather than on the right-hand page.+import { beforeEach, describe, expect, it, vi } from 'vitest';++import type { BookDocument, BookElement, BookFrame, BookTravelContext, JourneyStats } from '@trek/shared';+import {+ BOOK_SATELLITE_TILES,+ bookBadgeValue,+ bookPageSetupSchema,+ bookTravelBadge,+ bookTravelCountries,+ bookTravelMap,+ bookTravelSize,+ bookTravelStats,+} from '@trek/shared';++import { StudioTravelPanel } from '../../../src/components/Studio/StudioTravelPanel';+import { useStudioStore } from '../../../src/store/studioStore';+import { fireEvent, render, screen } from '../../helpers/render';++// A placed map asks for its roads. The answer never comes, so every map stays as it was placed.+vi.mock('../../../src/components/Map/RouteCalculator', () => ({+ calculateRouteWithLegs: vi.fn(() => new Promise(() => {})),+}));++const ICELAND = 11;+const PORTUGAL = 22;++const page = bookPageSetupSchema.parse({ preset: 'square-210' });++/** A stop on the route, read from a trip's place rather than from an entry. */+const stop = (+ label: string,+ [lat, lng]: [number, number],+ country: string,+ tripId: number,+ date: string+): JourneyStats['points'][number] => ({+ lat,+ lng,+ label,+ date,+ country,+ tripId,+ photoId: null,+ entryId: null,+});++const stats: JourneyStats = {+ journeyId: 5,+ distance: 4_000_000,+ days: 21,+ steps: 6,+ photos: 40,+ places: 12,+ furthest: 3_000_000,+ countries: [+ { code: 'IS', name: 'Iceland', places: 2, firstVisit: '2026-06-02' },+ { code: 'PT', name: 'Portugal', places: 2, firstVisit: '2026-09-04' },+ ],+ points: [+ { ...stop('Reykjavík', [64.14, -21.94], 'IS', ICELAND, '2026-06-02'), photoId: 3 },+ stop('Akureyri', [65.68, -18.12], 'IS', ICELAND, '2026-06-06'),+ stop('Lisboa', [38.72, -9.14], 'PT', PORTUGAL, '2026-09-04'),+ stop('Porto', [41.15, -8.61], 'PT', PORTUGAL, '2026-09-08'),+ ],+ // Named apart from the countries, so a trip card and a country card never share a name.+ trips: [+ { id: ICELAND, title: 'June', start: '2026-06-02', end: '2026-06-14', points: 2 },+ { id: PORTUGAL, title: 'September', start: '2026-09-04', end: '2026-09-12', points: 2 },+ ],+ excluded: [],+ start: '2026-06-02',+ end: '2026-09-12',+};++/** The recorded way, as the hook hands it to the panel. */+const PATH: [number, number][][] = [+ [+ [64.14, -21.94],+ [65.68, -18.12],+ ],+ [+ [38.72, -9.14],+ [41.15, -8.61],+ ],+];++/** What the panel hands the factories: `t` answers with the key in this suite. */+const travel: BookTravelContext = {+ locale: 'en',+ stats,+ path: PATH,+ entries: [],+ labels: {+ day: 'journey.studio.dayWord',+ stations: 'journey.studio.stations',+ summary: 'journey.studio.summary',+ countries: 'journey.studio.countries',+ distance: 'journey.studio.metric.distance',+ pros: 'journey.editor.pros',+ cons: 'journey.editor.cons',+ },+};++/** A size centred across the open spread, the panel's own placement. */+const spreadCentre = (size: { w: number; h: number }): BookFrame => ({+ x: (page.pageWidth * 2 - size.w) / 2,+ y: (page.pageHeight - size.h) / 2,+ w: size.w,+ h: size.h,+});++const ANY_FRAME: BookFrame = { x: 0, y: 0, w: 1, h: 1 };++/** An element apart from what the panel decides itself: the id it mints and where the frame goes. */+const content = (el: BookElement) => ({ ...el, id: '', frame: ANY_FRAME });++function open(journey: JourneyStats = stats) {+ return render(+ <StudioTravelPanel+ page={page}+ stats={journey}+ path={PATH}+ t={(k) => k}+ locale="en"+ canEdit={false}+ onToggleStop={async () => true}+ />+ );+}++const card = (name: string) => screen.getByRole('button', { name });++/** The element the last click put on the page. */+function placed(): BookElement {+ const elements = useStudioStore.getState().doc?.spreads[0]?.elements ?? [];+ const last = elements[elements.length - 1];+ if (!last) throw new Error('nothing was placed');+ return last;+}++beforeEach(() => {+ useStudioStore.getState().load({+ version: 1,+ title: 'T',+ page,+ spreads: [{ id: 's1', role: 'inner', background: null, elements: [], parked: [], entryId: null }],+ } as unknown as BookDocument);+});++describe('the Travel panel builds through the book engine', () => {+ it('STTRV-001: places a single figure as the engine builds it, centred across the spread', () => {+ open();++ fireEvent.click(card('journey.studio.metric.days'));++ const size = bookTravelSize('stats', page);+ expect(content(placed())).toEqual(+ content(bookTravelStats(stats, { id: 'st', frame: ANY_FRAME, metrics: ['days'] }))+ );+ expect(placed().frame).toEqual(spreadCentre(size));+ });++ it('STTRV-002: places a journey map with the recorded way, in the style of its card', () => {+ open();++ fireEvent.click(card('journey.studio.mapStyle.dark'));++ const engine = bookTravelMap(travel, stats, { id: 'mp', frame: ANY_FRAME, scope: 'journey' });+ expect(content(placed())).toEqual(content({ ...engine, style: 'dark' as const }));+ expect(placed()).toMatchObject({ kind: 'map', style: 'dark', source: 'vector', tripId: null, path: PATH });+ expect(placed().frame).toEqual(spreadCentre(bookTravelSize('map', page)));+ });++ it('STTRV-003: places a map per trip of that trip alone, with its own countries and no journey trail', () => {+ open();++ fireEvent.click(card('June'));++ const engine = bookTravelMap(travel, stats, { id: 'mp', frame: ANY_FRAME, scope: { tripId: ICELAND } });+ expect(content(placed())).toEqual(content(engine));+ expect(placed()).toMatchObject({+ tripId: ICELAND,+ countries: ['IS'],+ path: [],+ points: [{ label: 'Reykjavík', photoId: 3 }, { label: 'Akureyri' }],+ });+ });++ it('STTRV-004: places the satellite map the engine places, with its tiles, its credit and a white line', () => {+ open();++ fireEvent.click(card('journey.studio.mapSourceSatellite'));++ const engine = bookTravelMap(travel, stats, { id: 'mp', frame: ANY_FRAME, scope: 'journey', source: 'satellite' });+ expect(content(placed())).toEqual(content(engine));+ expect(placed()).toMatchObject({ source: 'tiles', tileUrl: BOOK_SATELLITE_TILES, accent: '#ffffff' });+ });++ it('STTRV-005: places each mark with the words, size and style the engine gives it', () => {+ open();++ const marks = [+ ['journey.studio.dateMark', 'date'],+ ['journey.studio.dayMark', 'day'],+ ['journey.studio.coordsMark', 'coords'],+ ['journey.studio.flagMark', 'flag'],+ ['journey.studio.distanceMark', 'distance'],+ ] as const;+ for (const [name, variant] of marks) {+ fireEvent.click(card(name));+ const value = bookBadgeValue(travel, variant, null);+ if (!value) throw new Error(`the engine has no ${variant} mark for this journey`);+ expect(content(placed())).toEqual(content(bookTravelBadge({ id: 'bd', frame: ANY_FRAME, variant, value })));+ expect(placed().frame).toEqual(spreadCentre(bookTravelSize('badge', page, { variant })));+ }+ // The last one, read back as words: the distance in an outline.+ expect(placed()).toMatchObject({ variant: 'distance', text: '4,000 km', style: 'outline' });+ });++ it('STTRV-006: offers no date mark without a start, and places a country and its mark by the name', () => {+ open({ ...stats, start: null });++ expect(screen.queryByRole('button', { name: 'journey.studio.dateMark' })).toBeNull();+ fireEvent.click(card('journey.studio.dayMark'));+ expect(placed()).toMatchObject({ variant: 'day', text: 'journey.studio.dayWord 1', style: 'chip' });++ const [outline, mark] = screen.getAllByRole('button', { name: 'Iceland' });+ fireEvent.click(outline);+ expect(content(placed())).toEqual(+ content(bookTravelCountries(travel, { id: 'co', frame: ANY_FRAME, codes: ['IS'] }))+ );+ expect(placed()).toMatchObject({ codes: ['IS'], names: ['Iceland'] });++ fireEvent.click(mark);+ expect(placed()).toMatchObject({ kind: 'badge', variant: 'country', text: 'Iceland', sub: '', code: 'IS' });+ });+});