import { useState, type ReactNode } from 'react' import type { BookBadgeElement, BookCountriesElement, BookElement, BookListElement, BookMapElement, BookMetric, BookStatsElement, JourneyStats, } from '@trek/shared' import { BOOK_BADGE_STYLES, BOOK_COUNTRY_LOOKS, BOOK_METRICS, BOOK_STATS_LOOKS, MAX_PATH_POINTS, MAX_PATH_SEGMENTS, isStale, refreshPatch, } from '@trek/shared' import { Swatches } from './StudioSwatches' import { StudioFontPicker } from './StudioFontPicker' import { WeightLine } from './StudioTypeControls' import { sourceIdOf, useMapSources } from './mapSources' import { printDpi, tileView } from './mapTiles' import { useCartoApiKey } from '../../hooks/useTileUrl' import { Choice, Line, Picks, Section, Switch } from './StudioControls' import { fetchRoads } from './roadRoute' import { useStudioStore } from '../../store/studioStore' import { StudioThemeLink } from './theme/StudioThemeLink' import { mapZoomInUse, travelTypeInUse } from './inspector/inspectorModel' /** * Properties of the travel elements. * * Its own file because these five are a different kind of thing from a photo or * a paragraph: what you adjust is *what the element says*, not how a box looks. * Keeping them here leaves the inspector about the elements that have been * there since the beginning. * * In the order every kind follows: what the element says first (a map's scope, * source and framing, a summary's figures, a mark's words), then where it sits, * then how it looks (a map's line and layers, the type, the colours). */ 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) => void t: (k: string) => string locale: string /** The position and size group, which every kind places after what it is. */ position: ReactNode } interface Props { el: T set: (patch: Partial) => void t: (k: string) => string } export function TravelInspector({ el, stats, path, set, t, position }: TravelInspectorProps) { const theme = useStudioStore(s => s.doc?.theme) if ( el.kind !== 'map' && el.kind !== 'stats' && el.kind !== 'countries' && el.kind !== 'badge' && el.kind !== 'list' ) { return null } const stale = isStale(el, stats) return ( <> {stale && (

{t('journey.studio.staleHint')}

)} {el.kind === 'map' && } {el.kind === 'stats' && } {el.kind === 'countries' && } {el.kind === 'badge' && } {el.kind === 'list' && } {position} {el.kind === 'map' && } {/* * Type, for all five alike. * * These elements set their own words — a figure over its caption, a * country's name over its outline — and until now the only thing you * could change about that was the size. A book set in a serif with its * stats block in the default sans is a book with one element in the * wrong typeface and no way to fix it. Folded, and open on an element * already set in another face, weight or size. */}
set(patch as Partial)} t={t} />
set({ weight } as Partial)} t={t} /> ({ value: scale, label: `${scale}×`, }))} onPick={textScale => set({ textScale } as Partial)} />
{/* * Colour, for all five alike, and in one group. * * These were two sections called Accent and Colour, one under the other, * each ten unlabelled swatches wrapping onto two rows: twenty squares and * no way to tell which of them painted what. The role now sits beside the * row and says it — the accent is the mark's own colour, the ink is what * is written on it. * * They ship with one warm accent so a book made without touching anything * still reads as designed. That is a starting point, not a house style: a * book printed to match a cover, or one that simply should not be orange, * needs both of these. */}
set({ accent: c } as Partial)} /> set({ accent, accentToken } as Partial)} onUnlink={() => set({ accentToken: undefined } as Partial)} /> {/* Picking a colour is what turns automatic off, so the swatch does both and the switch below is the way back rather than the way in. Only marks have it; nothing else here has a fill of its own for the words to answer to. */} set( (el.kind === 'badge' ? { color: c, autoColor: false } : { color: c }) as Partial, )} /> set( (el.kind === 'badge' ? { color, token, autoColor: false } : { color, token }) as Partial, )} onUnlink={() => set({ token: undefined } as Partial)} /> {el.kind === 'badge' && (
set({ autoColor: !el.autoColor } as Partial)} />
)}
) } function ListProps({ el, set, t }: Props) { return (
set({ layout } as Partial)} />
set({ showMarks: !el.showMarks } as Partial)} />
) } /** 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 & { stats: JourneyStats | null journeyPath: [number, number][][] } /** What a map shows: which trip, where the picture comes from and its style, the framing and the zoom. */ function MapContent({ el, set, t, stats, journeyPath }: MapPropsInput) { const cartoKey = useCartoApiKey() const sources = useMapSources(el.frame, el.points, { source: el.source, tileUrl: el.tileUrl }) /** Only trips that put stops on the route: a map of the others is a blank. */ const tripsWithRoute = (stats?.trips ?? []).filter(t => t.points > 0) /* * The grid this element will really fetch, asked for here so the panel can * say what it will print at. Same call the renderer makes, same answer. */ const view = el.source === 'tiles' && el.tileUrl ? tileView(el.points, { w: el.frame.w, h: el.frame.h }, el.tileUrl, el.zoom, undefined, 'print', cartoKey) : null const dpi = view ? printDpi(view, el.tileUrl) : null return ( <> {/* Which trip, when the journey is made of more than one. A journey of two trips drawn as one route puts a line from the last stop of the first to the first stop of the second: usually the longest leg on the page, and one nobody travelled. Switching here re-cuts the route on the spot rather than at the next refresh, because a control that changes nothing visible reads as broken. */} {tripsWithRoute.length > 1 && (
({ value: trip.id, label: trip.title || t('journey.studio.untitled'), })), ]} onPick={id => { const tripId = id === 0 ? null : id // 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, path: tripId == null ? journeyPath.slice(0, MAX_PATH_SEGMENTS).map(seg => seg.slice(0, MAX_PATH_POINTS)) : [], roads: [], } as Partial) }} />
)} {/* Where the picture comes from and what it looks like: one question with two halves, which is one group rather than two. */}
({ value: src.id, label: t(src.labelKey) }))} onPick={id => { const src = sources.find(x => x.id === id) if (!src) return set({ source: src.source, tileUrl: src.url, // The credit travels with the source. Switching to imagery and // leaving the previous attribution would print the wrong one. attribution: src.attribution, } as Partial) }} />
({ value: style, label: t(`journey.studio.mapStyle.${style}`), }))} onPick={style => set({ style } as Partial)} />
{el.source !== 'vector' && ( <>

{t(SOURCE_HINT[sourceIdOf(el, sources)]?.hintKey ?? 'journey.studio.mapSourceHint')}

{/* What this map will actually print at, at the size it is now. A number rather than a warning icon: 300 means nothing to argue with, and somebody who wants a soft map on purpose can have one. */} {dpi != null && (

{t('journey.studio.mapPrintDpi')} {dpi} dpi {dpi < 150 && `, ${t('journey.studio.mapPrintDpiLow')}`}

)} )}
{/* ── What the map shows ───────────────────────────────────────────── Three questions, and they are not the same question: how close the view is, how much air is left around it, and what shape the picture is cut to. The first two used to be decided for you, and the decision was wrong often enough to be the loudest complaint about this element: a trip that stayed inside one city was drawn as the whole country with two dots in the middle of it. */}
set({ fitToCountries: v === 'country' } as Partial)} /> {/* Room around what is drawn, as a share of it: the same setting has to look right around a walk across a city and a drive across a continent, and millimetres cannot do that. */} Math.abs(el.fitPadding - v) < 0.001) ?? 0.18} options={[ { value: 0.04, label: t('journey.studio.mapPadTight') }, { value: 0.18, label: t('journey.studio.mapPadNormal') }, { value: 0.5, label: t('journey.studio.mapPadWide') }, { value: 1.2, label: t('journey.studio.mapPadFar') }, ]} onPick={fitPadding => set({ fitPadding } as Partial)} /> {/* And the shape. A rectangle is a map in a box, which is what a full page wants; cut to the coastline it stops being a figure and becomes an illustration that can sit next to anything. */} set({ clip } as Partial)} />
{el.source === 'tiles' && (
({ value: z, label: String(z) })), ]} onPick={z => set({ zoom: z === -1 ? null : z } as Partial)} />
)} ) } /** * How a map looks: the line of the route, whether it follows the roads, and * which layers are drawn. After the position, like the look of every kind. */ function MapLook({ el, set, t }: Props) { const [roadState, setRoadState] = useState<'idle' | 'busy'>('idle') const [roadDone, setRoadDone] = useState(0) const hasRoads = (el.roads ?? []).some(r => r && r.length > 1) /* * One leg at a time, paced, and written into the document when it is done * rather than leg by leg: a hundred commits would be a hundred undo steps and * a hundred autosaves for one action. */ const loadRoads = async () => { setRoadState('busy') setRoadDone(0) try { const roads = await fetchRoads( el.points.map(p => ({ lat: p.lat, lng: p.lng })), { onProgress: done => setRoadDone(done) }, ) set({ roads } as Partial) } finally { setRoadState('idle') } } return ( <> {/* How the line itself is drawn, and whether it follows real roads. Open by default, unlike the groups below it. It was folded, on the reasoning that a look is chosen once per book — but a control nobody can see is a control nobody has, and the first thing anyone wants from a map of a journey is the line across it. */}
set({ routeStyle } as Partial)} /> {/* The roads, fetched once and kept. Not a switch, because it is not free: it asks a public routing service one question per leg, from this browser, and the answer is then frozen into the document so the book prints the same line offline and next year. A switch would imply it could simply be turned back on later, on a page that is being exported, which is exactly when it cannot. */}
{/* Which way the line goes between two stops. A choice rather than a button, because that is what it is from where the user sits: the roads, or the way a map has always drawn a leg it does not know. That the roads have to be fetched once and are then kept in the book is an implementation detail, and the only place it shows is the counter while it works. */} {roadState === 'busy' ? (
{t('journey.studio.roadsBusy')} {roadDone}/{Math.max(1, el.points.length - 1)}
) : ( { if (v === 'direct') { set({ roads: [] } as Partial) } else { void loadRoads() } }} /> )}
{hasRoads && roadState !== 'busy' && (
)}

