feat(trail-edit): auto-fill basic info from the route (#49 part 2) #54

Closed
maximus wants to merge 0 commits from feat/49-basic-info-autofill into deploy
Member

Part 2 of #49 (the "Basic info" items on /trail/edit/…). Part 1 (map, profile, stats overlay, design) is a separate PR; this one stays inside the Basic-info form section and keeps the logic in new modules so the two merge cleanly.

What changes

Persist estimated pace stats

Once the pace estimator has a result, a Use pace estimate button appears in the Basic-info header. It copies the personal moving time into Est. duration, and the estimator's LiDAR-corrected D+/D− into Elevation gain/loss. Distance stays the router's, which is exact for the drawn geometry. The copied values survive stop drawing (which recomputes the totals) until the route itself changes.

Auto-fill name and location

  • Name: "<start> – <end>", or "<start> loop" (i18n key trail-name-loop) when start and end are ≤ LOOP_THRESHOLD_METERS = 200 m apart. Place = named peak, pass or hut when the point is on one, else the most local settlement (hamlet → village → suburb → town → city → municipality → county → state). If both ends geocode to the same place, the name is just that place.

  • Location: the reverse-geocoded start (same full label as before: "Town, State, Country").

  • Ownership: the auto-fill only touches a text field that is empty or still shows its last auto value. Typing claims the field; clearing it hands it back. Route changes re-fill untouched fields.

  • Geocoder: reuses the existing /api/v1/geocoding/reverse proxy (Nominatim). Calls are debounced 1 s after the last route change and cached per ~110 m cell (toFixed(3)), so editing the middle of a route never re-queries its ends. Stale answers are dropped. A failure only logs a warning.

  • Placeholder names from uploads: isPlaceholderTrailName (pure and unit-tested) marks a name from an uploaded file as replaceable when it is clearly not a chosen name. It matches:

    • filenames (*.gpx/.fit/.tcx/.kml/.kmz/.geojson/.igc) and wanderer's own trail-<ISO date> fallback
    • numbered defaults (Activity_1234567, Track 001, Recording-12, Activité 3) and Current Track: …
    • date-only names (2026-11-05 09:12, 05.11.2026, 05 NOV 2026 09:12)
    • Strava time-of-day defaults in EN/FR/DE/IT (Morning Run, Course à pied le matin, Morgenlauf, Corsa mattutina)
    • Garmin defaults: a bare activity (Hiking, Trail Running) always counts. <X> <Activity> / <X> - <Activity> counts only when X is a locality of the reverse-geocoded start: its short place, hamlet, village, suburb, town, city or municipality, compared case-, accent- and hyphen-insensitively. So Sospel Running starting in Sospel is replaced, but Gorges du Verdon Hiking starting in Castellane is kept. If the lookup fails, the name is also kept.

    It stays conservative: anything else counts as a real name, and the tests cover names that must survive, such as GR 52, Route 66, Morning Run to the Col de Braus, Mont Agel 2026-11-05, Tour du Mont Blanc Hiking and Gorges du Verdon Hiking. A replaceable name is overwritten only by a successful geocode, so it stays if the lookup fails, and any edit by the user claims it.

  • Behaviour change (kept as decided): stop drawing and upload file used to overwrite Location unconditionally (also on existing trails). They now go through the same "only if empty or untouched" rule.

Auto-choose difficulty and category

Pure module web/src/lib/util/trail_heuristics.ts; the criteria are documented in its header:

Track metrics

  • Gradients are measured over non-overlapping windows of ≥ 100 m horizontal distance, so DEM noise does not create spikes.
  • maxGrade is the steepest window, up or down.
  • avgClimbGrade is the climb divided by the horizontal length of the uphill windows.
  • Moving speed counts only point pairs ≤ 5 min apart and moving ≥ 1 km/h. It is used only for uploaded recordings, because drawn routes carry synthetic router timestamps.

Category (first match wins)

  1. Recorded track: raw moving speed ≥ 15 km/h → Biking. Effort speed ((km + D+/100) per moving hour) ≥ 8 → Running.
  2. Route drawn with the bicycle router profile → Biking.
  3. No usable recorded speed (a drawn route, or a file without timestamps) and the pace estimator in run mode → Running. Toggling run/hike re-evaluates the category while it is still a suggestion.
  4. On foot (hike mode): ≤ 8 km, D+ ≤ 200 m, max gradient < 15 % and SAC ≤ T1 (or unknown) → Walking; anything else → Hiking.
  • Climbing, Skiing, Canoeing and Other are never guessed.
  • Names are matched against categories by canonical or English name. Fallbacks: Walking → Hiking, Running → Hiking, Hiking → Walking. If nothing matches, the current default stays. Subcategory is reset to none; subcategory suggestions are deferred to a later PR.

Difficulty

  • Effort km = km + D+/100 on foot, km/4 + D+/100 by bike: < 12 → easy, < 25 → moderate, otherwise difficult.
  • Steepness floor: max gradient ≥ 25 % or average climb gradient ≥ 15 % → at least moderate; max gradient ≥ 40 % → difficult.
  • SAC floor (input ready for BRouter path tags, #5): T3 → at least moderate, T4+ → difficult.

The suggestions apply only while the user has not chosen: for new trails, and not for duplicates or existing trails. Picking a difficulty or category stops them. A small hint under the fields says when the shown values are suggestions.

Also

Fixed the hidden elevation_loss input in read-only Basic info. It posted elevation_gain under the wrong name.

Files

  • web/src/lib/util/trail_heuristics.ts (+ test): metrics, category/difficulty rules, DB name mapping
  • web/src/lib/util/trail_autofill.ts (+ test): loop detection, name formatting, place-name picking, field ownership, pace-stat mapping, cached geocoder, debounce
  • web/src/lib/stores/search_store.ts: reverse result gains a short place and its localities
  • web/src/routes/trail/edit/[id]/+page.svelte: glue (one block after handleCategoryChange) + Basic-info markup
  • web/src/lib/i18n/locales/en.json: 6 keys

Tests

  • npm run check: 0 errors. The 2 warnings were already there (pace-splits <tbody> a11y, not in this diff).
  • npm run test:unit -- --run: 73 files passed, 973 tests passed, 13 skipped. That includes 139 new tests in trail_heuristics.test.ts and trail_autofill.test.ts.
  • Locally, vitest also reports 1 unhandled error (ERR_INVALID_STATE, undici stream) from src/lib/server/trail_analyze.test.ts. That file is untouched here, and the error doesn't happen in CI (the web job passed for the first commit).

Refs #49 (part 2; does not close it).

https://claude.ai/code/session_01XMf4EGfBC9xbQ6rjD6HxgP

🤖 Generated with Claude Code

Part 2 of #49 (the "Basic info" items on `/trail/edit/…`). Part 1 (map, profile, stats overlay, design) is a separate PR; this one stays inside the Basic-info form section and keeps the logic in new modules so the two merge cleanly. ## What changes ### Persist estimated pace stats Once the pace estimator has a result, a **Use pace estimate** button appears in the Basic-info header. It copies the personal moving time into *Est. duration*, and the estimator's LiDAR-corrected D+/D− into *Elevation gain/loss*. Distance stays the router's, which is exact for the drawn geometry. The copied values survive *stop drawing* (which recomputes the totals) until the route itself changes. ### Auto-fill name and location - **Name**: `"<start> – <end>"`, or `"<start> loop"` (i18n key `trail-name-loop`) when start and end are ≤ `LOOP_THRESHOLD_METERS` = **200 m** apart. Place = named peak, pass or hut when the point is on one, else the most local settlement (hamlet → village → suburb → town → city → municipality → county → state). If both ends geocode to the same place, the name is just that place. - **Location**: the reverse-geocoded start (same full label as before: "Town, State, Country"). - **Ownership**: the auto-fill only touches a text field that is empty or still shows its last auto value. Typing claims the field; clearing it hands it back. Route changes re-fill untouched fields. - **Geocoder**: reuses the existing `/api/v1/geocoding/reverse` proxy (Nominatim). Calls are debounced 1 s after the last route change and cached per ~110 m cell (`toFixed(3)`), so editing the middle of a route never re-queries its ends. Stale answers are dropped. A failure only logs a warning. - **Placeholder names from uploads**: `isPlaceholderTrailName` (pure and unit-tested) marks a name from an uploaded file as replaceable when it is clearly not a chosen name. It matches: - filenames (`*.gpx/.fit/.tcx/.kml/.kmz/.geojson/.igc`) and wanderer's own `trail-<ISO date>` fallback - numbered defaults (`Activity_1234567`, `Track 001`, `Recording-12`, `Activité 3`) and `Current Track: …` - date-only names (`2026-11-05 09:12`, `05.11.2026`, `05 NOV 2026 09:12`) - Strava time-of-day defaults in EN/FR/DE/IT (`Morning Run`, `Course à pied le matin`, `Morgenlauf`, `Corsa mattutina`) - Garmin defaults: a bare activity (`Hiking`, `Trail Running`) always counts. `<X> <Activity>` / `<X> - <Activity>` counts **only when X is a locality of the reverse-geocoded start**: its short place, hamlet, village, suburb, town, city or municipality, compared case-, accent- and hyphen-insensitively. So `Sospel Running` starting in Sospel is replaced, but `Gorges du Verdon Hiking` starting in Castellane is kept. If the lookup fails, the name is also kept. It stays conservative: anything else counts as a real name, and the tests cover names that must survive, such as `GR 52`, `Route 66`, `Morning Run to the Col de Braus`, `Mont Agel 2026-11-05`, `Tour du Mont Blanc Hiking` and `Gorges du Verdon Hiking`. A replaceable name is overwritten only by a successful geocode, so it stays if the lookup fails, and any edit by the user claims it. - **Behaviour change** (kept as decided): *stop drawing* and *upload file* used to overwrite **Location** unconditionally (also on existing trails). They now go through the same "only if empty or untouched" rule. ### Auto-choose difficulty and category Pure module `web/src/lib/util/trail_heuristics.ts`; the criteria are documented in its header: **Track metrics** - Gradients are measured over non-overlapping windows of ≥ 100 m horizontal distance, so DEM noise does not create spikes. - `maxGrade` is the steepest window, up or down. - `avgClimbGrade` is the climb divided by the horizontal length of the uphill windows. - Moving speed counts only point pairs ≤ 5 min apart and moving ≥ 1 km/h. It is used only for uploaded recordings, because drawn routes carry synthetic router timestamps. **Category** (first match wins) 1. Recorded track: raw moving speed ≥ 15 km/h → **Biking**. Effort speed ((km + D+/100) per moving hour) ≥ 8 → **Running**. 2. Route drawn with the bicycle router profile → **Biking**. 3. No usable recorded speed (a drawn route, or a file without timestamps) and the pace estimator in **run** mode → **Running**. Toggling run/hike re-evaluates the category while it is still a suggestion. 4. On foot (hike mode): ≤ 8 km, D+ ≤ 200 m, max gradient < 15 % and SAC ≤ T1 (or unknown) → **Walking**; anything else → **Hiking**. - Climbing, Skiing, Canoeing and Other are never guessed. - Names are matched against `categories` by canonical or English name. Fallbacks: Walking → Hiking, Running → Hiking, Hiking → Walking. If nothing matches, the current default stays. Subcategory is reset to none; subcategory suggestions are deferred to a later PR. **Difficulty** - Effort km = km + D+/100 on foot, km/4 + D+/100 by bike: < 12 → easy, < 25 → moderate, otherwise difficult. - Steepness floor: max gradient ≥ 25 % or average climb gradient ≥ 15 % → at least moderate; max gradient ≥ 40 % → difficult. - SAC floor (input ready for BRouter path tags, #5): T3 → at least moderate, T4+ → difficult. The suggestions apply only while the user has not chosen: for new trails, and not for duplicates or existing trails. Picking a difficulty or category stops them. A small hint under the fields says when the shown values are suggestions. ### Also Fixed the hidden `elevation_loss` input in read-only Basic info. It posted `elevation_gain` under the wrong name. ## Files - `web/src/lib/util/trail_heuristics.ts` (+ test): metrics, category/difficulty rules, DB name mapping - `web/src/lib/util/trail_autofill.ts` (+ test): loop detection, name formatting, place-name picking, field ownership, pace-stat mapping, cached geocoder, debounce - `web/src/lib/stores/search_store.ts`: reverse result gains a short `place` and its `localities` - `web/src/routes/trail/edit/[id]/+page.svelte`: glue (one block after `handleCategoryChange`) + Basic-info markup - `web/src/lib/i18n/locales/en.json`: 6 keys ## Tests - `npm run check`: 0 errors. The 2 warnings were already there (pace-splits `<tbody>` a11y, not in this diff). - `npm run test:unit -- --run`: 73 files passed, 973 tests passed, 13 skipped. That includes 139 new tests in `trail_heuristics.test.ts` and `trail_autofill.test.ts`. - Locally, vitest also reports 1 unhandled error (`ERR_INVALID_STATE`, undici stream) from `src/lib/server/trail_analyze.test.ts`. That file is untouched here, and the error doesn't happen in CI (the web job passed for the first commit). Refs #49 (part 2; does not close it). https://claude.ai/code/session_01XMf4EGfBC9xbQ6rjD6HxgP 🤖 Generated with [Claude Code](https://claude.com/claude-code)
feat(trail-edit): auto-fill basic info from the route (#49)
Some checks failed
CI / web (push) Successful in 1m29s
CI / go (push) Has been cancelled
1cfab50a86
- Add a "Use pace estimate" button that copies the estimator's moving
  time and D+/D- into the Basic-info fields (kept until the route changes).
- Suggest the name ("<start> – <end>" or "<start> loop", loop = ends
  <= 200 m apart) and location from the reverse-geocoded start/end,
  debounced and cached per ~110 m cell; only empty or untouched fields
  are filled, and typing claims a field.
- Pre-select difficulty and category from track heuristics (effort km,
  max/avg climb gradient, recorded speed, routing profile, SAC floor)
  in the pure, tested trail_heuristics module, mapped to the DB
  categories with fallbacks; only while the user has not chosen.
- Fix the read-only elevation_loss hidden input posting elevation_gain.

Refs #49

Claude-Session: https://claude.ai/code/session_01XMf4EGfBC9xbQ6rjD6HxgP
Co-Authored-By: Claude Opus 5.5 <[email protected]>
feat(trail-edit): replace placeholder GPX names, use pace mode for category
Some checks failed
CI / go (push) Has been cancelled
CI / web (push) Has been cancelled
1453ea2bdc
- Treat filename-like and device/app default names from uploaded files
  ("Morning_Run.gpx", "Activity_123", "Track 001", "Current Track: …",
  date-only names, Strava EN/FR/DE/IT and Garmin defaults) as unfilled,
  so the route-based name replaces them. Detection is a narrow, pure,
  unit-tested function; anything unrecognised is kept.
- For drawn routes (no recorded speed), the pace estimator's run/hike
  mode decides Running vs the walk/hike rule; recorded tracks keep the
  speed rule and bicycle routing still wins.

Refs #49

Claude-Session: https://claude.ai/code/session_01XMf4EGfBC9xbQ6rjD6HxgP
Co-Authored-By: Claude Opus 5.5 <[email protected]>
fix(trail-edit): only treat Garmin names as placeholders at their start locality
All checks were successful
CI / web (push) Successful in 1m49s
CI / go (push) Successful in 14m28s
065230cac9
Garmin names activities "<start locality> <Activity>". Treat such a name
as a placeholder only when its prefix matches a locality of the
reverse-geocoded start (case-, accent- and hyphen-insensitive; short
place, hamlet, village, suburb, town, city, municipality). Without a
match, or when the lookup fails, the name is kept, so "Gorges du Verdon
Hiking" starting in Castellane survives. A bare activity ("Hiking")
stays a placeholder.

Refs #49

Claude-Session: https://claude.ai/code/session_01XMf4EGfBC9xbQ6rjD6HxgP
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Author
Member

Shipped via batch PR #64 (deploy 0d0d85a4), which merged this branch head unchanged; live since 2026-11-05 ~19:30 CET in wanderer-web:deploy-676a7c62 (homelab-flux #843). Forgejo does not mark stacked PRs as merged, so I am closing this by hand.

🤖 Generated with Claude Code

Shipped via batch PR #64 (`deploy` 0d0d85a4), which merged this branch head unchanged; live since 2026-11-05 ~19:30 CET in `wanderer-web:deploy-676a7c62` (homelab-flux #843). Forgejo does not mark stacked PRs as merged, so I am closing this by hand. 🤖 Generated with [Claude Code](https://claude.com/claude-code)
maximus closed this pull request 2026-11-05 19:10:43 +00:00
All checks were successful
CI / web (push) Successful in 1m49s
Required
Details
CI / go (push) Successful in 14m28s
Required
Details

Pull request closed

Sign in to join this conversation.
No reviewers
No milestone
No project
No assignees
2 participants
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Dependencies

No dependencies set

Reference
public/wanderer!54
No description provided.