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
+210
View File
@@ -0,0 +1,210 @@
#!/usr/bin/env node
/**
* The finer country outlines for TREK Studio's vector map, one file per
* country, built from the boundaries the server already bundles for Atlas.
*
* node scripts/build-country-detail.mjs
*
* Writes `public/country-detail/<CODE>.json`. Run it when
* `server/assets/atlas/admin0.geojson.gz` changes; the output is committed, so
* a normal build never runs this.
*
* ── Why a second set beside countryShapes.ts ──────────────────────────────
*
* The bundled silhouettes (`src/components/Studio/countryShapes.ts`, from
* build-country-shapes.mjs) are cut for a country drawn at postage-stamp size:
* islands below 1.2% of the mainland are dropped and every outline keeps at
* most 190 points. That is right for a whole country and wrong for a map of
* part of one. Hawaii is a tenth of a percent of the United States, so a trip
* there was drawn as a route over empty sea (#3056), and a week on the Greek
* islands showed half of them.
*
* These keep every ring above a few square kilometres and a far larger point
* budget. They are static files rather than code: a map that needs one loads
* it when it is drawn (countryDetail.ts), the app bundle and the offline
* precache stay as they were, and the coarse set stays the fallback whenever a
* file has not arrived.
*
* Same projection, same antimeridian handling and the same 0..100 box as the
* coarse set, with two decimals instead of one, so `countryWorldPath` and
* `countryParts` read both alike.
*/
import fs from 'node:fs';
import path from 'node:path';
import url from 'node:url';
import zlib from 'node:zlib';
const HERE = path.dirname(url.fileURLToPath(import.meta.url));
const SRC = path.join(HERE, '..', '..', 'server', 'assets', 'atlas', 'admin0.geojson.gz');
const OUT = path.join(HERE, '..', 'public', 'country-detail');
/** Rings below this projected area (square degrees, about 5 km² at the equator) are specks at any map size. */
const MIN_RING_AREA = 0.0004;
/** Never more than this many rings for one country. */
const MAX_RINGS = 240;
/** Point budget per country, across every ring it keeps. */
const MAX_POINTS = 1600;
/** Web Mercator, unscaled. y is flipped so it grows downwards like SVG's. */
function project([lng, lat]) {
const clamped = Math.max(-85.05, Math.min(85.05, lat));
const rad = (clamped * Math.PI) / 180;
return [lng, -(Math.log(Math.tan(Math.PI / 4 + rad / 2)) * 180) / Math.PI];
}
function ringArea(ring) {
let a = 0;
for (let i = 0, j = ring.length - 1; i < ring.length; j = i++) {
a += ring[j][0] * ring[i][1] - ring[i][0] * ring[j][1];
}
return Math.abs(a / 2);
}
/** Perpendicular distance from p to the segment ab, squared. */
function segDistSq(p, a, b) {
let x = a[0],
y = a[1];
let dx = b[0] - x,
dy = b[1] - y;
if (dx !== 0 || dy !== 0) {
const t = ((p[0] - x) * dx + (p[1] - y) * dy) / (dx * dx + dy * dy);
if (t > 1) {
x = b[0];
y = b[1];
} else if (t > 0) {
x += dx * t;
y += dy * t;
}
}
dx = p[0] - x;
dy = p[1] - y;
return dx * dx + dy * dy;
}
/** Douglas-Peucker, iterative so a long coastline cannot blow the stack. */
function simplify(points, tolerance) {
if (points.length < 3) return points;
const tolSq = tolerance * tolerance;
const keep = new Uint8Array(points.length);
keep[0] = 1;
keep[points.length - 1] = 1;
const stack = [[0, points.length - 1]];
while (stack.length) {
const [first, last] = stack.pop();
let maxSq = 0;
let index = 0;
for (let i = first + 1; i < last; i++) {
const d = segDistSq(points[i], points[first], points[last]);
if (d > maxSq) {
maxSq = d;
index = i;
}
}
if (maxSq > tolSq) {
keep[index] = 1;
stack.push([first, index], [index, last]);
}
}
return points.filter((_, i) => keep[i]);
}
function outerRings(geometry) {
if (!geometry) return [];
if (geometry.type === 'Polygon') return geometry.coordinates.slice(0, 1);
if (geometry.type === 'MultiPolygon') return geometry.coordinates.map((poly) => poly[0]);
return [];
}
/** A ring across the antimeridian, lifted into one continuous longitude range (as build-country-shapes.mjs does). */
function unwrap(ring) {
let min = Infinity;
let max = -Infinity;
for (const [lng] of ring) {
if (lng < min) min = lng;
if (lng > max) max = lng;
}
if (max - min <= 180) return ring;
return ring.map(([lng, lat]) => [lng < 0 ? lng + 360 : lng, lat]);
}
const round = (n) => Math.round(n * 100) / 100;
function build(feature) {
const rings = outerRings(feature.geometry)
.map(unwrap)
.map((ring) => ring.map(project))
.map((ring) => ({ ring, area: ringArea(ring) }))
.sort((a, b) => b.area - a.area);
if (!rings.length) return null;
const biggest = rings[0].area;
// The mainland always, however small the country; every other ring above the speck size.
const kept = rings
.filter((r, i) => i === 0 || r.area >= Math.min(MIN_RING_AREA, biggest))
.slice(0, MAX_RINGS)
.map((r) => r.ring);
let minX = Infinity,
minY = Infinity,
maxX = -Infinity,
maxY = -Infinity;
for (const ring of kept) {
for (const [x, y] of ring) {
if (x < minX) minX = x;
if (x > maxX) maxX = x;
if (y < minY) minY = y;
if (y > maxY) maxY = y;
}
}
const spanX = maxX - minX;
const spanY = maxY - minY;
if (!(spanX > 0) || !(spanY > 0)) return null;
const scale = 100 / Math.max(spanX, spanY);
const normalised = kept.map((ring) => ring.map(([x, y]) => [(x - minX) * scale, (y - minY) * scale]));
let tolerance = 0.012;
let simplified = normalised.map((r) => simplify(r, tolerance));
let guard = 0;
while (simplified.reduce((n, r) => n + r.length, 0) > MAX_POINTS && guard++ < 60) {
tolerance *= 1.25;
simplified = normalised.map((r) => simplify(r, tolerance));
}
const d = simplified
.map((ring) => {
// Two decimals can fold neighbours onto one point; a ring left with fewer than three is not a shape.
const pts = ring.map(([x, y]) => `${round(x)} ${round(y)}`).filter((p, i, all) => i === 0 || p !== all[i - 1]);
return pts.length >= 3 ? `M${pts.join('L')}Z` : '';
})
.join('');
if (!d) return null;
return {
d,
w: Math.round(spanX * scale * 10) / 10,
h: Math.round(spanY * scale * 10) / 10,
b: [minX, minY, maxX, maxY].map((v) => Math.round(v * 100) / 100),
};
}
const collection = JSON.parse(zlib.gunzipSync(fs.readFileSync(SRC)).toString('utf8'));
const shapes = new Map();
for (const feature of collection.features) {
const code = String(feature.properties?.ISO_A2 || '').toUpperCase();
if (!/^[A-Z]{2}$/.test(code)) continue;
const built = build(feature);
if (!built) continue;
// Two features for one code: the one with more outline is the country rather than a dependency.
const prev = shapes.get(code);
if (!prev || built.d.length > prev.d.length) shapes.set(code, built);
}
fs.rmSync(OUT, { recursive: true, force: true });
fs.mkdirSync(OUT, { recursive: true });
let bytes = 0;
for (const code of [...shapes.keys()].sort()) {
const body = `${JSON.stringify(shapes.get(code))}\n`;
bytes += Buffer.byteLength(body);
fs.writeFileSync(path.join(OUT, `${code}.json`), body, 'utf8');
}
console.log(
`[country-detail] ${shapes.size} countries, ${Math.round(bytes / 1024)} kB → ${path.relative(process.cwd(), OUT)}`
);
-1
View File
@@ -1822,7 +1822,6 @@
"tests/helpers/mobileTrip.ts",
"tests/helpers/msw/handlers/admin.ts",
"tests/helpers/msw/handlers/auth.ts",
"tests/helpers/msw/handlers/index.ts",
"tests/helpers/msw/handlers/notifications.ts",
"tests/helpers/msw/handlers/shared.ts",
"tests/helpers/multipart.ts",
+1 -1
View File
@@ -13,7 +13,7 @@
"src/components/Planner/DayPlanSidebar.tsx": 2908,
"src/components/Planner/PlaceFormModal.test.tsx": 2836,
"src/components/Planner/PlaceInspector.tsx": 1030,
"src/components/Studio/TravelElements.tsx": 1559,
"src/components/Studio/TravelElements.tsx": 1332,
"src/components/Studio/countryShapes.ts": 2595,
"src/index.css": 1636,
"src/mobile/screens/admin/MAdminPluginsPanel.tsx": 1503,