{t(hasRoads ? 'journey.studio.roadsHave' : 'journey.studio.roadsHint')}

{el.routeStyle === 'drawn' && ( <> set({ routeArc } as Partial)} /> {el.routeArc === 'bow' && (
set({ routeDash: el.routeDash === 'arcs' ? 'solid' : 'arcs', } as Partial)} />
)}
set({ pinStyle } as Partial)} />
{el.pinStyle === 'photo' && !el.points.some(p => p.photoId != null) && (

{t('journey.studio.pinPhotoNone')}

)} )}
{/* Four things that are either drawn or not. They used to be the same pill as the style choice above, so a layer looked like an option. */}
{el.source !== 'tiles' && el.source !== 'static' && ( set({ showLand: !el.showLand } as Partial)} /> )} set({ showRoute: !el.showRoute } as Partial)} /> set({ showPins: !el.showPins } as Partial)} /> set({ showLabels: !el.showLabels } as Partial)} />
) } function StatsProps({ el, set, t }: Props) { const toggleMetric = (m: BookMetric) => { const next = el.metrics.includes(m) ? el.metrics.filter(x => x !== m) : [...el.metrics, m] // An empty panel would be a blank rectangle nobody could get back out of, // so the last figure cannot be switched off. if (!next.length) return set({ metrics: next } as Partial) } return ( <> {/* Which figures, out of seven. A set rather than a row of choices, and it looks like one now: the picked ones carry a tick instead of being the same filled pill the layout below uses for "this one". */}
({ value: m, label: t(`journey.studio.metric.${m}`) }))} onToggle={toggleMetric} />
{/* The look first: the arrangement below belongs to the classic one alone. */} ({ value: look, label: t(`journey.studio.statsLook.${look}`) }))} onPick={look => set({ look } as Partial)} /> {(el.look ?? 'classic') === 'classic' && ( ({ value: layout, label: t(`journey.studio.layout${layout[0].toUpperCase()}${layout.slice(1)}`), }))} onPick={layout => set({ layout } as Partial)} /> )} set({ units } as Partial)} />
{/* Its label used to be "Elements", which is the name of a panel on the other side of the screen and not what this draws. */} set({ showIcons: !el.showIcons } as Partial)} />
) } function CountriesProps({ el, set, t }: Props) { return (
({ value: look, label: t(`journey.studio.countryLook.${look}`) }))} onPick={look => set({ look } as Partial)} /> {(el.look ?? 'classic') === 'classic' && el.codes.length > 1 && ( ({ value: layout, label: t(`journey.studio.layout${layout[0].toUpperCase()}${layout.slice(1)}`), }))} onPick={layout => set({ layout } as Partial)} /> )} {/* These three read as raw English out of the code before: `left`, `center`, `right`, straight from the value. */} ({ value: align, label: t(`journey.studio.align.${align}`), }))} onPick={align => set({ align } as Partial)} />
set({ showOutline: !el.showOutline } as Partial)} /> set({ showFlag: !el.showFlag } as Partial)} /> set({ showName: !el.showName } as Partial)} />
{/* The names themselves, one per line. They arrive resolved from the journey and are usually right, but "usually" is not a thing you can print: a country whose English name nobody uses, a territory the geocoder names differently from the way the trip talked about it, a line that wants to read "Scotland" rather than "United Kingdom". A textarea rather than a field per country because the list is two names on one page and twenty on another, and lines are how anyone already edits a list. Editing only the names is deliberate: the codes stay as they were, so the outlines and flags keep matching the places actually visited. */} {el.showName && (