Implement shared packages (tasks 2.1-2.6)

- @trails-cool/types: Route, Activity, Waypoint, RouteVersion, RouteMetadata
- @trails-cool/gpx: GPX parser (XML→waypoints/tracks/elevation) and generator
  with round-trip test, haversine distance, elevation gain/loss computation
- @trails-cool/map: MapView (Leaflet + OSM/OpenTopoMap/CyclOSM layer switcher),
  RouteLayer (GeoJSON polyline rendering)
- @trails-cool/ui: Button (primary/secondary/ghost), Input (with label/error),
  Card components with Tailwind styling
- @trails-cool/i18n: react-i18next config with English + German translations,
  browser language detection, fallback to English

All 13 unit tests pass. Both apps build successfully.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
Ullrich Schäfer 2026-03-22 13:09:35 +01:00
parent 325a4466d5
commit 2cfa5e54e7
No known key found for this signature in database
GPG key ID: A32FF691A0F752D9
23 changed files with 809 additions and 30 deletions

View file

@ -2,6 +2,12 @@
"name": "@trails-cool/gpx",
"version": "0.0.1",
"type": "module",
"exports": {
".": "./src/index.ts"
},
"main": "./src/index.ts",
"types": "./src/index.ts"
"types": "./src/index.ts",
"dependencies": {
"@trails-cool/types": "workspace:*"
}
}

View file

@ -0,0 +1,51 @@
import { describe, it, expect } from "vitest";
import { generateGpx } from "./generate";
import { parseGpx } from "./parse";
describe("generateGpx", () => {
it("generates valid GPX with name", () => {
const gpx = generateGpx({ name: "Test Route" });
expect(gpx).toContain('<?xml version="1.0"');
expect(gpx).toContain("<name>Test Route</name>");
expect(gpx).toContain("</gpx>");
});
it("generates waypoints", () => {
const gpx = generateGpx({
waypoints: [
{ lat: 52.52, lon: 13.405, name: "Berlin" },
{ lat: 48.137, lon: 11.576 },
],
});
expect(gpx).toContain('wpt lat="52.52" lon="13.405"');
expect(gpx).toContain("<name>Berlin</name>");
expect(gpx).toContain('wpt lat="48.137" lon="11.576"');
});
it("generates track points with elevation", () => {
const gpx = generateGpx({
tracks: [[{ lat: 52.52, lon: 13.405, ele: 34 }, { lat: 48.137, lon: 11.576, ele: 519 }]],
});
expect(gpx).toContain("<trkseg>");
expect(gpx).toContain('<trkpt lat="52.52" lon="13.405">');
expect(gpx).toContain("<ele>34</ele>");
});
it("escapes XML special characters in names", () => {
const gpx = generateGpx({ name: "Route <A> & B" });
expect(gpx).toContain("Route &lt;A&gt; &amp; B");
});
it("produces round-trippable GPX", () => {
const original = generateGpx({
name: "Round Trip",
waypoints: [{ lat: 52.52, lon: 13.405, name: "Start" }],
tracks: [[{ lat: 52.52, lon: 13.405, ele: 34 }, { lat: 48.137, lon: 11.576, ele: 519 }]],
});
const parsed = parseGpx(original);
expect(parsed.name).toBe("Round Trip");
expect(parsed.waypoints).toHaveLength(1);
expect(parsed.waypoints[0]!.name).toBe("Start");
expect(parsed.tracks[0]).toHaveLength(2);
});
});

View file

