feat(studio): maps framed by hand, across the antimeridian, with the small islands

The vector map draws a hand-framed view as given, widened to the frame's
proportions as the fit always was, and the tile grid takes the same
extent. A view east of 180 lifts the stops, tracks, roads and outlines
west of it by a turn, so Fiji is one map rather than two halves of the
world. The fit, the bows and the route's extent move to travel/mapFit.ts,
which takes TravelElements.tsx from 1559 to 1332 lines.

Hawaii and other small islands vanished because the bundled outlines
drop every ring below 1.2 % of the mainland (#3056). A finer set, built
from the same admin-0 boundaries by scripts/build-country-detail.mjs, is
served as one static file per country under country-detail/ and loaded
when a map's route (or its own view) is regional, or when coastDetail
asks for it; the coarse outline stays the fallback offline and until a
file arrives. The decision reads the route, not the fitted window, since
fitted to its countries a Hawaii trip falls back to the whole United
States. The export waits for the files before the sheets render, the
trip PDF's outline map loads them for a regional route, and the service
worker keeps them once fetched without precaching them.
This commit is contained in:
Maurice
2026-11-30 14:40:05 +01:00
parent 83f3fee848
commit 5990792e0b
217 changed files with 1560 additions and 324 deletions
+19 -3
View File
@@ -5,6 +5,7 @@ import type { BookDocument } from '@trek/shared'
import { BookSheetsView } from './BookSheetsView'
import { sheetBox, sheetsFor, type SheetMode } from './bookSheets'
import { printSheets } from './printSheets'
import { mapDetailPending, mapDetailReady } from './printReady'
/**
* Getting the book out.
@@ -52,8 +53,23 @@ export function StudioExport({
const box = sheetBox(widest, doc.page.pageHeight, doc.page.bleed, marks)
const single = sheetBox(doc.page.pageWidth, doc.page.pageHeight, doc.page.bleed, marks)
/*
* The finer coastlines the maps draw are fetched first (printReady.ts), so
* the sheets render with them and the markup taken from them has them. Kept
* per book, so a second export of the same book does not wait again.
*/
const [readyFor, setReadyFor] = useState<BookDocument | null>(null)
// Ready at once for a book whose maps want nothing still out, which is most books and every second export.
const mapsReady = readyFor === doc || (building && !mapDetailPending(doc))
useEffect(() => {
if (!building) return
if (!building || mapsReady) return
let live = true
void mapDetailReady(doc).then(() => { if (live) setReadyFor(doc) })
return () => { live = false }
}, [building, doc, mapsReady])
useEffect(() => {
if (!building || !mapsReady) return
const html = stage.current?.innerHTML
if (!html) return
@@ -76,7 +92,7 @@ export function StudioExport({
// Runs once per build. Re-running on every render of the options would
// open a second print view behind the first.
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [building])
}, [building, mapsReady])
// Studio closes itself on Escape. While this dialog is open the key is its own,
// so it is taken in the capture phase before the editor's handler sees it.
@@ -144,7 +160,7 @@ export function StudioExport({
dialog itself is portalled over it. `aria-hidden` keeps them out of the
reading order.
*/}
{building && (
{building && mapsReady && (
<div
ref={stage}
aria-hidden="true"
@@ -1,8 +1,10 @@
import { render } from '@testing-library/react'
import { render, waitFor } from '@testing-library/react'
import { http, HttpResponse } from 'msw'
import { describe, expect, it } from 'vitest'
import { bookMapElementSchema } from '@trek/shared'
import { server } from '../../../tests/helpers/msw/server'
import { TravelElementView } from './TravelElements'
import { COUNTRY_SHAPES, countryParts } from './countryShapes'
import { COUNTRY_SHAPES, countryParts, countryWorldPath } from './countryShapes'
/*
* The maps are measured, not snapshotted: what went wrong in #2021 is a number
@@ -114,3 +116,67 @@ describe('countryParts', () => {
expect(parts[0][2]).toBeCloseTo(COUNTRY_SHAPES.CH.b[2], 1)
})
})
/** Every stop's position on the frame, in millimetres. */
function pins(over: Record<string, unknown>): { x: number; y: number }[] {
const { container } = render(
<TravelElementView el={mapEl(over)} frameStyle={{ width: '100mm', height: '100mm' }} />,
)
return [...container.querySelectorAll('circle')].map(c => ({
x: Number(c.getAttribute('cx')),
y: Number(c.getAttribute('cy')),
}))
}
describe('MapView framed by hand (#3239)', () => {
it('shows the view it was given rather than fitting the route', () => {
const fitted = pinSpan({ countries: ['FR'], points: [PARIS, LYON], fitToCountries: false })
const framed = pinSpan({
countries: ['FR'],
points: [PARIS, LYON],
fitToCountries: false,
view: { west: -8, south: 40, east: 14, north: 53 },
})
// The whole of France around two stops: they sit far closer than on a map fitted to them.
expect(framed).toBeLessThan(fitted / 2)
expect(framed).toBeGreaterThan(5)
})
it('keeps a stop out of view out of the frame, where the view leaves it', () => {
const at = pins({ points: [PARIS, NICE], view: { west: 1, south: 47.5, east: 4, north: 50 } })
const paris = at[0]
const nice = at[1]
expect(paris.x).toBeGreaterThan(0)
expect(paris.x).toBeLessThan(100)
expect(nice.y).toBeGreaterThan(100)
})
it('draws two islands either side of the antimeridian next to each other', () => {
const at = pins({
points: [{ lat: -18.14, lng: 178.44 }, { lat: -16.85, lng: -179.97 }],
view: { west: 176, south: -20, east: 182, north: -15 },
})
expect(Math.abs(at[1].x - at[0].x)).toBeLessThan(40)
for (const p of at) {
expect(p.x).toBeGreaterThan(0)
expect(p.x).toBeLessThan(100)
}
})
})
describe('MapView finer coastline (#3056)', () => {
it('draws the finer outline once it is in, and the coarse one until then', async () => {
const detail = { d: 'M0 0L50 0L50 50L0 50Z', w: 100, h: 100, b: [-160, -23, -154, -17] as [number, number, number, number] }
server.use(http.get('/country-detail/US.json', () => HttpResponse.json(detail)))
const { container } = render(
<TravelElementView
el={mapEl({ countries: ['US'], points: [{ lat: 21.31, lng: -157.86 }, { lat: 19.72, lng: -155.09 }] })}
frameStyle={{ width: '100mm', height: '100mm' }}
/>,
)
const land = () => [...container.querySelectorAll('path[d]')].map(p => p.getAttribute('d'))
expect(land()).toContain(countryWorldPath(COUNTRY_SHAPES.US))
await waitFor(() => expect(land()).toContain(countryWorldPath(detail)))
expect(land()).not.toContain(countryWorldPath(COUNTRY_SHAPES.US))
})
})
+39 -268
View File
@@ -12,9 +12,10 @@ import { badgeIconShare, badgeInk, inkOn, isBadgeLook } from './travel/badgeLook
import { BadgeIcon } from './travel/BadgeIcon'
import { EndMarker } from './travel/EndMarker'
import { FlagMark } from './travel/FlagMark'
import { haversineKm } from '../../utils/geo'
import { COUNTRY_SHAPES, countryParts, countryWorldPath, projectMercator, unprojectMercator } from './countryShapes'
import { COUNTRY_SHAPES, countryWorldPath, unprojectMercator } from './countryShapes'
import { useCountryDetail } from './countryDetail'
import { projectOntoTiles, tileView, usableStaticUrl } from './mapTiles'
import { fitMapWindow, landOffsets, mapBows, mapWantsDetail, projectMapRoute } from './travel/mapFit'
import { useCartoApiKey } from '../../hooks/useTileUrl'
import { useTranslation } from '../../i18n'
@@ -197,266 +198,39 @@ function MapView({ el, frameStyle, big = false }: {
* whenever either job wants it, and drawn only for the first.
*/
const wantsStencil = el.clip === 'country'
/*
* The route first, projected the way everything on this map is: across the
* antimeridian when the map was framed across it. Segments of the travelled
* way stay separate: two tracks that do not join must not be drawn as though
* they did, or a trip with a flight in it shows a road across the sea.
*/
const routed = projectMapRoute(el)
const { points, trail, project, shift } = routed
const path = el.path ?? []
const roads = el.roads ?? []
/*
* The finer outlines where the route is regional or lies off the coarse ones
* (Hawaii, the small islands; mapFit.ts says why the route decides), the
* coarse ones until they are in and wherever they are not.
*/
const detail = useCountryDetail(mapWantsDetail(el, routed) ? el.countries : [])
const shapes = (el.showLand && !imagery) || wantsStencil
? el.countries.map(c => COUNTRY_SHAPES[c.toUpperCase()]).filter(Boolean)
? el.countries.map(c => detail.get(c.toUpperCase()) ?? COUNTRY_SHAPES[c.toUpperCase()]).filter(Boolean)
: []
const drawLand = el.showLand && !imagery
const points = el.points.map(p => ({ ...p, ...projectMercator(p.lng, p.lat) }))
/*
* The travelled way, projected the same as everything else.
*
* Segments stay separate: two tracks that do not join must not be drawn as
* though they did, or a book about a trip with a flight in the middle of it
* shows a road across the sea.
*/
/*
* Defended rather than assumed, unlike the rest of the element's fields.
*
* A document that came through the contract always has this. One built by
* hand somewhere in the editor might not, and the cost of being wrong is not
* a missing line: reading `.map` off undefined here takes the whole spread
* down with it, in a renderer that also has to run for print.
*/
const path = el.path ?? []
/*
* The roads, one per leg, `null` where a leg has none. Read the same
* defensive way `path` is: an element built by hand and cast rather than
* parsed genuinely has the field missing, and `.length` on undefined takes
* the whole spread down in a renderer that also has to run for print.
*/
const roads = el.roads ?? []
const trail = path.map(seg => seg.map(([lat, lng]) => projectMercator(lng, lat)))
/*
* ── What the view is fitted to ────────────────────────────────────────
*
* The journey, not the geography. Fitting to the country outlines meant a
* trip that stayed inside Berlin was drawn as the whole of Germany with two
* dots in the middle of it: technically a map of where you were, useless as
* a page about the trip. The outlines are still drawn, they simply run off
* the edge of the frame the way a coastline does on any real map.
*
* `fitToCountries` asks for the other behaviour deliberately, for the page
* every travel book has: the country entire, with the route inside it.
*/
let minX = Infinity, minY = Infinity, maxX = -Infinity, maxY = -Infinity
/*
* Cutting to the coastline only means anything if the coastline is in view,
* so `clip` implies the country fit however the element was configured.
*/
const cutToLand = el.clip === 'country' && shapes.length > 0
const fitToLand = el.fitToCountries || cutToLand || (points.length === 0 && trail.length === 0)
for (const p of points) {
minX = Math.min(minX, p.x); minY = Math.min(minY, p.y)
maxX = Math.max(maxX, p.x); maxY = Math.max(maxY, p.y)
}
for (const seg of trail) {
for (const p of seg) {
minX = Math.min(minX, p.x); minY = Math.min(minY, p.y)
maxX = Math.max(maxX, p.x); maxY = Math.max(maxY, p.y)
}
}
/*
* A road wanders well outside the box around the two stops it joins — that is
* the whole point of drawing it. Fitted to the stops alone, the interesting
* part of it would be outside the frame.
*/
for (const road of roads) {
if (!road) continue
for (const [lat, lng] of road) {
const q = projectMercator(lng, lat)
minX = Math.min(minX, q.x); minY = Math.min(minY, q.y)
maxX = Math.max(maxX, q.x); maxY = Math.max(maxY, q.y)
}
}
/*
* The country fit comes last, because it needs to know where the journey is.
*
* A country is one path but not one landmass. France's is five rings, three
* of them Kerguelen, French Guiana and New Caledonia, so unioning its whole
* bounding box fitted a Paris-Lyon-Nice route to 221 degrees of longitude and
* printed the three stops as a single dot. Britain does the same through
* South Georgia, Norway through Svalbard, Ecuador through the Galapagos.
*
* So only the rings the journey is near are fitted to. The margin is the
* route's own size, floored at two degrees, and that floor is the whole of
* the judgement: at two degrees a Paris-Nice route still pulls in Corsica,
* which is the picture that trip wants, while Kerguelen at 68 degrees east
* stays out. Raise it far and the territories come back; drop it to zero and
* a coastal route sitting just off a simplified coastline stops matching the
* country it is in.
*
* The whole shape is still the fallback — with no route there is nothing to
* measure against, and a country none of whose rings match is better drawn
* whole than not at all. The outlines themselves are unchanged either way:
* the overseas rings are still painted, they just run off the frame the way
* a coastline does.
*/
if (fitToLand) {
const routed = Number.isFinite(minX)
const margin = Math.max(maxX - minX, maxY - minY, 2)
const nearX0 = minX - margin, nearY0 = minY - margin
const nearX1 = maxX + margin, nearY1 = maxY + margin
for (const s of shapes) {
const near = routed
? countryParts(s).filter(p => p[0] <= nearX1 && p[2] >= nearX0 && p[1] <= nearY1 && p[3] >= nearY0)
: []
for (const b of near.length > 0 ? near : [s.b]) {
minX = Math.min(minX, b[0]); minY = Math.min(minY, b[1])
maxX = Math.max(maxX, b[2]); maxY = Math.max(maxY, b[3])
}
}
}
/*
* ── The bow ───────────────────────────────────────────────────────────
*
* A straight line between two stops a continent apart is a claim about the
* journey that is plainly false, and a shallow curve is how printed maps have
* always said "this part was a flight". Two gates decide how much:
*
* **How far it was, in kilometres.** A fact about the journey rather than
* about the zoom, so two cafes four kilometres apart stay straight at every
* size and Tokyo to Los Angeles bows at every size. Ramped smoothly from
* 150km to 15000km rather than switched at a threshold, or a route would have
* one leg visibly curved and its neighbour dead straight.
*
* **Which way it runs.** A meridian is a great circle *and* a straight line
* in Mercator, so bowing a due north-south leg draws a detour that never
* happened. The east-west share of the leg damps it.
*
* The direction is poleward from the route's MEAN latitude, decided once for
* the element: per leg, a chain crossing the equator would flip sides halfway
* along and read as random rather than as drawn.
*/
const bowed = el.routeArc === 'bow' && trail.length === 0 && points.length > 1
const meanLat = el.points.length
? el.points.reduce((sum, p) => sum + p.lat, 0) / el.points.length
: 0
/**
* How far each leg bows, as a share of its own chord, and which way.
*
* A fraction rather than a distance, so the same numbers are right on a 40mm
* inset and a 400mm spread — what the eye reads is the angle the line leaves
* its marker at, and that is scale free.
*/
const bows: { k: number; nx: number; ny: number }[] = bowed
? el.points.slice(0, -1).map((a, i) => {
const b = el.points[i + 1]
const pa = projectMercator(a.lng, a.lat)
const pb = projectMercator(b.lng, b.lat)
const dx = pb.x - pa.x
const dy = pb.y - pa.y
const d = Math.hypot(dx, dy)
if (d < 1e-6) return { k: 0, nx: 0, ny: 0 }
const u = Math.min(1, Math.max(0, Math.log(haversineKm(a, b) / 150) / Math.log(10)))
const ramp = u * u * (3 - 2 * u)
// How much of the leg runs east-west, which is where a bow is truthful.
const eastWest = 0.35 + 0.65 * Math.abs(dx / d)
// The normal, turned to point away from the equator side the route is on.
let nx = -dy / d
let ny = dx / d
const poleward = meanLat >= 0 ? -1 : 1
if (Math.abs(ny) < 1e-9) {
// A due north-south leg has no poleward side; break the tie east.
nx = Math.abs(nx)
} else if (Math.sign(ny) !== poleward) {
nx = -nx
ny = -ny
}
return { k: 0.07 * ramp * eastWest, nx, ny }
})
: []
/*
* The apexes join the extent before it is fitted. Without this the tile
* window and the vector fit are both cut to the straight chords, and a bowed
* leg is clipped by the very frame it was fitted to.
*/
bows.forEach((bow, i) => {
if (!bow.k) return
const a = points[i]
const b = points[i + 1]
const d = Math.hypot(b.x - a.x, b.y - a.y)
const ax = (a.x + b.x) / 2 + bow.k * d * bow.nx
const ay = (a.y + b.y) / 2 + bow.k * d * bow.ny
minX = Math.min(minX, ax); maxX = Math.max(maxX, ax)
minY = Math.min(minY, ay); maxY = Math.max(maxY, ay)
})
const empty = !Number.isFinite(minX)
if (empty) { minX = -1; minY = -1; maxX = 1; maxY = 1 }
/*
* One stop is a place, not an extent.
*
* The window around it used to be two whole degrees, which put a single
* hotel on a map of half a country. A hundredth of the projected world is
* roughly a large city and its surroundings: near enough to see where it is,
* close enough that the pin means something.
*/
const SINGLE = 0.01
if (maxX - minX < SINGLE) { const c = (minX + maxX) / 2; minX = c - SINGLE / 2; maxX = c + SINGLE / 2 }
if (maxY - minY < SINGLE) { const c = (minY + maxY) / 2; minY = c - SINGLE / 2; maxY = c + SINGLE / 2 }
const bows = mapBows(el, routed)
const W = el.frame.w
const H = el.frame.h
/*
* Room around the route, as a share of the route rather than of the frame.
*
* A fixed margin in millimetres is the wrong shape twice over: on a wide
* route it is a hairline, and on a short one it is most of the picture. A
* share of the extent keeps the same amount of air around a walk across a
* city and a drive across a continent.
*/
// Same defence as `path`: undefined would make this NaN, and a NaN here
// propagates into every coordinate on the map rather than failing loudly.
const grow = Math.max(0, el.fitPadding ?? 0.18)
const spanX = (maxX - minX) * (1 + grow)
const spanY = (maxY - minY) * (1 + grow)
const cx = (minX + maxX) / 2
const cy = (minY + maxY) / 2
minX = cx - spanX / 2; maxX = cx + spanX / 2
minY = cy - spanY / 2; maxY = cy + spanY / 2
/*
* ── The window takes the frame's proportions ─────────────────────────
*
* Two fits used to disagree about what the map was of. The outlines and the
* route were *contained* in the frame — fitted whole, with air on the long
* side — while the imagery *covered* it, because a map with a strip of paper
* down one edge is not a map. On a frame whose shape did not match the
* route's, those are different windows, and the tiles won: the picture filled
* the box and the route ran off the top of it. Drag a map narrow enough and
* the line simply left the page.
*
* Widening the window to the frame's own proportions makes the two the same
* window. Cover and contain agree by construction, the route is inside
* whatever shape the element is dragged to, and the imagery still reaches
* every edge — it just shows a little more ground on the short side, which is
* what the extra room was always going to be filled with.
*/
const aspect = W / H
const haveW = maxX - minX
const haveH = maxY - minY
if (haveW / haveH < aspect) {
const want = haveH * aspect
minX = cx - want / 2
maxX = cx + want / 2
} else {
const want = haveW / aspect
minY = cy - want / 2
maxY = cy + want / 2
}
const scale = Math.min(W / (maxX - minX), H / (maxY - minY))
const offX = (W - (maxX - minX) * scale) / 2 - minX * scale
const offY = (H - (maxY - minY) * scale) / 2 - minY * scale
// The window, fitted to the route (and its countries) or framed by hand (travel/mapFit.ts).
const { minX, minY, maxX, maxY, scale, offX, offY } = fitMapWindow({ el, route: routed, bows, shapes, cutToLand, w: W, h: H })
const at = (x: number, y: number) => ({ x: x * scale + offX, y: y * scale + offY })
// The outlines once more a turn east (and west) where the view runs across the antimeridian.
const land = landOffsets(el.view).flatMap(dx => shapes.map(shape => ({ shape, dx })))
const stroke = Math.max(0.12, Math.min(W, H) * 0.006)
/*
@@ -570,9 +344,12 @@ function MapView({ el, frameStyle, big = false }: {
* zoom level. Using the wrong one puts the line next to the road rather than
* on it, which is the sort of error that only shows up once it is printed.
*/
const route = tiled
? el.points.map(p => projectOntoTiles(tiled, p.lng, p.lat))
: points.map(p => at(p.x, p.y))
const onScreen = (lng: number, lat: number) => {
if (tiled) return projectOntoTiles(tiled, shift(lng), lat)
const q = project(lng, lat)
return at(q.x, q.y)
}
const route = el.points.map(p => onScreen(p.lng, p.lat))
/*
* The drawn line, which is the travelled way when there is one.
@@ -583,7 +360,7 @@ function MapView({ el, frameStyle, big = false }: {
* something that did not happen.
*/
const trailOnScreen = tiled
? path.map(seg => seg.map(([lat, lng]) => projectOntoTiles(tiled, lng, lat)))
? path.map(seg => seg.map(([lat, lng]) => onScreen(lng, lat)))
: trail.map(seg => seg.map(p => at(p.x, p.y)))
/*
* ── What the plain line is made of ────────────────────────────────────
@@ -597,10 +374,7 @@ function MapView({ el, frameStyle, big = false }: {
const roadOnScreen = (leg: number) => {
const road = roads[leg]
if (!road || road.length < 2) return null
return road.map(([lat, lng]) => {
const q = projectMercator(lng, lat)
return tiled ? projectOntoTiles(tiled, lng, lat) : at(q.x, q.y)
})
return road.map(([lat, lng]) => onScreen(lng, lat))
}
const chain: { x: number; y: number }[][] = []
@@ -661,11 +435,8 @@ function MapView({ el, frameStyle, big = false }: {
const road = roads[i]
if (road && road.length > 1) {
flush()
const onScreen = road.map(([lat, lng]) => {
const q = projectMercator(lng, lat)
return tiled ? projectOntoTiles(tiled, lng, lat) : at(q.x, q.y)
})
strands.push({ d: `M${onScreen.map(pt => `${round2(pt.x)} ${round2(pt.y)}`).join(' L')}` })
const drawnRoad = road.map(([lat, lng]) => onScreen(lng, lat))
strands.push({ d: `M${drawnRoad.map(pt => `${round2(pt.x)} ${round2(pt.y)}`).join(' L')}` })
continue
}
@@ -846,8 +617,8 @@ function MapView({ el, frameStyle, big = false }: {
{cutToLand && (
<defs>
<clipPath id={clipId} clipPathUnits="userSpaceOnUse">
{shapes.map((sh, i) => (
<path key={i} d={countryWorldPath(sh)} transform={`translate(${offX} ${offY}) scale(${scale})`} />
{land.map(({ shape: sh, dx }, i) => (
<path key={i} d={countryWorldPath(sh)} transform={`translate(${offX + dx * scale} ${offY}) scale(${scale})`} />
))}
</clipPath>
</defs>
@@ -882,14 +653,14 @@ function MapView({ el, frameStyle, big = false }: {
</g>
)}
{(drawLand || cutToLand) && shapes.map((s, i) => (
{(drawLand || cutToLand) && land.map(({ shape: s, dx }, i) => (
<path
key={i}
d={countryWorldPath(s)}
// The path is in projected world units, so the transform does the
// fitting and the stroke is divided back out — the border stays the
// width it was asked for instead of scaling with the map.
transform={`translate(${offX} ${offY}) scale(${scale})`}
transform={`translate(${offX + dx * scale} ${offY}) scale(${scale})`}
// On a cut map the picture is the fill, and this path is only the
// edge around it — filling it as well would paint the land flat
// over the very imagery it was cut to show.
@@ -0,0 +1,112 @@
/**
* FE-STUDIO-DETAIL-001 to FE-STUDIO-DETAIL-005
*
* The finer country outlines (#3056): read only when they are a shape, loaded
* once per country, never failing a map that has to fall back to the coarse
* outline, and never holding the print view past its ceiling.
*
* The loaded outlines are kept for the page's life, so every test here asks
* for countries no other test in the file loads.
*/
import { renderHook, waitFor } from '@testing-library/react';
import { http, HttpResponse } from 'msw';
import { afterEach, describe, expect, it, vi } from 'vitest';
import { server } from '../../../tests/helpers/msw/server';
import {
countryDetailSettled,
countryDetailShapes,
preloadCountryDetail,
readCountryDetail,
useCountryDetail,
} from './countryDetail';
const SHAPE = { d: 'M0 0L10 0L10 10Z', w: 100, h: 80, b: [-160, -23, -154, -18] };
/** Answers the files of these countries with a shape, and counts the requests. */
function serve(codes: string[], answer: (code: string) => Response = () => HttpResponse.json(SHAPE)) {
const asked: string[] = [];
server.use(
http.get('/country-detail/:file', ({ params }) => {
const code = String(params.file).replace('.json', '');
asked.push(code);
return codes.includes(code) ? answer(code) : new HttpResponse(null, { status: 404 });
})
);
return asked;
}
afterEach(() => {
vi.useRealTimers();
});
describe('a file', () => {
it('FE-STUDIO-DETAIL-001: reads as a shape only when it is one', () => {
expect(readCountryDetail(SHAPE)).toEqual(SHAPE);
expect(readCountryDetail(null)).toBeNull();
expect(readCountryDetail('M0 0')).toBeNull();
expect(readCountryDetail({ ...SHAPE, d: '<svg/>' })).toBeNull();
expect(readCountryDetail({ ...SHAPE, w: '100' })).toBeNull();
expect(readCountryDetail({ ...SHAPE, b: [1, 2, 3] })).toBeNull();
expect(readCountryDetail({ ...SHAPE, b: [1, 2, 3, Number.NaN] })).toBeNull();
expect(readCountryDetail({ ...SHAPE, b: 'box' })).toBeNull();
});
});
describe('loading', () => {
it('FE-STUDIO-DETAIL-002: loads each country once, and only the countries the coarse set knows', async () => {
const asked = serve(['FJ']);
expect(countryDetailSettled('FJ')).toBe(false);
await Promise.all([preloadCountryDetail(['fj', 'FJ']), preloadCountryDetail(['FJ', 'XX', '1A', 'toolong'])]);
expect(asked).toEqual(['FJ']);
expect(countryDetailShapes(['FJ', 'XX']).get('FJ')).toEqual(SHAPE);
expect(countryDetailShapes(['FJ', 'XX']).has('XX')).toBe(false);
expect(countryDetailSettled('fj')).toBe(true);
// A code without a file of its own is never waited for.
expect(countryDetailSettled('XX')).toBe(true);
await preloadCountryDetail(['FJ']);
expect(asked).toEqual(['FJ']);
});
it('FE-STUDIO-DETAIL-003: settles without a shape when a file is missing or is not one, and the map stays coarse', async () => {
serve(['TO'], () => HttpResponse.json({ not: 'a shape' }));
await preloadCountryDetail(['TO', 'WS']);
expect(countryDetailSettled('TO')).toBe(true);
expect(countryDetailSettled('WS')).toBe(true);
expect(countryDetailShapes(['TO', 'WS']).size).toBe(0);
});
it('FE-STUDIO-DETAIL-004: stops waiting at the ceiling, while the file may still come', async () => {
let release: () => void = () => undefined;
const held = new Promise<void>((resolve) => {
release = resolve;
});
server.use(
http.get('/country-detail/VU.json', async () => {
await held;
return HttpResponse.json(SHAPE);
})
);
const started = Date.now();
await preloadCountryDetail(['VU'], 30);
expect(Date.now() - started).toBeLessThan(5000);
expect(countryDetailSettled('VU')).toBe(false);
release();
await waitFor(() => expect(countryDetailSettled('VU')).toBe(true));
expect(countryDetailShapes(['VU']).get('VU')).toEqual(SHAPE);
});
});
describe('useCountryDetail', () => {
it('FE-STUDIO-DETAIL-005: hands a map the finer outlines as they arrive, and asks for nothing when given none', async () => {
const asked = serve(['SB']);
const { result, rerender } = renderHook(({ codes }) => useCountryDetail(codes), {
initialProps: { codes: [] as string[] },
});
expect(result.current.size).toBe(0);
expect(asked).toEqual([]);
rerender({ codes: ['SB'] });
await waitFor(() => expect(result.current.get('SB')).toEqual(SHAPE));
expect(asked).toEqual(['SB']);
});
});
@@ -0,0 +1,142 @@
import { useEffect, useSyncExternalStore } from 'react';
import { COUNTRY_SHAPES, type CountryShape } from './countryShapes';
/**
* The finer country outlines, loaded when a map needs them (#3056).
*
* `countryShapes.ts` is the coarse set every map draws from the bundle: cut
* for a whole country at stamp size, it leaves out islands below a share of
* their mainland, Hawaii among them. The finer set lives beside the app as one
* static file per country (`public/country-detail/`, built by
* scripts/build-country-detail.mjs) and is fetched here, once per country per
* page load, by the maps whose route is small enough to show what it adds.
*
* Until a file is in, and whenever it cannot be fetched (offline, a proxy that
* does not serve it, a test), the coarse shape is drawn: a map is never empty
* for want of the finer one. The print view waits for them first
* (`mapDetailReady` in printReady.ts), so a printed page has the islands the
* editor showed.
*
* What is loaded is kept for the page's life. It is a cache of files that do
* not change while the app runs, read by every map at once, so it sits here
* rather than in each map's state.
*/
/** How long one file may take before the coarse outline stands in for good. */
const LOAD_TIMEOUT_MS = 10_000;
/** A country's finer shape, or null where there is none or it would not load. */
const loaded = new Map<string, CountryShape | null>();
const inFlight = new Map<string, Promise<void>>();
const listeners = new Set<() => void>();
let version = 0;
const notify = () => {
version += 1;
for (const listener of listeners) listener();
};
/** Only the countries the coarse set knows have a file; anything else is not fetched at all. */
const codeOf = (code: string): string | null => {
const upper = code.toUpperCase();
return /^[A-Z]{2}$/.test(upper) && COUNTRY_SHAPES[upper] ? upper : null;
};
const isNumber = (v: unknown): v is number => typeof v === 'number' && Number.isFinite(v);
/** The file's contents as a shape, or null for anything that is not one. */
export function readCountryDetail(raw: unknown): CountryShape | null {
if (!raw || typeof raw !== 'object') return null;
const { d, w, h, b } = raw as Record<string, unknown>;
if (typeof d !== 'string' || !d.startsWith('M') || !isNumber(w) || !isNumber(h)) return null;
const box: unknown[] = Array.isArray(b) ? b : [];
if (box.length !== 4 || !box.every(isNumber)) return null;
return { d, w, h, b: [box[0], box[1], box[2], box[3]] };
}
async function fetchDetail(code: string): Promise<CountryShape | null> {
try {
const res = await fetch(`/country-detail/${code}.json`, { signal: AbortSignal.timeout(LOAD_TIMEOUT_MS) });
if (!res.ok) return null;
return readCountryDetail(await res.json());
} catch {
// Offline, timed out or not served: the coarse outline is the answer, and it is already drawn.
return null;
}
}
/** Load one country's finer outline; resolves once it is in or known to be missing, never rejects. */
function loadOne(code: string): Promise<void> {
if (loaded.has(code)) return Promise.resolve();
const running = inFlight.get(code);
if (running) return running;
const load = fetchDetail(code).then((shape) => {
loaded.set(code, shape);
inFlight.delete(code);
notify();
});
inFlight.set(code, load);
return load;
}
/**
* Load the finer outlines of these countries; resolves when every one has
* settled, or after `ceilingMs` when given, whichever comes first. Never
* rejects: a file that does not come leaves its country coarse.
*/
export async function preloadCountryDetail(codes: readonly string[], ceilingMs?: number): Promise<void> {
const known = [...new Set(codes.map(codeOf).filter((c): c is string => c !== null))];
const all = Promise.all(known.map(loadOne));
if (ceilingMs === undefined) {
await all;
return;
}
let timer: ReturnType<typeof setTimeout> | undefined;
const ceiling = new Promise<void>((resolve) => {
timer = setTimeout(resolve, ceilingMs);
});
await Promise.race([all, ceiling]);
clearTimeout(timer);
}
/** Whether a country's finer outline is in, or known not to come; a country without one counts as settled. */
export function countryDetailSettled(code: string): boolean {
const known = codeOf(code);
return !known || loaded.has(known);
}
/** The finer outlines already in, of these countries. */
export function countryDetailShapes(codes: readonly string[]): Map<string, CountryShape> {
const out = new Map<string, CountryShape>();
for (const code of codes) {
const known = codeOf(code);
const shape = known ? loaded.get(known) : undefined;
if (known && shape) out.set(known, shape);
}
return out;
}
function subscribe(listener: () => void): () => void {
listeners.add(listener);
return () => {
listeners.delete(listener);
};
}
const snapshot = () => version;
/**
* The finer outlines of these countries that are in, keyed by code, loading
* the rest. An empty list loads nothing, which is how a map that does not want
* them asks. The component draws again as each one arrives.
*/
export function useCountryDetail(codes: readonly string[]): Map<string, CountryShape> {
useSyncExternalStore(subscribe, snapshot, snapshot);
const key = codes.join(',');
useEffect(() => {
if (!key) return;
void preloadCountryDetail(key.split(','));
}, [key]);
return countryDetailShapes(codes);
}
@@ -1,14 +1,24 @@
/**
* FE-STUDIO-PRINT-001 to FE-STUDIO-PRINT-004
* FE-STUDIO-PRINT-001 to FE-STUDIO-PRINT-006
*
* When the print view of a book may be printed: every picture in, the SVG
* ones too wherever they sit (a map marker, a photo behind a clip path), and
* a ceiling that gives a book of many photographs longer before the Save
* button gives up waiting.
*/
import { bookMapElementSchema, bookSpreadSchema, type BookElement } from '@trek/shared';
import { http, HttpResponse } from 'msw';
import { afterEach, describe, expect, it, vi } from 'vitest';
import { printReadyCeilingMs, svgImagesToWait, whenReady } from './printReady';
import { server } from '../../../tests/helpers/msw/server';
import {
bookMapDetailCountries,
mapDetailPending,
mapDetailReady,
printReadyCeilingMs,
svgImagesToWait,
whenReady,
} from './printReady';
const SVG = 'http://www.w3.org/2000/svg';
const XLINK = 'http://www.w3.org/1999/xlink';
@@ -73,3 +83,38 @@ describe('the ceiling', () => {
expect(ready).toBe(true);
});
});
describe('the finer coastlines', () => {
const map = (id: string, over: Record<string, unknown>) =>
bookMapElementSchema.parse({ id, kind: 'map', frame: { x: 0, y: 0, w: 100, h: 80 }, ...over }) as BookElement;
const hawaii = [
{ lat: 21.31, lng: -157.86 },
{ lat: 19.72, lng: -155.09 },
];
const book = (elements: BookElement[]) => ({
spreads: [bookSpreadSchema.parse({ id: 's', elements })],
});
it('FE-STUDIO-PRINT-005: names the countries whose finer outline a map of the book draws, each once', () => {
const doc = book([
map('a', { countries: ['us'], points: hawaii }),
map('b', { countries: ['US'], points: hawaii, coastDetail: 'detailed' }),
map('c', { countries: ['FR'], points: hawaii, coastDetail: 'simple' }),
map('d', { countries: ['DE'], points: [{ lat: 52.5, lng: 13.4 }], source: 'tiles' }),
]);
expect(bookMapDetailCountries(doc)).toEqual(['US']);
expect(bookMapDetailCountries(book([]))).toEqual([]);
});
it('FE-STUDIO-PRINT-006: waits for them before the sheets render, and no longer once they are in', async () => {
server.use(
http.get('/country-detail/NZ.json', () => HttpResponse.json({ d: 'M0 0L1 0L1 1Z', w: 1, h: 1, b: [0, 0, 1, 1] }))
);
const doc = book([map('nz', { countries: ['NZ'], points: [{ lat: -36.85, lng: 174.76 }] })]);
expect(mapDetailPending(doc)).toBe(true);
await mapDetailReady(doc);
expect(mapDetailPending(doc)).toBe(false);
// A book without maps that want them is ready at once.
await expect(mapDetailReady(book([]))).resolves.toBeUndefined();
});
});
@@ -4,7 +4,13 @@
* Both halves matter and neither is covered by the load event: a photograph
* still decoding prints as an empty box, and a face still loading prints in the
* fallback, the exact substitution the bundled typefaces exist to prevent.
* A third is the finer coastline a map draws where it has it, which has to be
* in before the sheets are rendered at all (`mapDetailReady`).
*/
import type { BookDocument } from '@trek/shared';
import { countryDetailSettled, preloadCountryDetail } from './countryDetail';
import { mapWantsDetail } from './travel/mapFit';
/** How long the print view waits at most, and the photo count past which a book gets the longer wait. */
const PRINT_READY = {
@@ -22,6 +28,38 @@ export function printReadyCeilingMs(photos: number): number {
return photos > PRINT_READY.largeBookPhotos ? PRINT_READY.largeCeilingMs : PRINT_READY.ceilingMs;
}
/** The countries whose finer outline some map of the book draws, each once. */
export function bookMapDetailCountries(doc: Pick<BookDocument, 'spreads'>): string[] {
const codes = new Set<string>();
for (const spread of doc.spreads) {
for (const el of spread.elements) {
if (el.kind === 'map' && mapWantsDetail(el)) for (const code of el.countries) codes.add(code.toUpperCase());
}
}
return [...codes];
}
/** Whether some finer outline the book's maps draw is still to come. */
export function mapDetailPending(doc: Pick<BookDocument, 'spreads'>): boolean {
return bookMapDetailCountries(doc).some((code) => !countryDetailSettled(code));
}
/**
* Wait until the finer country outlines the book's maps draw are in, or until
* the ceiling. The sheets are rendered to markup once and printed from it, so
* a map whose islands had not arrived yet would print without them; with
* them loaded first, every map draws them on its first render. A file that
* cannot be fetched leaves its map on the coarse outline, never the export
* waiting.
*/
export async function mapDetailReady(
doc: Pick<BookDocument, 'spreads'>,
ceilingMs: number = PRINT_READY.ceilingMs
): Promise<void> {
const codes = bookMapDetailCountries(doc);
if (codes.length) await preloadCountryDetail(codes, ceilingMs);
}
/** What `whenReady` reads off the print document: its `<img>` elements, its SVG and its fonts. */
interface PrintDocument {
images: ArrayLike<Element & { complete?: boolean }>;
@@ -0,0 +1,164 @@
/**
* FE-STUDIO-MAPFIT-001 to FE-STUDIO-MAPFIT-008
*
* Where a book map looks: the window fitted to its route or framed by hand,
* the antimeridian, and when a map draws the finer coastline. Measured, not
* drawn: what goes wrong here is a number, the box the frame shows.
*/
import { bookMapElementSchema } from '@trek/shared';
import { describe, expect, it } from 'vitest';
import { COUNTRY_SHAPES, projectMercator } from '../countryShapes';
import {
fitMapWindow,
landOffsets,
lngShift,
mapBows,
mapWantsDetail,
projectMapRoute,
routeBox,
viewBox,
} from './mapFit';
const FRAME = { x: 0, y: 0, w: 100, h: 50 };
const map = (over: Record<string, unknown> = {}) =>
bookMapElementSchema.parse({ id: 'm', kind: 'map', frame: FRAME, ...over });
const HONOLULU = { lat: 21.31, lng: -157.86 };
const HILO = { lat: 19.72, lng: -155.09 };
const SUVA = { lat: -18.14, lng: 178.44 };
const TAVEUNI = { lat: -16.85, lng: -179.97 };
function windowOf(over: Record<string, unknown>) {
const el = map(over);
const route = projectMapRoute(el);
const shapes = el.countries.map((c) => COUNTRY_SHAPES[c]).filter(Boolean);
return fitMapWindow({ el, route, bows: mapBows(el, route), shapes, cutToLand: false, w: FRAME.w, h: FRAME.h });
}
describe('the window a map shows', () => {
it('FE-STUDIO-MAPFIT-001: takes a view framed by hand as it is, widened to the frame, whatever the route', () => {
const view = { west: -160, south: 18, east: -154, north: 23 };
const win = windowOf({ view, points: [HONOLULU], countries: ['US'], fitToCountries: true });
const box = viewBox(view);
// A 2:1 frame: the box keeps its height and grows sideways about its centre.
expect(win.minY).toBeCloseTo(box.minY, 6);
expect(win.maxY).toBeCloseTo(box.maxY, 6);
expect((win.minX + win.maxX) / 2).toBeCloseTo((box.minX + box.maxX) / 2, 6);
expect((win.maxX - win.minX) / (win.maxY - win.minY)).toBeCloseTo(2, 6);
expect(win.scale).toBeCloseTo(FRAME.h / (box.maxY - box.minY), 6);
});
it('FE-STUDIO-MAPFIT-002: without a view fits the route with room around it, never the whole country', () => {
const win = windowOf({ points: [HONOLULU, HILO], fitToCountries: false, fitPadding: 0.5 });
const a = projectMercator(HONOLULU.lng, HONOLULU.lat);
const b = projectMercator(HILO.lng, HILO.lat);
expect(win.minX).toBeLessThan(Math.min(a.x, b.x));
expect(win.maxX).toBeGreaterThan(Math.max(a.x, b.x));
expect(win.maxX - win.minX).toBeLessThan(20);
});
it('FE-STUDIO-MAPFIT-003: a single stop is a place, not the world', () => {
const win = windowOf({ points: [HONOLULU], fitToCountries: false });
expect(win.maxY - win.minY).toBeLessThan(0.1);
});
});
describe('across the antimeridian', () => {
it('FE-STUDIO-MAPFIT-004: lifts the longitudes west of a view past 180 by a turn, and leaves other maps alone', () => {
const fiji = { west: 176, south: -20, east: 182, north: -15 };
expect(lngShift(fiji)(-179.97)).toBeCloseTo(180.03, 6);
expect(lngShift(fiji)(178.44)).toBe(178.44);
expect(lngShift(null)(-179.97)).toBe(-179.97);
expect(landOffsets(fiji)).toEqual([0, 360]);
expect(landOffsets({ west: -180, south: 0, east: -170, north: 5 })).toEqual([0, -360]);
expect(landOffsets(undefined)).toEqual([0]);
});
it('FE-STUDIO-MAPFIT-005: draws two islands either side of 180 next to each other on a map framed across it', () => {
const el = map({ view: { west: 176, south: -20, east: 182, north: -15 }, points: [SUVA, TAVEUNI] });
const route = projectMapRoute(el);
const [suva, taveuni] = route.points;
expect(Math.abs(taveuni.x - suva.x)).toBeLessThan(3);
const box = routeBox(route);
expect(box.maxX).toBeGreaterThan(180);
});
});
describe('the route', () => {
it('FE-STUDIO-MAPFIT-006: counts the roads into the extent, and bows only a chain of stops', () => {
const roads = [
[
[21.3, -157.8],
[20.5, -156.0],
[19.7, -155.1],
],
null,
];
const el = map({ points: [HONOLULU, HILO, HONOLULU], roads, routeArc: 'bow' });
const route = projectMapRoute(el);
expect(route.roads).toHaveLength(3);
expect(routeBox(route).maxY).toBeGreaterThanOrEqual(projectMercator(-155.1, 19.7).y);
expect(mapBows(el, route)).toHaveLength(2);
const tracked = map({
points: [HONOLULU, HILO],
routeArc: 'bow',
path: [
[
[21.3, -157.8],
[19.7, -155.1],
],
],
});
expect(mapBows(tracked, projectMapRoute(tracked))).toEqual([]);
expect(routeBox(projectMapRoute(map())).minX).toBe(Infinity);
});
});
describe('the finer coastline', () => {
it('FE-STUDIO-MAPFIT-007: wants it for a regional route, read from the route rather than the country fit', () => {
// Oahu to the Big Island: regional, and off every ring the coarse United States keeps.
expect(mapWantsDetail(map({ countries: ['US'], points: [HONOLULU, HILO] }))).toBe(true);
// Coast to coast is not regional, and its stops lie on the coarse outline.
const across = map({
countries: ['US'],
points: [
{ lat: 40.71, lng: -74.0 },
{ lat: 34.05, lng: -118.24 },
],
});
expect(mapWantsDetail(across)).toBe(false);
// A country of the map none of whose coarse rings is near the route: the finer one may have the island it is.
const far = map({
countries: ['US', 'NZ'],
points: [
{ lat: 40.71, lng: -74.0 },
{ lat: 34.05, lng: -118.24 },
],
});
expect(mapWantsDetail(far)).toBe(true);
});
it('FE-STUDIO-MAPFIT-008: follows the coast it was told, and never asks over imagery or without countries', () => {
const regional = { countries: ['US'], points: [HONOLULU, HILO] };
expect(mapWantsDetail(map({ ...regional, coastDetail: 'simple' }))).toBe(false);
const across = {
countries: ['US'],
points: [
{ lat: 40.71, lng: -74.0 },
{ lat: 34.05, lng: -118.24 },
],
};
expect(mapWantsDetail(map({ ...across, coastDetail: 'detailed' }))).toBe(true);
expect(mapWantsDetail(map({ ...regional, source: 'tiles' }))).toBe(false);
// Cut to its country, imagery still needs the outline as its stencil.
expect(mapWantsDetail(map({ ...regional, source: 'tiles', clip: 'country' }))).toBe(true);
expect(mapWantsDetail(map({ ...regional, showLand: false }))).toBe(false);
expect(mapWantsDetail(map({ points: [HONOLULU, HILO] }))).toBe(false);
expect(mapWantsDetail(map({ countries: ['US'] }))).toBe(false);
// A view framed by hand decides by its own size.
expect(mapWantsDetail(map({ countries: ['US'], view: { west: -160, south: 18, east: -154, north: 23 } }))).toBe(
true
);
});
});
@@ -0,0 +1,363 @@
import type { BookMapElement, BookMapView } from '@trek/shared';
import { haversineKm } from '../../../utils/geo';
import { COUNTRY_SHAPES, type CountryShape, countryParts, projectMercator } from '../countryShapes';
/**
* Where a route map looks: the route projected, the bows its long legs take,
* and the window the frame shows, fitted to the route or framed by hand.
*
* Moved out of the map element's view (TravelElements.tsx) so the print view
* can ask the same questions before it renders (which countries want their
* finer outline) and so the fit can be measured without drawing anything.
*/
interface MapXY {
x: number;
y: number;
}
/** A box in projected world units: longitude as x, Mercator y growing southwards. */
interface MapBox {
minX: number;
minY: number;
maxX: number;
maxY: number;
}
/** How far a leg bows, as a share of its chord, and which way. */
interface MapBow {
k: number;
nx: number;
ny: number;
}
/** The route of a map, projected: its stops, its recorded track, and every point its roads pass. */
interface MapRoute {
points: (BookMapElement['points'][number] & MapXY)[];
trail: MapXY[][];
roads: MapXY[];
/** Projects a coordinate the way everything on this map is, the antimeridian included. */
project: (lng: number, lat: number) => MapXY;
/** The longitude as this map draws it: lifted by a turn where its view runs past 180. */
shift: (lng: number) => number;
}
const EMPTY_BOX = (): MapBox => ({ minX: Infinity, minY: Infinity, maxX: -Infinity, maxY: -Infinity });
function grow(box: MapBox, p: MapXY) {
box.minX = Math.min(box.minX, p.x);
box.minY = Math.min(box.minY, p.y);
box.maxX = Math.max(box.maxX, p.x);
box.maxY = Math.max(box.maxY, p.y);
}
/**
* The longitude a map draws a coordinate at. A view framed across the
* antimeridian runs east past 180 (up to 540), so a stop at -175 on a map of
* Fiji is drawn at 185, beside the stops at 178, rather than a world away.
*/
export function lngShift(view: BookMapView | null | undefined): (lng: number) => number {
if (!view || view.east <= 180) return (lng) => lng;
return (lng) => (lng < view.west ? lng + 360 : lng);
}
/** The copies of the outlines a view needs, in degrees: one more to the east where it runs past 180. */
export function landOffsets(view: BookMapView | null | undefined): number[] {
if (!view) return [0];
const out = [0];
if (view.east > 180) out.push(360);
// The outlines of a country across the antimeridian are lifted past 180 themselves (Fiji, Chukotka).
if (view.west < -170) out.push(-360);
return out;
}
/** A view framed by hand, as a projected box. */
export function viewBox(view: BookMapView): MapBox {
const nw = projectMercator(view.west, view.north);
const se = projectMercator(view.east, view.south);
return { minX: nw.x, minY: nw.y, maxX: se.x, maxY: se.y };
}
/** A map's route, projected, the shift for its view applied. */
export function projectMapRoute(el: BookMapElement): MapRoute {
const shift = lngShift(el.view);
const project = (lng: number, lat: number) => projectMercator(shift(lng), lat);
/*
* Defended rather than assumed: an element built by hand somewhere in the
* editor and cast rather than parsed can lack `path` or `roads`, and reading
* `.map` off undefined would take the whole spread down in a renderer that
* also has to run for print.
*/
const path = el.path ?? [];
const roads = el.roads ?? [];
return {
points: el.points.map((p) => ({ ...p, ...project(p.lng, p.lat) })),
trail: path.map((seg) => seg.map(([lat, lng]) => project(lng, lat))),
roads: roads.flatMap((road) => (road ? road.map(([lat, lng]) => project(lng, lat)) : [])),
project,
shift,
};
}
/**
* The box around what the route draws: the stops, the recorded track, and the
* roads, which wander well outside the box around the two stops they join
* (that is the whole point of drawing them). Infinite while there is nothing.
*/
export function routeBox(route: MapRoute): MapBox {
const box = EMPTY_BOX();
for (const p of route.points) grow(box, p);
for (const seg of route.trail) for (const p of seg) grow(box, p);
for (const p of route.roads) grow(box, p);
return box;
}
/*
* ── The country fit ───────────────────────────────────────────────────────
*
* A country is one path but not one landmass. France's is five rings, three
* of them Kerguelen, French Guiana and New Caledonia, so unioning its whole
* bounding box fitted a Paris-Lyon-Nice route to 221 degrees of longitude and
* printed the three stops as a single dot. Britain does the same through South
* Georgia, Norway through Svalbard, Ecuador through the Galapagos.
*
* So only the rings the journey is near are fitted to. The margin is the
* route's own size, floored at two degrees, and that floor is the whole of the
* judgement: at two degrees a Paris-Nice route still pulls in Corsica, which is
* the picture that trip wants, while Kerguelen at 68 degrees east stays out.
* Raise it far and the territories come back; drop it to zero and a coastal
* route sitting just off a simplified coastline stops matching the country.
*
* The whole shape is still the fallback: with no route there is nothing to
* measure against, and a country none of whose rings match is better drawn
* whole than not at all. The outlines themselves are unchanged either way.
*/
function nearParts(shape: CountryShape, route: MapBox): [number, number, number, number][] {
if (!Number.isFinite(route.minX)) return [];
const margin = Math.max(route.maxX - route.minX, route.maxY - route.minY, 2);
const x0 = route.minX - margin,
y0 = route.minY - margin;
const x1 = route.maxX + margin,
y1 = route.maxY + margin;
return countryParts(shape).filter((p) => p[0] <= x1 && p[2] >= x0 && p[1] <= y1 && p[3] >= y0);
}
function withLand(box: MapBox, shapes: readonly CountryShape[]): MapBox {
const route = { ...box };
const out = { ...box };
for (const shape of shapes) {
const near = nearParts(shape, route);
for (const b of near.length > 0 ? near : [shape.b]) {
grow(out, { x: b[0], y: b[1] });
grow(out, { x: b[2], y: b[3] });
}
}
return out;
}
/*
* ── The bow ───────────────────────────────────────────────────────────────
*
* A straight line between two stops a continent apart is a claim about the
* journey that is plainly false, and a shallow curve is how printed maps have
* always said "this part was a flight". Two gates decide how much:
*
* **How far it was, in kilometres.** A fact about the journey rather than
* about the zoom, so two cafes four kilometres apart stay straight at every
* size and Tokyo to Los Angeles bows at every size. Ramped smoothly from 150km
* to 15000km rather than switched at a threshold, or a route would have one
* leg visibly curved and its neighbour dead straight.
*
* **Which way it runs.** A meridian is a great circle *and* a straight line in
* Mercator, so bowing a due north-south leg draws a detour that never
* happened. The east-west share of the leg damps it.
*
* The direction is poleward from the route's MEAN latitude, decided once for
* the element: per leg, a chain crossing the equator would flip sides halfway
* along and read as random rather than as drawn. A fraction of the chord
* rather than a distance, so the same numbers are right on a 40mm inset and a
* 400mm spread: what the eye reads is the angle the line leaves its marker at.
*/
export function mapBows(el: BookMapElement, route: MapRoute): MapBow[] {
if (el.routeArc !== 'bow' || route.trail.length > 0 || route.points.length < 2) return [];
const meanLat = el.points.reduce((sum, p) => sum + p.lat, 0) / el.points.length;
const poleward = meanLat >= 0 ? -1 : 1;
return el.points.slice(0, -1).map((a, i) => {
const b = el.points[i + 1];
const pa = route.points[i];
const pb = route.points[i + 1];
const dx = pb.x - pa.x;
const dy = pb.y - pa.y;
const d = Math.hypot(dx, dy);
if (d < 1e-6) return { k: 0, nx: 0, ny: 0 };
const u = Math.min(1, Math.max(0, Math.log(haversineKm(a, b) / 150) / Math.log(10)));
const ramp = u * u * (3 - 2 * u);
// How much of the leg runs east-west, which is where a bow is truthful.
const eastWest = 0.35 + 0.65 * Math.abs(dx / d);
// The normal, turned to point away from the equator side the route is on.
let nx = -dy / d;
let ny = dx / d;
if (Math.abs(ny) < 1e-9) {
// A due north-south leg has no poleward side; break the tie east.
nx = Math.abs(nx);
} else if (Math.sign(ny) !== poleward) {
nx = -nx;
ny = -ny;
}
return { k: 0.07 * ramp * eastWest, nx, ny };
});
}
/**
* The apexes join the extent before it is fitted. Without this the tile window
* and the vector fit are both cut to the straight chords, and a bowed leg is
* clipped by the very frame it was fitted to.
*/
function withBows(box: MapBox, route: MapRoute, bows: readonly MapBow[]): MapBox {
const out = { ...box };
bows.forEach((bow, i) => {
if (!bow.k) return;
const a = route.points[i];
const b = route.points[i + 1];
const d = Math.hypot(b.x - a.x, b.y - a.y);
grow(out, { x: (a.x + b.x) / 2 + bow.k * d * bow.nx, y: (a.y + b.y) / 2 + bow.k * d * bow.ny });
});
return out;
}
/**
* One stop is a place, not an extent. The window around it used to be two
* whole degrees, which put a single hotel on a map of half a country. A
* hundredth of the projected world is roughly a large city and its
* surroundings: near enough to see where it is, close enough that the pin
* means something.
*/
function atLeastAPlace(box: MapBox): MapBox {
const out = Number.isFinite(box.minX) ? { ...box } : { minX: -1, minY: -1, maxX: 1, maxY: 1 };
const SINGLE = 0.01;
if (out.maxX - out.minX < SINGLE) {
const c = (out.minX + out.maxX) / 2;
out.minX = c - SINGLE / 2;
out.maxX = c + SINGLE / 2;
}
if (out.maxY - out.minY < SINGLE) {
const c = (out.minY + out.maxY) / 2;
out.minY = c - SINGLE / 2;
out.maxY = c + SINGLE / 2;
}
return out;
}
/**
* Room around the route, as a share of the route rather than of the frame. A
* fixed margin in millimetres is the wrong shape twice over: on a wide route it
* is a hairline, and on a short one it is most of the picture.
*/
function padded(box: MapBox, share: number): MapBox {
// Same defence as `path`: undefined would make this NaN, and a NaN here reaches every coordinate on the map.
const more = 1 + Math.max(0, share);
const cx = (box.minX + box.maxX) / 2;
const cy = (box.minY + box.maxY) / 2;
const halfX = ((box.maxX - box.minX) * more) / 2;
const halfY = ((box.maxY - box.minY) * more) / 2;
return { minX: cx - halfX, maxX: cx + halfX, minY: cy - halfY, maxY: cy + halfY };
}
/*
* ── The window takes the frame's proportions ──────────────────────────────
*
* Two fits used to disagree about what the map was of. The outlines and the
* route were *contained* in the frame, fitted whole with air on the long side,
* while the imagery *covered* it, because a map with a strip of paper down one
* edge is not a map. On a frame whose shape did not match the route's those are
* different windows, and the tiles won: the picture filled the box and the
* route ran off the top of it.
*
* Widening the window to the frame's own proportions makes the two the same
* window. Cover and contain agree by construction, the route is inside
* whatever shape the element is dragged to, and the imagery still reaches
* every edge. A view framed by hand is widened the same way, about its centre.
*/
function framed(box: MapBox, w: number, h: number): MapBox {
const aspect = w / h;
const cx = (box.minX + box.maxX) / 2;
const cy = (box.minY + box.maxY) / 2;
const haveW = box.maxX - box.minX;
const haveH = box.maxY - box.minY;
if (haveW / haveH < aspect) {
const want = haveH * aspect;
return { ...box, minX: cx - want / 2, maxX: cx + want / 2 };
}
const want = haveW / aspect;
return { ...box, minY: cy - want / 2, maxY: cy + want / 2 };
}
/** The window a map shows, and how its projected world lands on the frame's millimetres. */
interface MapWindow extends MapBox {
scale: number;
offX: number;
offY: number;
}
/**
* The window a map shows. A view framed by hand is that view, widened to the
* frame's proportions. Otherwise it is fitted to what the map has to show,
* with a uniform scale so a route across Iceland is not stretched to fill a
* spread-wide frame: the journey, not the geography (a trip that stayed inside
* Berlin is a map of Berlin, not of Germany with two dots in it), unless
* `fitToCountries` asks for the country entire or the map is cut to its
* coastline, which only means anything with the coastline in view.
*/
export function fitMapWindow(input: {
el: BookMapElement;
route: MapRoute;
bows: readonly MapBow[];
shapes: readonly CountryShape[];
cutToLand: boolean;
w: number;
h: number;
}): MapWindow {
const { el, route, w, h } = input;
let box: MapBox;
if (el.view) {
box = viewBox(el.view);
} else {
box = routeBox(route);
const fitToLand = el.fitToCountries || input.cutToLand || (route.points.length === 0 && route.trail.length === 0);
if (fitToLand) box = withLand(box, input.shapes);
box = padded(atLeastAPlace(withBows(box, route, input.bows)), el.fitPadding ?? 0.18);
}
const win = framed(box, w, h);
const scale = Math.min(w / (win.maxX - win.minX), h / (win.maxY - win.minY));
const offX = (w - (win.maxX - win.minX) * scale) / 2 - win.minX * scale;
const offY = (h - (win.maxY - win.minY) * scale) / 2 - win.minY * scale;
return { ...win, scale, offX, offY };
}
/*
* ── Which outline a map draws ─────────────────────────────────────────────
*
* The coarse set (countryShapes.ts) is cut for a whole country, and leaves out
* the islands below a share of the mainland: Hawaii is a tenth of a percent of
* the United States. The finer one (countryDetail.ts) is worth its download
* where the map is regional, or where the route lies off every coarse ring of
* its countries, which is the trip to Hawaii exactly. The decision reads the
* route, never the fitted window: fitted to the countries, a Hawaii trip finds
* no coarse ring near it and falls back to the whole United States, and a map
* of the whole United States would never ask for the islands.
*/
/** A route this many projected degrees across, or less, is regional. */
const REGIONAL_SPAN = 30;
/** Whether a map draws the finer outlines of its countries. */
export function mapWantsDetail(el: BookMapElement, route: MapRoute = projectMapRoute(el)): boolean {
// Outlines are drawn as land on the vector map, and as the stencil of a map cut to its countries.
const drawsLand = (el.showLand && el.source === 'vector') || el.clip === 'country';
if (!drawsLand || el.coastDetail === 'simple' || el.countries.length === 0) return false;
if (el.coastDetail === 'detailed') return true;
const box = el.view ? viewBox(el.view) : routeBox(route);
if (!Number.isFinite(box.minX)) return false;
if (Math.max(box.maxX - box.minX, box.maxY - box.minY) <= REGIONAL_SPAN) return true;
const coarse = el.countries.map((c) => COUNTRY_SHAPES[c.toUpperCase()]).filter((s): s is CountryShape => !!s);
return coarse.some((shape) => nearParts(shape, box).length === 0);
}