feat(journey): complete sharing, photo drafts and Studio maps

Connect the Journey backend to the web and mobile UI, including public access and subscriptions, day recordings, photo drafts and per-map framing. Preserve legacy recording responses and cover the new behavior in every locale.
This commit is contained in:
Maurice
2026-11-30 16:55:22 +01:00
parent 458227f489
commit ede109dce8
90 changed files with 5306 additions and 292 deletions
@@ -0,0 +1,239 @@
import {
MAX_PATH_POINTS,
MAX_PATH_SEGMENTS,
bookMapStopFor,
refreshPatch,
type BookElement,
type BookMapElement,
type BookMapView,
type JourneyStats,
} from '@trek/shared';
import { ArrowDown, ArrowLeft, ArrowRight, ArrowUp, Minus, Plus } from 'lucide-react';
import { useRef, useState, type PointerEvent } from 'react';
import { useTranslation } from '../../i18n';
import { Choice, Line, Section } from './StudioControls';
import { TravelElementView } from './TravelElements';
import { boxToView, currentMapBox, moveBox, zoomBox } from './travel/mapViewEdit';
type T = (key: string, params?: Record<string, string | number>) => string;
type Kind = 'journey' | 'trip' | 'country' | 'day' | 'stop';
interface Parts {
tripId: number | null;
country: string | null;
dayDate: string | null;
stop: BookMapElement['stop'];
}
const NONE: Parts = { tripId: null, country: null, dayDate: null, stop: null };
function kindOf(el: BookMapElement): Kind {
if (el.stop) return 'stop';
if (el.dayDate) return 'day';
if (el.country) return 'country';
return el.tripId != null ? 'trip' : 'journey';
}
/** The days the route passes through, in order. */
function daysOf(stats: JourneyStats): string[] {
return [...new Set(stats.points.map((p) => p.date?.slice(0, 10)).filter((d): d is string => !!d))].sort();
}
/**
* What a map is of (#3024, #3239): the whole journey, one trip, one country,
* one day or one stop. Picking one re-cuts the route on the spot with the
* engine's own refresh, so the map is what a newly placed map of that scope
* would be, and a later refresh keeps it to that scope.
*/
export function MapScopeSection({
el,
set,
t,
stats,
journeyPath,
}: {
el: BookMapElement;
set: (patch: Partial<BookElement>) => void;
t: T;
stats: JourneyStats | null;
journeyPath: [number, number][][];
}) {
const { locale } = useTranslation();
if (!stats || stats.points.length === 0) return null;
const trips = stats.trips.filter((trip) => trip.points > 0);
const days = daysOf(stats);
const stops = stats.points.filter((p) => p.entryId != null);
const kind = kindOf(el);
const apply = (parts: Parts) => {
const whole = parts.tripId == null && !parts.country && !parts.dayDate && !parts.stop;
set({
...refreshPatch({ ...el, ...parts } as BookElement, stats),
...parts,
// The recorded way belongs to the whole journey; the roads went with the old legs.
path: whole ? journeyPath.slice(0, MAX_PATH_SEGMENTS).map((seg) => seg.slice(0, MAX_PATH_POINTS)) : [],
roads: [],
} as Partial<BookElement>);
};
const pickKind = (next: Kind) => {
if (next === kind) return;
if (next === 'journey') apply(NONE);
else if (next === 'trip' && trips[0]) apply({ ...NONE, tripId: trips[0].id });
else if (next === 'country' && stats.countries[0]) apply({ ...NONE, country: stats.countries[0].code });
else if (next === 'day' && days[0]) apply({ ...NONE, dayDate: days[0] });
else if (next === 'stop' && stops[0]?.entryId != null) {
const stop = bookMapStopFor(stats, [], stops[0].entryId);
if (stop) apply({ ...NONE, stop });
}
};
const dayLabel = (day: string) =>
new Date(`${day}T00:00:00`).toLocaleDateString(locale || undefined, { day: 'numeric', month: 'short' });
const kinds: { value: Kind; label: string }[] = [
{ value: 'journey', label: t('journey.studio.mapWholeJourney') },
...(trips.length > 1 ? [{ value: 'trip' as const, label: t('journey.studio.mapScopeTrip') }] : []),
...(stats.countries.length > 0 ? [{ value: 'country' as const, label: t('journey.studio.mapScopeCountry') }] : []),
...(days.length > 0 ? [{ value: 'day' as const, label: t('journey.studio.mapScopeDay') }] : []),
...(stops.length > 0 ? [{ value: 'stop' as const, label: t('journey.studio.mapScopeStop') }] : []),
];
return (
<Section label={t('journey.studio.mapScope')}>
<Choice value={kind} options={kinds} onPick={pickKind} ariaLabel={t('journey.studio.mapScope')} />
{/* The one it is of, when there is more than one to choose from. */}
<div className="mt-2 max-h-[132px] overflow-y-auto">
{kind === 'trip' && trips.length > 1 && (
<Choice
value={el.tripId ?? 0}
options={trips.map((trip) => ({ value: trip.id, label: trip.title || t('journey.studio.untitled') }))}
onPick={(tripId) => apply({ ...NONE, tripId })}
/>
)}
{kind === 'country' && stats.countries.length > 1 && (
<Choice
value={el.country ?? ''}
options={stats.countries.map((c) => ({ value: c.code, label: c.name }))}
onPick={(country) => apply({ ...NONE, country })}
/>
)}
{kind === 'day' && days.length > 1 && (
<Choice
value={el.dayDate ?? ''}
options={days.map((day) => ({ value: day, label: dayLabel(day) }))}
onPick={(dayDate) => apply({ ...NONE, dayDate })}
/>
)}
{kind === 'stop' && stops.length > 1 && (
<Choice
value={el.stop?.entryId ?? 0}
options={stops.map((p) => ({ value: p.entryId ?? 0, label: p.label }))}
onPick={(entryId) => {
const stop = bookMapStopFor(stats, [], entryId);
if (stop) apply({ ...NONE, stop });
}}
/>
)}
</div>
</Section>
);
}
const NUDGE = 0.15;
const ZOOM = 1.4;
function MapDragPreview({ el, onCommit }: { el: BookMapElement; onCommit: (view: BookMapView) => void }) {
const [preview, setPreview] = useState<BookMapView | null>(null);
const drag = useRef<{ x: number; y: number; box: ReturnType<typeof currentMapBox> } | null>(null);
const viewAt = (event: PointerEvent<HTMLDivElement>) => {
const start = drag.current;
const { clientWidth, clientHeight } = event.currentTarget;
if (!start || clientWidth === 0 || clientHeight === 0) return null;
return boxToView(
moveBox(start.box, (start.x - event.clientX) / clientWidth, (start.y - event.clientY) / clientHeight)
);
};
return (
<div
aria-hidden="true"
className="relative mt-2 max-w-56 cursor-grab touch-none overflow-hidden rounded-lg border border-edge active:cursor-grabbing"
style={{ aspectRatio: el.frame.w / el.frame.h }}
onPointerDown={(event) => {
if (event.button !== 0 || !event.isPrimary) return;
event.currentTarget.setPointerCapture(event.pointerId);
drag.current = { x: event.clientX, y: event.clientY, box: currentMapBox(el) };
}}
onPointerMove={(event) => {
if (event.currentTarget.hasPointerCapture(event.pointerId)) setPreview(viewAt(event));
}}
onPointerUp={(event) => {
if (!event.currentTarget.hasPointerCapture(event.pointerId)) return;
const view = viewAt(event);
drag.current = null;
setPreview(null);
if (view) onCommit(view);
}}
onLostPointerCapture={() => {
drag.current = null;
setPreview(null);
}}
>
<TravelElementView
el={{ ...el, id: `${el.id}-framing-preview`, view: preview ?? el.view, source: 'vector' }}
frameStyle={{ width: '100%', height: '100%', pointerEvents: 'none' }}
/>
</div>
);
}
/**
* The window a map shows (#3239): fitted to its route by itself, or framed by
* hand, nudged and zoomed in steps from what it showed. Back to automatic
* forgets the hand-framed view.
*/
export function MapViewLine({ el, set, t }: { el: BookMapElement; set: (patch: Partial<BookElement>) => void; t: T }) {
const own = !!el.view;
const setView = (view: BookMapView) => set({ view } as Partial<BookElement>);
const change = (step: (box: ReturnType<typeof currentMapBox>) => ReturnType<typeof currentMapBox>) =>
setView(boxToView(step(currentMapBox(el))));
const nudges = [
{ label: t('journey.studio.mapViewLeft'), icon: ArrowLeft, run: () => change((b) => moveBox(b, -NUDGE, 0)) },
{ label: t('journey.studio.mapViewUp'), icon: ArrowUp, run: () => change((b) => moveBox(b, 0, -NUDGE)) },
{ label: t('journey.studio.mapViewDown'), icon: ArrowDown, run: () => change((b) => moveBox(b, 0, NUDGE)) },
{ label: t('journey.studio.mapViewRight'), icon: ArrowRight, run: () => change((b) => moveBox(b, NUDGE, 0)) },
{ label: t('journey.studio.zoomOut'), icon: Minus, run: () => change((b) => zoomBox(b, 1 / ZOOM)) },
{ label: t('journey.studio.zoomIn'), icon: Plus, run: () => change((b) => zoomBox(b, ZOOM)) },
];
return (
<>
<Line label={t('journey.studio.mapView')}>
<Choice
value={own ? 'own' : 'auto'}
options={[
{ value: 'auto' as const, label: t('journey.studio.folioAuto') },
{ value: 'own' as const, label: t('journey.studio.mapViewOwn') },
]}
onPick={(v) => {
if (v === 'auto') set({ view: null } as Partial<BookElement>);
else if (!own) change((b) => b);
}}
/>
</Line>
{own && (
<>
<MapDragPreview el={el} onCommit={setView} />
<div className="st-row mt-2">
{nudges.map(({ label, icon: Icon, run }) => (
<button key={label} type="button" className="st-chip" aria-label={label} title={label} onClick={run}>
<Icon size={13} />
</button>
))}
</div>
</>
)}
</>
);
}
@@ -4,7 +4,7 @@ import type {
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,
BOOK_BADGE_STYLES, BOOK_COUNTRY_LOOKS, BOOK_MAP_COAST_DETAILS, BOOK_METRICS, BOOK_STATS_LOOKS, isStale, refreshPatch,
} from '@trek/shared'
import { Swatches } from './StudioSwatches'
import { StudioFontPicker } from './StudioFontPicker'
@@ -17,6 +17,7 @@ import { fetchRoads } from './roadRoute'
import { useStudioStore } from '../../store/studioStore'
import { StudioThemeLink } from './theme/StudioThemeLink'
import { mapZoomInUse, travelTypeInUse } from './inspector/inspectorModel'
import { MapScopeSection, MapViewLine } from './StudioMapScope'
/**
* Properties of the travel elements.
@@ -226,8 +227,6 @@ type MapPropsInput = Props<BookMapElement> & {
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.
@@ -248,45 +247,7 @@ function MapContent({ el, set, t, stats, journeyPath }: MapPropsInput) {
route on the spot rather than at the next refresh, because a control
that changes nothing visible reads as broken.
*/}
{tripsWithRoute.length > 1 && (
<Section label={t('journey.studio.mapScope')}>
<Choice
value={el.tripId ?? 0}
options={[
{ value: 0, label: t('journey.studio.mapWholeJourney') },
...tripsWithRoute.map(trip => ({
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.
*/
// Picking a trip or the whole journey is what the map is of from now on: no country, day or stop left over.
const scope = { tripId, country: null, dayDate: null, stop: null }
set({
...refreshPatch({ ...el, ...scope }, stats),
...scope,
path: tripId == null
? journeyPath.slice(0, MAX_PATH_SEGMENTS).map(seg => seg.slice(0, MAX_PATH_POINTS))
: [],
roads: [],
} as Partial<BookElement>)
}}
/>
</Section>
)}
<MapScopeSection el={el} set={set} t={t} stats={stats} journeyPath={journeyPath} />
{/* Where the picture comes from and what it looks like: one question
with two halves, which is one group rather than two. */}
@@ -350,6 +311,10 @@ function MapContent({ el, set, t, stats, journeyPath }: MapPropsInput) {
two dots in the middle of it.
*/}
<Section label={t('journey.studio.mapFraming')}>
<MapViewLine el={el} set={set} t={t} />
{/* A view framed by hand is the window itself: fit and room only shape the automatic one. */}
{!el.view && (
<>
<Line label={t('journey.studio.mapFit')}>
<Choice
value={el.fitToCountries ? 'country' : 'stops'}
@@ -378,6 +343,8 @@ function MapContent({ el, set, t, stats, journeyPath }: MapPropsInput) {
onPick={fitPadding => set({ fitPadding } as Partial<BookElement>)}
/>
</Line>
</>
)}
{/*
And the shape. A rectangle is a map in a box, which is what a full
@@ -401,8 +368,21 @@ function MapContent({ el, set, t, stats, journeyPath }: MapPropsInput) {
</Line>
</Section>
{el.countries.length > 0 && ((el.source === 'vector' && el.showLand) || el.clip === 'country') && (
<Section label={t('journey.studio.mapCoastDetail')} defaultOpen={false}>
<Choice
value={el.coastDetail ?? 'auto'}
options={BOOK_MAP_COAST_DETAILS.map(value => ({
value,
label: t(`journey.studio.mapCoastDetail.${value}`),
}))}
onPick={coastDetail => set({ coastDetail } as Partial<BookElement>)}
/>
</Section>
)}
{el.source === 'tiles' && (
<Section label={t('journey.studio.mapZoom')} defaultOpen={mapZoomInUse(el)}>
<Section label={t('journey.studio.tileDetail')} defaultOpen={mapZoomInUse(el)}>
<Choice
value={el.zoom ?? -1}
options={[
@@ -17,7 +17,7 @@ interface MapXY {
y: number;
}
/** A box in projected world units: longitude as x, Mercator y growing southwards. */
interface MapBox {
export interface MapBox {
minX: number;
minY: number;
maxX: number;
@@ -0,0 +1,45 @@
import { bookMapElementSchema, bookMapViewSchema } from '@trek/shared';
import { describe, expect, it } from 'vitest';
import { boxToView, currentMapBox, moveBox, zoomBox } from './mapViewEdit';
const frame = { x: 0, y: 0, w: 100, h: 50 };
describe('editing the visible Studio map window', () => {
it('starts from the automatic framing of the current route', () => {
const el = bookMapElementSchema.parse({
id: 'map',
kind: 'map',
frame,
points: [
{ lat: 52.51, lng: 13.38 },
{ lat: 52.49, lng: 13.42 },
],
});
const fitted = boxToView(currentMapBox(el));
expect(fitted.west).toBeLessThan(13.38);
expect(fitted.east).toBeGreaterThan(13.42);
expect(fitted.south).toBeLessThan(52.49);
expect(fitted.north).toBeGreaterThan(52.51);
});
it('pans a manual view across the antimeridian and zooms it around the same centre', () => {
const view = { west: 175, east: 181, south: -19, north: -16 };
const el = bookMapElementSchema.parse({ id: 'map', kind: 'map', frame, view });
const start = currentMapBox(el);
const moved = moveBox(start, 0.5, 0);
const closer = boxToView(zoomBox(moved, 2));
expect(closer.west).toBeCloseTo(179.5);
expect(closer.east).toBeCloseTo(182.5);
expect(closer.north).toBeLessThan(view.north);
expect(closer.south).toBeGreaterThan(view.south);
});
it('keeps an extreme drag or zoom within a valid stored world window', () => {
const view = boxToView({ minX: 2000, maxX: 3000, minY: -900, maxY: 900 });
expect(bookMapViewSchema.safeParse(view).success).toBe(true);
expect(view.east - view.west).toBeLessThanOrEqual(360);
expect(view.east).toBeLessThanOrEqual(540);
});
});
@@ -0,0 +1,71 @@
import { MAX_BOOK_VIEW_LNG, type BookMapElement, type BookMapView } from '@trek/shared';
import { countryDetailShapes } from '../countryDetail';
import { COUNTRY_SHAPES, projectMercator, unprojectMercator } from '../countryShapes';
import { fitMapWindow, mapBows, mapWantsDetail, projectMapRoute, viewBox, type MapBox } from './mapFit';
/*
* A map framed by hand (#3239): the window it shows as a projected box, moved
* and zoomed in the inspector and stored as a view in degrees. Pure, so the
* inspector only draws what these answer.
*/
const MIN_SPAN = 0.002;
const MAX_LAT = 85;
/** What the map shows by itself, fitted to its route: the box a hand-framed view starts from. */
function autoMapBox(el: BookMapElement): MapBox {
const plain = { ...el, view: null };
const route = projectMapRoute(plain);
const drawLand = (el.source === 'vector' && el.showLand) || el.clip === 'country';
const detail = countryDetailShapes(mapWantsDetail(plain, route) ? el.countries : []);
const shapes = drawLand
? el.countries.map((code) => detail.get(code.toUpperCase()) ?? COUNTRY_SHAPES[code.toUpperCase()]).filter(Boolean)
: [];
const win = fitMapWindow({
el: plain,
route,
bows: mapBows(plain, route),
shapes,
cutToLand: el.clip === 'country' && shapes.length > 0,
w: el.frame.w,
h: el.frame.h,
});
return { minX: win.minX, minY: win.minY, maxX: win.maxX, maxY: win.maxY };
}
/** The box a map shows now: its own view, or the fitted one. */
export function currentMapBox(el: BookMapElement): MapBox {
return el.view ? viewBox(el.view) : autoMapBox(el);
}
const clamp = (v: number, lo: number, hi: number) => Math.min(hi, Math.max(lo, v));
/** A projected box as a view the schema takes: west to east at most once round, inside the poles. */
export function boxToView(box: MapBox): BookMapView {
const top = projectMercator(0, MAX_LAT).y;
const bottom = projectMercator(0, -MAX_LAT).y;
const minY = clamp(box.minY, top, bottom - MIN_SPAN);
const maxY = clamp(box.maxY, minY + MIN_SPAN, bottom);
const span = clamp(box.maxX - box.minX, MIN_SPAN, 360);
const west = clamp((box.minX + box.maxX - span) / 2, -180, MAX_BOOK_VIEW_LNG - span);
const east = Math.min(west + span, MAX_BOOK_VIEW_LNG);
const nw = unprojectMercator(west, minY);
const se = unprojectMercator(east, maxY);
return { west: nw.lng, north: nw.lat, east: se.lng, south: se.lat };
}
/** The same box seen closer (factor above 1) or from further away, around its middle. */
export function zoomBox(box: MapBox, factor: number): MapBox {
const cx = (box.minX + box.maxX) / 2;
const cy = (box.minY + box.maxY) / 2;
const hw = Math.max((box.maxX - box.minX) / 2 / factor, MIN_SPAN);
const hh = Math.max((box.maxY - box.minY) / 2 / factor, MIN_SPAN);
return { minX: cx - hw, maxX: cx + hw, minY: cy - hh, maxY: cy + hh };
}
/** The box moved by a share of its own width and height. */
export function moveBox(box: MapBox, dx: number, dy: number): MapBox {
const w = box.maxX - box.minX;
const h = box.maxY - box.minY;
return { minX: box.minX + dx * w, maxX: box.maxX + dx * w, minY: box.minY + dy * h, maxY: box.maxY + dy * h };
}