@ -0,0 +1,60 @@
import type { Waypoint } from "@trails-cool/types";
import type { TrackPoint } from "./types";
/**
* Generate a GPX XML string from waypoints and track points.
*/
export function generateGpx(options: {
name?: string;
waypoints?: Waypoint[];
tracks?: TrackPoint[][];
}): string {
const lines: string[] = [
'<?xml version="1.0" encoding="UTF-8"?>',
'<gpx version="1.1" creator="trails.cool"',
' xmlns="http://www.topografix.com/GPX/1/1">',
];
if (options.name) {
lines.push(" <metadata>", ` <name>${escapeXml(options.name)}</name>`, " </metadata>");
}
if (options.waypoints) {
for (const wpt of options.waypoints) {
lines.push(` <wpt lat="${wpt.lat}" lon="${wpt.lon}">`);
if (wpt.name) {
lines.push(` <name>${escapeXml(wpt.name)}</name>`);
}
lines.push(" </wpt>");
}
}
if (options.tracks) {
for (const track of options.tracks) {
lines.push(" <trk>", " <trkseg>");
for (const pt of track) {
lines.push(` <trkpt lat="${pt.lat}" lon="${pt.lon}">`);
if (pt.ele !== undefined) {
lines.push(` <ele>${pt.ele}</ele>`);
}
if (pt.time) {
lines.push(` <time>${escapeXml(pt.time)}</time>`);
}
lines.push(" </trkpt>");
}
lines.push(" </trkseg>", " </trk>");
}
}
lines.push("</gpx>");
return lines.join("\n");
}
function escapeXml(str: string): string {
return str
.replace(/&/g, "&amp;")
.replace(/</g, "&lt;")
.replace(/>/g, "&gt;")
.replace(/"/g, "&quot;")
.replace(/'/g, "&apos;");
}

View file

@ -1,4 +1,3 @@
/**
* GPX parsing, generation, and validation for trails.cool
*/
export {};
export { parseGpx } from "./parse";
export { generateGpx } from "./generate";
export type { GpxData, TrackPoint, ElevationProfile } from "./types";

View file

@ -0,0 +1,56 @@
import { describe, it, expect } from "vitest";
import { parseGpx } from "./parse";
const sampleGpx = `<?xml version="1.0" encoding="UTF-8"?>
<gpx version="1.1" creator="test" xmlns="http://www.topografix.com/GPX/1/1">
<metadata><name>Test Route</name></metadata>
<wpt lat="52.52" lon="13.405"><name>Berlin</name></wpt>
<wpt lat="48.137" lon="11.576"><name>Munich</name></wpt>
<trk>
<trkseg>
<trkpt lat="52.52" lon="13.405"><ele>34</ele></trkpt>
<trkpt lat="51.05" lon="13.74"><ele>113</ele></trkpt>
<trkpt lat="48.137" lon="11.576"><ele>519</ele></trkpt>
</trkseg>
</trk>
</gpx>`;
describe("parseGpx", () => {
it("parses route name", () => {
const result = parseGpx(sampleGpx);
expect(result.name).toBe("Test Route");
});
it("parses waypoints with lat, lon, and name", () => {
const result = parseGpx(sampleGpx);
expect(result.waypoints).toHaveLength(2);
expect(result.waypoints[0]).toEqual({ lat: 52.52, lon: 13.405, name: "Berlin" });
expect(result.waypoints[1]).toEqual({ lat: 48.137, lon: 11.576, name: "Munich" });
});
it("parses track points with elevation", () => {
const result = parseGpx(sampleGpx);
expect(result.tracks).toHaveLength(1);
expect(result.tracks[0]).toHaveLength(3);
expect(result.tracks[0]![0]).toEqual({ lat: 52.52, lon: 13.405, ele: 34, time: undefined });
});
it("computes elevation gain and loss", () => {
const result = parseGpx(sampleGpx);
expect(result.elevation.gain).toBeGreaterThan(0);
expect(result.elevation.loss).toBe(0); // monotonically increasing elevation
expect(result.elevation.gain).toBe(485); // 113-34 + 519-113
});
it("builds elevation profile", () => {
const result = parseGpx(sampleGpx);
expect(result.elevation.profile).toHaveLength(3);
expect(result.elevation.profile[0]!.distance).toBe(0);
expect(result.elevation.profile[0]!.elevation).toBe(34);
expect(result.elevation.profile[2]!.distance).toBeGreaterThan(0);
});
it("throws on invalid XML", () => {
expect(() => parseGpx("not xml at all <<<<")).toThrow("Invalid GPX XML");
});
});

103
packages/gpx/src/parse.ts Normal file
View file

@ -0,0 +1,103 @@
import type { Waypoint } from "@trails-cool/types";
import type { GpxData, TrackPoint, ElevationProfile } from "./types";
/**
* Parse a GPX XML string into structured data.
*/
export function parseGpx(xml: string): GpxData {
const parser = new DOMParser();
const doc = parser.parseFromString(xml, "application/xml");
const parserError = doc.querySelector("parsererror");
if (parserError) {
throw new Error(`Invalid GPX XML: ${parserError.textContent}`);
}
const name = doc.querySelector("metadata > name")?.textContent ?? undefined;
const waypoints = parseWaypoints(doc);
const tracks = parseTracks(doc);
const elevation = computeElevation(tracks);
return { name, waypoints, tracks, elevation };
}
function parseWaypoints(doc: Document): Waypoint[] {
const wpts = doc.querySelectorAll("wpt");
return Array.from(wpts).map((wpt) => {
const lat = parseFloat(wpt.getAttribute("lat") ?? "0");
const lon = parseFloat(wpt.getAttribute("lon") ?? "0");
const name = wpt.querySelector("name")?.textContent ?? undefined;
return { lat, lon, name };
});
}
function parseTracks(doc: Document): TrackPoint[][] {
const tracks: TrackPoint[][] = [];
const trksegs = doc.querySelectorAll("trk > trkseg");
for (const seg of trksegs) {
const points: TrackPoint[] = [];
for (const pt of seg.querySelectorAll("trkpt")) {
const lat = parseFloat(pt.getAttribute("lat") ?? "0");
const lon = parseFloat(pt.getAttribute("lon") ?? "0");
const eleText = pt.querySelector("ele")?.textContent;
const time = pt.querySelector("time")?.textContent ?? undefined;
points.push({
lat,
lon,
ele: eleText ? parseFloat(eleText) : undefined,
time,
});
}
tracks.push(points);
}
return tracks;
}
function computeElevation(tracks: TrackPoint[][]): GpxData["elevation"] {
let gain = 0;
let loss = 0;
const profile: ElevationProfile[] = [];
let totalDistance = 0;
for (const track of tracks) {
for (let i = 0; i < track.length; i++) {
const pt = track[i]!;
if (i > 0) {
const prev = track[i - 1]!;
totalDistance += haversineDistance(prev.lat, prev.lon, pt.lat, pt.lon);
if (pt.ele !== undefined && prev.ele !== undefined) {
const diff = pt.ele - prev.ele;
if (diff > 0) gain += diff;
else loss += Math.abs(diff);
}
}
if (pt.ele !== undefined) {
profile.push({ distance: totalDistance, elevation: pt.ele });
}
}
}
return { gain: Math.round(gain), loss: Math.round(loss), profile };
}
/** Haversine distance between two points in meters */
function haversineDistance(
lat1: number,
lon1: number,
lat2: number,
lon2: number,
): number {
const R = 6371000;
const toRad = (deg: number) => (deg * Math.PI) / 180;
const dLat = toRad(lat2 - lat1);
const dLon = toRad(lon2 - lon1);
const a =
Math.sin(dLat / 2) ** 2 +
Math.cos(toRad(lat1)) * Math.cos(toRad(lat2)) * Math.sin(dLon / 2) ** 2;
return R * 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
}

26
packages/gpx/src/types.ts Normal file
View file

@ -0,0 +1,26 @@
import type { Waypoint } from "@trails-cool/types";
export interface TrackPoint {
lat: number;
lon: number;
ele?: number;
time?: string;
}
export interface ElevationProfile {
/** Distance from start in meters */
distance: number;
/** Elevation in meters */
elevation: number;
}
export interface GpxData {
name?: string;
waypoints: Waypoint[];
tracks: TrackPoint[][];
elevation: {
gain: number;
loss: number;
profile: ElevationProfile[];
};
}

View file

@ -2,6 +2,15 @@
"name": "@trails-cool/i18n",
"version": "0.0.1",
"type": "module",
"exports": {
".": "./src/index.ts",
"./locales/*": "./src/locales/*"
},
"main": "./src/index.ts",
"types": "./src/index.ts"
"types": "./src/index.ts",
"peerDependencies": {
"react": ">=18",
"i18next": ">=23",
"react-i18next": ">=14"
}
}

View file

@ -1,5 +1,29 @@
/**
* Shared i18n configuration and translation strings for trails.cool
* Uses react-i18next. Start with English + German.
*/
export {};
import i18n from "i18next";
import { initReactI18next } from "react-i18next";
import LanguageDetector from "i18next-browser-languagedetector";
import en from "./locales/en";
import de from "./locales/de";
export const defaultNS = "common";
export const resources = {
en: { common: en.common, planner: en.planner, journal: en.journal },
de: { common: de.common, planner: de.planner, journal: de.journal },
} as const;
export function initI18n() {
return i18n
.use(LanguageDetector)
.use(initReactI18next)
.init({
resources,
defaultNS,
fallbackLng: "en",
supportedLngs: ["en", "de"],
interpolation: {
escapeValue: false,
},
});
}
export { i18n };

View file

@ -0,0 +1,59 @@
export default {
common: {
save: "Speichern",
cancel: "Abbrechen",
delete: "Löschen",
edit: "Bearbeiten",
close: "Schließen",
loading: "Wird geladen...",
error: "Etwas ist schiefgelaufen",
},
planner: {
title: "trails.cool Planer",
subtitle: "Gemeinsame Routenplanung",
newSession: "Neue Sitzung",
saveRoute: "Route speichern",
exportGpx: "GPX exportieren",
profile: "Routing-Profil",
profiles: {
trekking: "Wandern",
bike: "Radfahren",
shortest: "Kürzeste",
},
elevation: {
gain: "Höhenmeter aufwärts",
loss: "Höhenmeter abwärts",
profile: "Höhenprofil",
},
},
journal: {
title: "trails.cool",
subtitle: "Dein Outdoor-Aktivitäten-Tagebuch",
routes: {
title: "Routen",
new: "Neue Route",
edit: "Route bearbeiten",
editInPlanner: "Im Planer bearbeiten",
importGpx: "GPX importieren",
exportGpx: "GPX exportieren",
delete: "Route löschen",
distance: "Strecke",
elevationGain: "Höhenmeter",
},
activities: {
title: "Aktivitäten",
new: "Neue Aktivität",
duration: "Dauer",
linkToRoute: "Mit Route verknüpfen",
createRouteFromActivity: "Route aus Aktivität erstellen",
},
auth: {
login: "Anmelden",
register: "Registrieren",
logout: "Abmelden",
email: "E-Mail",
password: "Passwort",
username: "Benutzername",
},
},
} as const;

View file

@ -0,0 +1,59 @@
export default {
common: {
save: "Save",
cancel: "Cancel",
delete: "Delete",
edit: "Edit",
close: "Close",
loading: "Loading...",
error: "Something went wrong",
},
planner: {
title: "trails.cool Planner",
subtitle: "Collaborative route planning",
newSession: "New Session",
saveRoute: "Save Route",
exportGpx: "Export GPX",
profile: "Routing Profile",
profiles: {
trekking: "Hiking",
bike: "Cycling",
shortest: "Shortest",
},
elevation: {
gain: "Elevation Gain",
loss: "Elevation Loss",
profile: "Elevation Profile",
},
},
journal: {
title: "trails.cool",
subtitle: "Your outdoor activity journal",
routes: {
title: "Routes",
new: "New Route",
edit: "Edit Route",
editInPlanner: "Edit in Planner",
importGpx: "Import GPX",
exportGpx: "Export GPX",
delete: "Delete Route",
distance: "Distance",
elevationGain: "Elevation Gain",
},
activities: {
title: "Activities",
new: "New Activity",
duration: "Duration",
linkToRoute: "Link to Route",
createRouteFromActivity: "Create Route from Activity",
},
auth: {
login: "Log In",
register: "Sign Up",
logout: "Log Out",
email: "Email",
password: "Password",
username: "Username",
},
},
} as const;

View file

@ -2,6 +2,15 @@
"name": "@trails-cool/map",
"version": "0.0.1",
"type": "module",
"exports": {
".": "./src/index.ts"
},
"main": "./src/index.ts",
"types": "./src/index.ts"
"types": "./src/index.ts",
"peerDependencies": {
"react": ">=18",
"react-dom": ">=18",
"leaflet": ">=1.9",
"react-leaflet": ">=5"
}
}

