Skip to content

Commit 46f4e44

Browse files
committed
Plan 019: trip reconstruction — design + Phase 1 artifacts
Additive multi-stop Trip (optional ordered stops[]; from/to mirror first/last for backward-compat), widened approximate date (YYYY / YYYY-MM), great-circle path distance reusing haversineKm/coordsOf, and a page-layer composer via a new useUi.tripEditId. US3 back-nav fix: route the Travel airport row to openCity(IATA) — CityScreen already serves airports — so one Back returns to the Travel list instead of stranding on the map. Stations deferred (no dataset; stop model kept kind-agnostic). No new deps; SCHEMA_VERSION 10 -> 11. Constitution Check PASS — retrospective reconstruction (remembering), explicitly not trip planning. plan.md, research.md, data-model.md, contracts/, quickstart.md.
1 parent b660770 commit 46f4e44

5 files changed

Lines changed: 494 additions & 0 deletions

File tree

Lines changed: 93 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,93 @@
1+
# Contract: Trip Reconstruction
2+
3+
Interfaces this feature exposes/changes. All pure functions are offline, deterministic, and
4+
side-effect-free; UI/store contracts follow the app's existing seams.
5+
6+
## 1. Pure logic (unit-tested)
7+
8+
### `features/travel/tripStops.ts` (NEW)
9+
```ts
10+
// Ordered-stops helpers — immutable, no I/O.
11+
export function addStop(stops: PlaceRef[], place: PlaceRef): PlaceRef[];
12+
export function removeStop(stops: PlaceRef[], index: number): PlaceRef[];
13+
export function moveStop(stops: PlaceRef[], from: number, to: number): PlaceRef[]; // reorder (clamped)
14+
export function endpoints(stops: PlaceRef[]): { from: PlaceRef; to: PlaceRef } | null; // null if <2
15+
```
16+
- `moveStop` clamps indices; a no-op move returns an equal-length array.
17+
- Never mutates the input array.
18+
19+
### `features/travel/distance.ts` (EXTEND)
20+
```ts
21+
export function tripPathKm(
22+
stops: PlaceRef[],
23+
ref: ReferenceData,
24+
): { km: number; unresolvedLegs: number };
25+
// Σ haversineKm over consecutive resolvable stops; a leg touching an unresolvable
26+
// stop adds 0 and increments unresolvedLegs. <2 stops → { km: 0, unresolvedLegs: 0 }.
27+
28+
// tripDistanceKm(trip, ref): if trip.stops?.length >= 2 → tripPathKm(trip.stops).km,
29+
// else the existing from→to distance (unchanged for legacy trips).
30+
// travelTotals: uses the stops path when present.
31+
```
32+
33+
### `features/travel/tripDate.ts` (NEW)
34+
```ts
35+
export type TripDate = string | null; // "YYYY" | "YYYY-MM" | "YYYY-MM-DD" | null
36+
export function parseTripDate(s: TripDate): { year: number; month: number | null; day: number | null } | null;
37+
export function formatTripDate(s: TripDate, locale: string): string; // "2024", "Aug 2024", "12 Aug 2024", ""
38+
export function compareTripDate(a: TripDate, b: TripDate): number; // undated sorts last; year-only orders within its year
39+
export function isValidTripDate(s: string): boolean; // matches ^\d{4}(-\d{2}(-\d{2})?)?$ with real month/day
40+
```
41+
42+
## 2. Schema (`lib/schema/models.ts` + `helpers.ts`)
43+
44+
- `TripSchema` gains `stops: z.array(PlaceRefSchema).min(2).max(200).optional()` using the
45+
transform-before-optional idiom (never injected on parse).
46+
- `TripSchema.date` regex widened to `^\d{4}(-\d{2}(-\d{2})?)?$` (still `.nullable().optional()`).
47+
- `SCHEMA_VERSION` 10 → 11 with the v11 changelog entry (see data-model.md).
48+
- **Contract test**: a v11 multi-stop trip validates; a v10 file (no `stops`, full date) still
49+
validates and round-trips byte-identically (no `stops` key injected).
50+
51+
## 3. Navigation (`lib/store/useUi.ts` + `App.tsx`)
52+
53+
### Composer page layer (NEW)
54+
```ts
55+
// useUi additions (mirror cityPageId/countryPageId):
56+
tripEditId: string | null; // "new" | <tripId> | null
57+
openTripComposer: (id: string | "new") => void; // pushHistory(); set tripEditId
58+
closeTripComposer: () => void; // prefer goBack(); else clear tripEditId
59+
```
60+
- `App.tsx` renders `<TripComposer/>` when `tripEditId` is set (alongside city/country pages), and
61+
`closePages()` also clears `tripEditId` so Escape from the composer leaves the page layer.
62+
- Opening pushes the `{tab, cityPageId, countryPageId, tripEditId}` snapshot; Back/Escape/Android
63+
back close it and return to the launching screen (the Trips tab). *(NavState gains `tripEditId`.)*
64+
65+
### US3 back-navigation fix (CHANGE)
66+
```ts
67+
// TravelScreen airport roll-up row onClick:
68+
// BEFORE: useUi.getState().selectPlace(lon, lat, { kind:"airport", ... })
69+
// AFTER: useUi.getState().openCity(airport.id) // row → airport detail page layer
70+
```
71+
- **Contract**: opening a place from the Travel screen and pressing Back/Escape/Android-back
72+
**once** returns to the Travel list (no map dead-end, no app exit). Verified by e2e.
73+
74+
## 4. Composer ↔ store (`TripComposer.tsx` ↔ `useTrips`)
75+
76+
- On Save: construct `Trip { tripId, name, stops, from: stops[0], to: stops[last], mode, date,
77+
addedAt/updatedAt }` → `useTrips.addTrip(trip)` (new) or `updateTrip(id, patch)` (edit). No visit
78+
writes (FR-008).
79+
- On Cancel/Back: discard; nothing persisted.
80+
- Stop picker: reuse `PlacePicker` / `searchPlaces(ref, q)` filtered to `kind ∈ {airport, city}`.
81+
82+
## 5. i18n
83+
84+
New keys under `trip.*` / `trip.compose.*` / `trip.date.*` in `en/fr/ko.ts` with compile-time
85+
parity (en is the source of the `MessageKey` type). All composer controls carry `aria-label`/
86+
`title`; reorder controls are keyboard-operable buttons (not drag-only).
87+
88+
## 6. Invariants / edge behavior
89+
90+
- `stops.length < 2` ⇒ not savable as a reconstructed trip (from/to undefined); composer disables Save.
91+
- Unresolvable stop ⇒ its legs are skipped in the total; the composer shows "some legs unmeasured".
92+
- Legacy single-leg trips (no `stops`) render and total exactly as before.
93+
- Everything offline: no network call in any of the above (e2e asserts zero outbound requests).
Lines changed: 73 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,73 @@
1+
# Phase 1 Data Model: Trip Reconstruction
2+
3+
Extends the existing `Trip` (Travel Log) additively. Source of truth: `apps/postcards/src/lib/
4+
schema/models.ts` (Zod → TS types + published JSON Schema). Schema version: **10 → 11**.
5+
6+
## Entity: Trip (extended)
7+
8+
The existing single-leg `Trip` gains an optional ordered `stops` array and a wider `date`. Fields
9+
unchanged unless noted.
10+
11+
| Field | Type | Notes |
12+
|-------|------|-------|
13+
| `tripId` | `idString` (1–100 chars) | unchanged |
14+
| `name` | `string ≤80`, sanitized, optional | unchanged (folder label / trip title) |
15+
| `from` | `PlaceRef` (required) | **For a multi-stop trip = `stops[0]`.** Kept required for backward-compat: old readers still see a leg. |
16+
| `to` | `PlaceRef` (required) | **For a multi-stop trip = `stops[last]`.** |
17+
| `stops` | `PlaceRef[]`, optional, **min 2 when present, max 200** | **NEW.** The ordered chain of waypoints. Present ⇒ multi-stop journey; absent ⇒ legacy single-leg. `from`/`to` MUST equal first/last stop when present. |
18+
| `mode` | `TravelMode` enum, default `"flight"` | unchanged |
19+
| `date` | `string \| null`, optional | **WIDENED** regex `^\d{4}(-\d{2}(-\d{2})?)?$` — accepts `YYYY`, `YYYY-MM`, or `YYYY-MM-DD`. Still nullable/optional (undated allowed). |
20+
| `carrier` | `string ≤120 \| null` | unchanged |
21+
| `note` | `string ≤2000 \| null` | unchanged |
22+
| `addedAt` | ISO datetime | unchanged |
23+
| `updatedAt` | ISO datetime, optional | unchanged (sync stamp) |
24+
25+
**Validation rules**:
26+
- `stops`, when present: length ∈ [2, 200]; every element a valid `PlaceRef`; `from` deep-equals
27+
`stops[0]` and `to` deep-equals `stops[last]` (enforced by the writer, not a cross-field Zod
28+
refine unless cheap — the composer guarantees it; import validates shape only, inert).
29+
- `stops` uses `.optional()` with the transform-before-optional idiom (as `name` does) so the key
30+
is **never injected on parse** — v1–v10 files round-trip byte-identically and don't gain a `stops`
31+
key.
32+
- `date`: the widened regex is a **relaxation** — every previously-valid value still validates.
33+
34+
**Stop = `PlaceRef`** (reused, `models.ts:27`): `{ kind, id, name, countryId, lat?, lon?, population? }`.
35+
MVP stops are `kind: "airport" | "city"`; coordinates are **resolved from reference data** at
36+
compute time (`coordsOf`), not stored (airports/cities have no need). The kind-agnostic `PlaceRef`
37+
lets a future `"station"` kind slot in (D6).
38+
39+
## Derived (never stored)
40+
41+
- **Total distance (km)**: `tripPathKm(stops, ref)` = Σ `haversineKm(coordsOf(stops[i]),
42+
coordsOf(stops[i+1]))` over consecutive **resolvable** pairs; returns `{ km, unresolvedLegs }`.
43+
A leg touching an unresolvable stop contributes 0 and increments `unresolvedLegs`. For a legacy
44+
trip (no `stops`), distance stays `tripDistanceKm(from, to)`.
45+
- **Endpoints for display/map**: `from`/`to` (already the first/last stop).
46+
47+
## Top-level file (`PostcardsFileSchema`) — unchanged shape
48+
49+
`trips: z.array(TripSchema).max(200_000).optional().default([])` already exists (v2). No new
50+
top-level array. Only `TripSchema` grows and `SCHEMA_VERSION` bumps.
51+
52+
## Versioning
53+
54+
`SCHEMA_VERSION: 10 → 11`. New changelog entry in `helpers.ts`:
55+
56+
> v11 adds an optional ordered `stops` array on a trip (multi-stop journey reconstruction) and
57+
> widens a trip's `date` to accept a year (`YYYY`) or month (`YYYY-MM`), not only a full day.
58+
> Both are additive/relaxing: v1–v10 files validate and round-trip unchanged (`stops` is never
59+
> injected on parse; the date regex only accepts *more*). `from`/`to` mirror the first/last stop,
60+
> so an older build reading a v11 multi-stop trip still sees a valid `from → to` leg.
61+
62+
**Backward/forward compatibility**:
63+
- Old file → new app: no `stops`, full `date` ⇒ legacy single-leg trip (unchanged behavior). ✅
64+
- New file → old app: unknown behavior guarded by the version bump's "update the app" prompt; if
65+
parsed leniently, the trip still reads as `from → to` (endpoints present). ✅
66+
- Round-trip: files without `stops` never gain the key. ✅
67+
68+
## State transitions (composer session, transient)
69+
70+
`draft` (in the composer) → add/remove/reorder stops → on **Save**: build `Trip` with `stops`,
71+
`from = stops[0]`, `to = stops[last]`, `name`, `date`, `mode`, stamps → `useTrips.addTrip` /
72+
`updateTrip` (writes IndexedDB + tombstone rules unchanged). **Cancel/Back** discards the draft.
73+
No visit records are created or changed (FR-008, pure summary).
Lines changed: 143 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,143 @@
1+
# Implementation Plan: Trip Reconstruction (retrospective journeys)
2+
3+
**Branch**: `019-trip-reconstruction` (developed on `claude/journal-redesign-spec-kit-ku0l3d`) | **Date**: 2026-07-21 | **Spec**: [spec.md](./spec.md)
4+
5+
**Input**: Feature specification from `/specs/019-trip-reconstruction/spec.md`
6+
7+
## Summary
8+
9+
Evolve the Travel screen's trip log so a user can **reconstruct a past journey as an ordered
10+
chain of stops** (airports + cities), see its **total great-circle distance** live, and have it
11+
count toward the Travel totals — a fast, approximate "here's what I did," never a planner. The
12+
existing single-leg `Trip` gains an **additive, optional `stops` array** (first/last stop mirror
13+
the existing required `from`/`to`, so old app builds still read new trips as a simple leg), plus a
14+
looser **approximate date** (month or year). A dedicated **composer page layer** hosts the builder
15+
(add/remove/reorder stops, name, rough date, running km). Separately, fix the **Travel back bug**:
16+
tapping an airport in the roll-up jumps to the map and opens a popup card, so the first Back only
17+
dismisses the card and strands the user on the map — re-route the row to the airport's **detail
18+
page layer** (row → details, per the app's own rule) so a single Back returns to the Travel list.
19+
Reuses the existing `haversineKm`/`coordsOf` helpers, `searchPlaces`/`PlacePicker`, `useTrips`
20+
store + `tripsDb`, and the `cityPageId`/`countryPageId` page-layer + `history`/`goBack` model.
21+
22+
## Technical Context
23+
24+
**Language/Version**: TypeScript 5 + React 19 (Vite), PWA + Capacitor (iOS/Android).
25+
26+
**Primary Dependencies**: Zustand (stores), Zod (schema → JSON Schema), MapLibre GL (map only —
27+
not used for distance), existing `features/travel/distance.ts` (`haversineKm`, `coordsOf`,
28+
`travelTotals`, `tripArcs`). No new runtime dependency.
29+
30+
**Storage**: IndexedDB working store (`lib/db/tripsDb`, via `useTrips`); canonical portable
31+
**JSON** file validated by `lib/schema/models.ts` (`PostcardsFileSchema`, current
32+
`SCHEMA_VERSION = 10`). Trips already persist in the `trips` array (additive since schema v2).
33+
34+
**Testing**: Vitest (pure logic: distance, date parsing, stops validation, schema round-trip) +
35+
Playwright/axe (composer flow, offline zero-egress, back-navigation, WCAG 2.1 AA). Existing gate:
36+
`pnpm typecheck && pnpm test && pnpm test:e2e`.
37+
38+
**Target Platform**: Web (self-hostable PWA) + native iOS/Android via Capacitor. Offline-first.
39+
40+
**Project Type**: Single web app (`apps/postcards/`), feature-foldered.
41+
42+
**Performance Goals**: Composer interactions feel instantaneous; distance recompute on
43+
add/remove/reorder is O(stops) haversine calls — trivially <16ms for realistic trips.
44+
45+
**Constraints**: Fully offline; zero network egress; no maps/routing/geocoding service (distance
46+
is pure haversine on-device); aggregator-only (no invented reference data); additive schema
47+
(older files + existing single-leg trips stay valid); WCAG 2.1 AA + keyboard-first; i18n parity
48+
en/fr/ko enforced at compile time.
49+
50+
**Scale/Scope**: One new page-layer composer + a store/schema evolution + a small nav fix. Trips
51+
per file bounded by the existing `.max(200_000)`; stops per trip bounded (e.g. ≤200).
52+
53+
## Constitution Check
54+
55+
*GATE: must pass before Phase 0 and re-checked after Phase 1 design.*
56+
57+
| Principle | Assessment |
58+
|-----------|------------|
59+
| **I. Aggregator, never an author** | ✅ Stops reference existing reference places (airports/cities) resolved from named datasets; the app invents no coordinates or place facts. Railway stations are **deferred** precisely because no openly-licensed dataset ships — they will arrive as a separate shareable dataset, never hard-wired. |
60+
| **II. Local-first & decentralized** | ✅ No server, account, or network. Trips live on-device (IndexedDB) + the portable file. |
61+
| **III. Privacy by default** | ✅ No telemetry, no egress. Trips leave the device only via the existing explicit export. Distance is computed locally. |
62+
| **IV. One portable, human-readable file** | ✅ Trips stay in the single JSON file; the multi-stop shape is **additive + versioned** (schema bump), export/re-import lossless, Markdown export unaffected. |
63+
| **V. Zero lock-in** | ✅ No new proprietary/cloud dependency; no new runtime dep at all. Great-circle math is local. |
64+
| **VI. Security — data is inert** | ✅ Stops are inert `PlaceRef`s validated by Zod on import; no executable content; sanitized name/date; strict schema rejects unknown fields. |
65+
| **VII. Efficient, accessible, keyboard-first** | ✅ Composer is keyboard-operable (add/remove/**reorder via buttons**, not drag-only), WCAG 2.1 AA, tooltips/aria on controls, reduced-motion respected; the nav fix removes a dead-end. |
66+
| **VIII. Interoperable & AI-friendly** | ✅ Additive versioned schema; new `stops` documented; old readers still parse new trips as a `from→to` leg (graceful degradation). |
67+
| **Scope discipline (NON-NEGOTIABLE)** | ✅ **This is retrospective reconstruction — remembering a journey already taken — NOT trip planning.** No routing, no future itineraries, no booking, no suggestions of where to go. It records "what I did + how far," squarely inside "store data and display it well." Framed and named to avoid any planner drift. |
68+
69+
**Gate result: PASS.** No violations; Complexity Tracking not required.
70+
71+
## Project Structure
72+
73+
### Documentation (this feature)
74+
75+
```text
76+
specs/019-trip-reconstruction/
77+
├── plan.md # This file
78+
├── research.md # Phase 0 — decisions (schema shape, date encoding, nav fix, stations)
79+
├── data-model.md # Phase 1 — Trip.stops, approximate date, derived distance, versioning
80+
├── contracts/
81+
│ └── trip-reconstruction.md # Phase 1 — pure fns + store + nav contract
82+
├── quickstart.md # Phase 1 — how to validate end-to-end
83+
├── checklists/
84+
│ └── requirements.md # (from /speckit-specify)
85+
└── tasks.md # Phase 2 — /speckit-tasks (NOT created here)
86+
```
87+
88+
### Source Code (repository root)
89+
90+
```text
91+
apps/postcards/
92+
├── src/
93+
│ ├── features/
94+
│ │ └── travel/
95+
│ │ ├── TravelScreen.tsx # + entry point to the composer; roll-up row → details (nav fix)
96+
│ │ ├── TripComposer.tsx # NEW — full-page multi-stop builder (page layer)
97+
│ │ ├── TripForm.tsx # existing single-leg add/edit (kept; may share PlacePicker)
98+
│ │ ├── PlacePicker.tsx # reused for each stop (aggregator-only search)
99+
│ │ ├── distance.ts # + tripPathKm(stops, ref); travelTotals honors stops
100+
│ │ ├── tripDate.ts # NEW — parse/format/compare approximate dates (YYYY | YYYY-MM | YYYY-MM-DD)
101+
│ │ └── tripStops.ts # NEW — pure helpers: reorder/add/remove, endpoints, validation
102+
│ │ └── map/
103+
│ │ └── MapScreen.tsx / MapView.tsx # optional: tripArcs draws each leg (nice-to-have)
104+
│ ├── lib/
105+
│ │ ├── schema/models.ts # TripSchema += optional stops[]; date regex widened; SCHEMA_VERSION → 11
106+
│ │ ├── schema/helpers.ts # SCHEMA_VERSION bump + changelog entry
107+
│ │ ├── store/useTrips.ts # unchanged shape (stores richer Trip); no API break
108+
│ │ ├── store/useUi.ts # + tripEditId page-layer state (open/close, pushes history)
109+
│ │ └── i18n/{en,fr,ko}.ts # new composer/date/nav strings, parity
110+
│ └── styles.css # composer + stop-row styles (≥44px targets)
111+
└── tests/
112+
├── unit/
113+
│ ├── tripPathKm.spec.ts # NEW — multi-stop distance, unresolved-stop skip
114+
│ ├── tripDate.spec.ts # NEW — approximate date parse/format/sort
115+
│ ├── tripStops.spec.ts # NEW — reorder/add/remove/endpoints
116+
│ └── schema round-trip # extend: new trip validates; old file still valid
117+
└── e2e/
118+
└── trip-reconstruction.spec.ts # NEW — build multi-stop trip, live km, back-from-airport, offline, a11y
119+
```
120+
121+
**Structure Decision**: Single web app, feature-foldered under `apps/postcards/src/features/travel/`.
122+
The composer is a **page layer** (new `useUi.tripEditId`) rendered over the Trips tab in
123+
`App.tsx`, mirroring `cityPageId`/`countryPageId` so Back/Escape/`goBack` behavior is inherited and
124+
consistent — this both delivers the "dedicated page" and underpins the US3 navigation fix.
125+
126+
## Phase notes
127+
128+
- **Phase 0 (research.md)** resolves: (a) multi-stop schema shape — additive `stops[]` with
129+
`from`/`to` mirrored to first/last for backward-compat vs. a new entity (chosen: additive
130+
`stops[]`); (b) approximate-date encoding (widen the existing `date` string to accept
131+
`YYYY`/`YYYY-MM`/`YYYY-MM-DD`); (c) distance model (great-circle sum, unresolved-stop skip);
132+
(d) the US3 nav-fix approach (row → airport **detail page layer**, not the map popup) and how
133+
the airport detail page is reached (`openCity` with the IATA id / the intra-city-places path
134+
from feature 014) — verified during implementation; (e) confirming **no station dataset** exists
135+
and the deferral is documented; (f) no new dependencies.
136+
- **Phase 1** emits `data-model.md` (the `Trip.stops` shape, approximate date, derived distance,
137+
`SCHEMA_VERSION` bump + backward-compat rules), `contracts/trip-reconstruction.md` (the pure
138+
functions `tripPathKm`/`tripStops`/`tripDate`, the `useUi.tripEditId` nav contract, and the
139+
composer↔store contract), and `quickstart.md` (end-to-end validation incl. offline + back-nav).
140+
141+
## Complexity Tracking
142+
143+
No constitutional violations; no deviations from ratified tech defaults. Section intentionally empty.

0 commit comments

Comments
 (0)