View file

@ -0,0 +1,34 @@
import { MapContainer, TileLayer, LayersControl } from "react-leaflet";
import { baseLayers } from "./layers";
import "leaflet/dist/leaflet.css";
export interface MapViewProps {
center?: [number, number];
zoom?: number;
className?: string;
children?: React.ReactNode;
}
export function MapView({
center = [50.1, 10.0],
zoom = 6,
className = "h-full w-full",
children,
}: MapViewProps) {
return (
<MapContainer center={center} zoom={zoom} className={className}>
<LayersControl position="topright">
{baseLayers.map((layer, i) => (
<LayersControl.BaseLayer key={layer.name} checked={i === 0} name={layer.name}>
<TileLayer
url={layer.url}
attribution={layer.attribution}
maxZoom={layer.maxZoom}
/>
</LayersControl.BaseLayer>
))}
</LayersControl>
{children}
</MapContainer>
);
}

View file

@ -0,0 +1,18 @@
import { GeoJSON } from "react-leaflet";
import type { GeoJsonObject } from "geojson";
export interface RouteLayerProps {
data: GeoJsonObject;
color?: string;
weight?: number;
}
export function RouteLayer({ data, color = "#2563eb", weight = 4 }: RouteLayerProps) {
return (
<GeoJSON
key={JSON.stringify(data)}
data={data}
style={{ color, weight, opacity: 0.8 }}
/>
);
}

View file

@ -1,5 +1,6 @@
/**
* Map rendering utilities for trails.cool
* Leaflet wrappers, tile layer configs, overlay management
*/
export {};
export { MapView } from "./MapView";
export type { MapViewProps } from "./MapView";
export { RouteLayer } from "./RouteLayer";
export type { RouteLayerProps } from "./RouteLayer";
export { baseLayers } from "./layers";
export type { TileLayerConfig } from "./layers";

View file

@ -0,0 +1,29 @@
export interface TileLayerConfig {
name: string;
url: string;
attribution: string;
maxZoom?: number;
}
export const baseLayers: TileLayerConfig[] = [
{
name: "OpenStreetMap",
url: "https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png",
attribution: '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a>',
maxZoom: 19,
},
{
name: "OpenTopoMap",
url: "https://{s}.tile.opentopomap.org/{z}/{x}/{y}.png",
attribution:
'&copy; <a href="https://opentopomap.org">OpenTopoMap</a> (<a href="https://creativecommons.org/licenses/by-sa/3.0/">CC-BY-SA</a>)',
maxZoom: 17,
},
{
name: "CyclOSM",
url: "https://{s}.tile-cyclosm.openstreetmap.fr/cyclosm/{z}/{x}/{y}.png",
attribution:
'&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> &copy; <a href="https://github.com/cyclosm/cyclosm-cartocss-style/releases">CyclOSM</a>',
maxZoom: 20,
},
];

View file

@ -0,0 +1,32 @@
import type { ButtonHTMLAttributes } from "react";
export interface ButtonProps extends ButtonHTMLAttributes<HTMLButtonElement> {
variant?: "primary" | "secondary" | "ghost";
size?: "sm" | "md" | "lg";
}
const variantStyles = {
primary: "bg-blue-600 text-white hover:bg-blue-700 active:bg-blue-800",
secondary: "bg-gray-100 text-gray-900 hover:bg-gray-200 active:bg-gray-300",
ghost: "text-gray-700 hover:bg-gray-100 active:bg-gray-200",
};
const sizeStyles = {
sm: "px-2.5 py-1.5 text-sm",
md: "px-4 py-2 text-sm",
lg: "px-6 py-3 text-base",
};
export function Button({
variant = "primary",
size = "md",
className = "",
...props
}: ButtonProps) {
return (
<button
className={`inline-flex items-center justify-center rounded-md font-medium transition-colors focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2 disabled:opacity-50 disabled:pointer-events-none ${variantStyles[variant]} ${sizeStyles[size]} ${className}`}
{...props}
/>
);
}

12
packages/ui/src/Card.tsx Normal file
View file

@ -0,0 +1,12 @@
export interface CardProps {
className?: string;
children: React.ReactNode;
}
export function Card({ className = "", children }: CardProps) {
return (
<div className={`rounded-lg border border-gray-200 bg-white p-6 shadow-sm ${className}`}>
{children}
</div>
);
}

25
packages/ui/src/Input.tsx Normal file
View file

@ -0,0 +1,25 @@
import type { InputHTMLAttributes } from "react";
export interface InputProps extends InputHTMLAttributes<HTMLInputElement> {
label?: string;
error?: string;
}
export function Input({ label, error, className = "", id, ...props }: InputProps) {
const inputId = id ?? label?.toLowerCase().replace(/\s+/g, "-");
return (
<div className="flex flex-col gap-1.5">
{label && (
<label htmlFor={inputId} className="text-sm font-medium text-gray-700">
{label}
</label>
)}
<input
id={inputId}
className={`rounded-md border border-gray-300 px-3 py-2 text-sm shadow-sm transition-colors focus:border-blue-500 focus:outline-none focus:ring-1 focus:ring-blue-500 ${error ? "border-red-500" : ""} ${className}`}
{...props}
/>
{error && <p className="text-sm text-red-600">{error}</p>}
</div>
);
}

View file

@ -1,4 +1,6 @@
/**
* Shared UI components for trails.cool
*/
export {};
export { Button } from "./Button";
export type { ButtonProps } from "./Button";
export { Input } from "./Input";
export type { InputProps } from "./Input";
export { Card } from "./Card";
export type { CardProps } from "./Card";