Compare commits

...

62 Commits

Author SHA1 Message Date
Maurice f4e524f3c3 place-enrichment: the details lookup is a standalone cache fill
The service reads a community place's details before the result cache and
every other place's after it, so the lookup has two call sites of which one
runs. It only fills the details row cache and turns a failure into no
details, so it is tagged @txStandalone and the enrich baseline drops to the
four writes it holds without it.
2026-10-31 06:45:13 +00:00
Maurice 682ae19143 test(place-enrichment): a cached OSM place still reads its details for the community version
An OSM element can hold community values, so the service reads its details
before the cache to learn the version it is served under. The second request
reads them once and then answers from the row cache without another lookup.
2026-10-31 06:27:31 +00:00
Maurice 255607b750 place-contrib: format the settle filters of the outbox repository
The id and cid lists the settle writes match on come from two small helpers,
which keeps each filter on one line in Prettier's layout.
2026-10-31 06:27:31 +00:00
Maurice ce7437a46f i18n: translate the place sharing, services card and refresh pill strings into Hebrew
The Hebrew locale arrived on dev while this branch was open, so its 80 new
admin.contribute, admin.servicesCard and places.refresh keys were missing
there.
2026-10-31 03:25:56 +00:00
Maurice 36d8cc2e7b wiki: the New place details pill offers the description too 2026-10-31 03:25:56 +00:00
Maurice dc76efc418 admin: a withdrawal that went through is reported even when the state re-read fails 2026-10-31 03:25:56 +00:00
Maurice 314b087f98 planner: the refresh pill compares with the place picked anew in the search box
After another place was picked while editing, the pill still offered the
saved place's details and would have written them onto the new one.
2026-10-31 03:25:56 +00:00
Maurice 2f689ea9ca maps: stop reading a community picture at its size cap
An answer without a content-length was buffered whole before its size was
checked. The read now stops at the cap.
2026-10-31 03:25:56 +00:00
Maurice 41edbcf67a maps: validate the community values and OSM elements the TREK Places API answers
Both answers were taken as typed. A value outside the published shape, such
as hours that are no text, reached the hours parser and failed the details
request. A place outside the shape is now left out of /v1/community, and an
element outside it sends the lookup to Overpass.
2026-10-31 03:25:56 +00:00
Maurice 6945b53c10 place-enrichment: a community summary the request carried stays out of the shared cache
Like an OpenStreetMap summary, a summary credited to the community is read
straight off the request's details, so any caller could have it served to
every user of the instance for a week under the community's name.
2026-10-31 03:25:56 +00:00
Maurice 7ade99c8ce place-contrib: audit a switch-off whose withdrawal the service did not confirm
Switching sharing off commits before the withdrawal asks the service. When
the service did not confirm, the decision had taken effect but left no audit
row. It is now audited with withdrawFailed, and the admin still gets the
error.
2026-10-31 03:25:56 +00:00
Maurice 593df53993 places: a picture route records the origin of the picture only
The upload and the trip-file routes vouched for every field that changed
between their read and their answer. A website the assistant or a
collaborator changed while a large picture uploaded was then recorded as
typed by the user and queued for the TREK Places API. Those writers now name
the one field they write, and other changes keep the origin their own writer
recorded.
2026-10-31 03:25:56 +00:00
Maurice aa41c67a20 place-contrib: settle a sent value only while its queue row still holds it
A value saved while the request for its predecessor was out rewrote the same
outbox row with a new cid; the answer for the old value then deleted the row,
or charged it an attempt, and the newer value was never sent. The settle
writes now match the cid that was sent as well as the id, so such a row stays
queued for the next run. A replaced value also counts its age from the
replacement, so a long pause cannot expire a value queued days ago.
2026-10-31 03:25:56 +00:00
Maurice c10a698b9f planner: keep a place's enrichment in the tab for ten minutes, not for good
A saved place reopened for editing has no community version in its key, so
the answer the tab kept the first time stayed until the tab closed: a picture
another installation contributed since never showed. Kept answers now carry
when they were fetched and are asked again after ten minutes, the same span
the server keeps an empty answer. The key version moves to 5 so open tabs drop
what they kept in the old shape.
2026-10-31 03:25:56 +00:00
Maurice e2756dab22 places: a picture another installation contributed shows on the next edit
Two gaps kept it out. The service writes absolute picture URLs on its own
host, and the community service only took relative paths, so every picture
was dropped; it now takes the path of a URL on the configured service and
nothing from another host. And a saved place opened for editing sends no
details, so no community version, and the cached answer kept for a week; for
an index or OSM place the details are now read before the cache, so a new
version is a new answer.
2026-10-31 03:25:56 +00:00
Maurice 330644e88b places: show the community's published pictures first in Pick a picture
The service delivers the pictures review approved for a place, but TREK never
read them. A new TrekCommunityService in the maps domain asks the TREK Places
API for them (the index row for a gers place, /v1/community for an OSM one),
accepts only paths of the service's picture store, and fetches the bytes with
the installation's key, capped at 4 MB. Enrichment puts them ahead of Google
and Commons, through the same photo cache, credited as TREK Community under
CC BY 4.0. The enrichment cache now follows the community version for OSM
places too, so a newly approved picture shows on the next open.

Also lowers the client's no-non-null-assertion baseline to 380: moving Use
this text into the description card removed two.
2026-10-31 03:25:56 +00:00
Maurice 0b86a13b51 admin: fold the transmission log to its newest five rows
A busy log pushed the rest of the card down. It shows the newest five rows,
a Show more toggle opens the rest, and the page buttons appear once it is
open.
2026-10-31 03:25:56 +00:00
Maurice 8d8629516b places: offer a newer description in the refresh pill
The pill compared website, phone, e-mail and hours only, so a description
the community published never showed up on a saved place. It now reads the
index description or the OSM summary, compares it as plain words against
the editor's markup, and shows it clamped to three lines.
2026-10-31 03:25:56 +00:00
Maurice 5822910f40 places: put Use this text right under the description it copies
The button was pinned to the foot of the details column, away from the text
it adopts. It now sits inside the description card, under the source line,
with the reason it is blocked directly beneath it.
2026-10-31 03:25:56 +00:00
Maurice ce5ec7132f places: a description the community shared is credited to the TREK community
A community description laid over OSM details or an index row showed up as
OpenStreetMap under ODbL, or as the place's own website. It now has a source of
its own, community, credited as TREK Community under CC BY 4.0, like the
service publishes it.
2026-10-31 03:25:56 +00:00
Maurice 7f2a3b6039 planner: keep REFRESH_FIELDS inside its module; docker: leave shared/node_modules out of the build context
A checkout where npm install ran once carried shared/node_modules into the
image build, and its stale packages broke the client build with a vite that
lacked vite/internal.
2026-10-31 03:25:56 +00:00
Maurice 3e860dd9ca place-contrib: tag enqueue's send run as independent of its queue write 2026-10-31 03:25:56 +00:00
Maurice c28604b891 planner: the details refresh reads through a repository, and the form drops what moved out
The fresh lookup behind New place details goes through placeDetailsRepo
(online-only, like the service identity) instead of api/ directly. The form
loses the Translate type and the comment that moved with the head band's
pills, which takes it under its line limit and out of the size baseline; the
maps service suite's test-size entry follows its shorter count.
2026-10-31 03:25:56 +00:00
Maurice aba329b1b1 planner: a saved place offers newer details from its provider, field by field
Editing a saved place looks it up again. Where the lookup has a website,
phone, e-mail or opening hours that differ from the place, a New place details
pill in the form's head band shows how many, and opens what the place holds
beside what the lookup has. Empty fields are ticked, filled ones are left to
the person and say they would replace; Take over writes only the ticked
fields, with the provider as their origin, and nothing the lookup does not
know is ever emptied.

The head band's pills move to PlaceFormHeaderPills.tsx, which brings the form
from 1157 to 1002 lines.
2026-10-31 03:25:56 +00:00
Maurice 04458bee12 place-contrib: community hours in the details' own shape, and no origin rows for collection copies
Community opening hours laid over OSM details now go through the same parser
as OSM's own, so they arrive as one line per day with open-now and the periods,
and a community description lands in the details' summary. A place copied from
a collection no longer records its values as an import: without an origin row a
value is never sent anyway, and a later edit marks only the fields it changes.
2026-10-31 03:25:56 +00:00
Maurice f01ffc2c67 maps: OSM details come from TREK's own copy of OpenStreetMap first
Opening an OSM place asked the public Overpass servers for its tags, which
took five seconds and more and answered nothing while they were down. Where
the TREK services are in use, the details now come from the Places API's
details layer (/v1/osm), with the community values in the same answer, and
Overpass is asked only for an element the layer does not hold.
2026-10-31 03:25:56 +00:00
Maurice 5cfe925b78 place-contrib: no promise in the job's condition; the OSM details test counts the community call 2026-10-31 03:25:55 +00:00
Maurice a2414685ad wiki: what the API Keys card still saves 2026-10-31 03:25:55 +00:00
Maurice a1ca1aae44 admin: place search and routing get a card of their own, the keys keep theirs
The TREK API, the transit provider, the place search provider and the search
log move out of API Keys into a card of their own, which keeps them together
and saves as they change. API Keys holds only Google Maps, Unsplash and Amap,
and is not shown on a managed install, where the keys are the operator's.
Allowed File Types moves to the left column, which had room for it.
2026-10-31 03:25:55 +00:00
Maurice 56536ae803 admin: the allowance and the sharing blocks take the settings' own card head
Both blocks in the TREK API card now use SettingsCard like Single Sign-On and
two-factor: an icon tile, the title with its state as a badge, the note under
it and the switch or badges on the right, with a flush variant for a card
inside a card. A figure badge no longer cuts the last pixels of its value, and
the withdrawal toast names how many values it took back.
2026-10-31 03:25:55 +00:00
Maurice 59154b34c9 maps: OSM details carry the values installations published for the element
A place found through Photon or Overpass, a relation or a way, is no row of the
TREK index, so the community values the index lays over its own rows never
reached it. Opening its details now asks /v1/community for the element and
lays what is published over the record, with the version, where the TREK index
is in use. No answer leaves the details as they were.
2026-10-31 03:25:55 +00:00
Maurice b64f4535fd admin: set the service card's state and its one action apart from the figures
The state and its badges sit in a head band, the new-identity button in a foot
band, each with a rule and the card's own surface, so neither reads as part of
the allowance tiles between them.
2026-10-31 03:25:55 +00:00
Maurice ad2916903c place-contrib: send a queued value at once instead of minutes later
A value is due the moment it is queued, and the save starts a send run right
away; the two-minute tick stays for the retries. One run goes at a time, and a
run asked for meanwhile follows right after it. Only where the schedules run, so
tests and replicas send nothing.
2026-10-31 03:25:55 +00:00
Maurice 71cd6c2de4 place-contrib: record origins for collection copies and booking imports
A place copied from a collection and a venue a booking import creates now
record their details as an import, so a later edit compares against what was
really written. Dawarich and the background enrichment write none of the
shareable fields, so they need nothing.

The admin panel asks again for a few seconds while a fresh installation is
still fetching its key, so the prompt appears without a reload.
2026-10-31 03:25:55 +00:00
Maurice 3f2dec6c47 place-contrib: sort the request id's parts with an explicit code-unit compare 2026-10-31 03:25:55 +00:00
Maurice 668df8c62e place-contrib: seed the repository tests through the row factories, not raw SQL 2026-10-31 03:25:55 +00:00
Maurice 294ba0a4fe place-contrib: repository tests for the log, the outbox and the field origins
Every method of the three new repositories, the empty-list shortcuts and the
filters included, so the repositories keep their 99 % floor.
2026-10-31 03:25:55 +00:00
Maurice 36c1599a09 place-contrib: settle the second CI round
- The plugin RPC fallback tests build PlacesRpc with its origin bookkeeping.
- The e2e guard and contract cases send their requests one after another; the
  test server reset connections opened all at once.
- The job's two cron registrations are tagged @txIndependent: neither writes.
- The panel draws its fold head itself instead of importing it from pages/.
2026-10-31 03:25:55 +00:00
Maurice 65abea6910 place-contrib: settle the first CI round
- The pause setting's type comes from its schema, so nullable fields read the
  same under the server's compiler settings.
- The place form passes the origin of a field through to the hook.
- Serial steps run through inOrder (src/nest/common/in-order.ts) and
  independent ones through Promise.all, instead of an await inside a loop. The
  bulk update in places.mcp.ts goes the same way, so its baseline drops by one.
- The status a call without a key gets is a named constant, not an envelope
  literal.
- A picture test no longer inherits the previous test's mock answer.
- The entity counts include the three new tables.
- The log keeps its failure per query instead of resetting it in the effect,
  and usePlaceForm sets its picture through one helper.
2026-10-31 03:25:55 +00:00
Maurice 18dc121132 wiki: sharing place details with the TREK Places API
What is sent and when, what never is, how values are checked before anyone
sees them, and where an admin switches it off or takes it back. The new
TREK_PLACES_CONTRIBUTE variable is listed with the compose file and the chart.
2026-10-31 03:25:55 +00:00
Maurice 013aa3954d admin: ask once, then show and steer what is shared of place details
The first time an admin opens the settings on an installation that can share,
a dialog asks for the whole installation, with every field switched on and a
plain list of what never goes along. Nothing is sent before Agree; Not now
asks again in 14 days, No keeps the question away until the terms change, and
closing it decides nothing.

Inside the TREK Places API card, Share place details then holds the switch for
the installation and one per field, the figures of the last 30 days, the
transmission log and the way to withdraw everything sent. The place form
reports for each field whether the user typed it or a provider filled it.
2026-10-31 03:25:55 +00:00
Maurice 182ed56fa4 places: let an admin share the details users typed with the TREK Places API
Every shareable field of a place now records where its value came from: typed
by a user, filled by a provider, written by the assistant, a plugin or an
import. Only values a user typed are ever sent, and only after an admin agreed
to the current terms for the whole installation, field by field.

The new place-contrib domain keeps the decision in app settings, queues values
in an outbox a cron job sends from, logs what the service made of each one and
can withdraw everything this installation sent. Development, test and demo
instances, an own TREK_PLACES_URL, TREK_SERVICES=off and
TREK_PLACES_CONTRIBUTE=off never send anything. Index results carry the
community version, so the details caches refresh when it changes.
2026-10-31 03:25:55 +00:00
Vini f56f6ae11e perf(atlas): keep the admin0 country index as Int16 arrays and send countries/geo from disk 2026-10-31 03:25:13 +00:00
Vini c94ff7421a keep looked-up regions as packed Int32 arrays under a 16 MiB budget 2026-10-31 03:25:12 +00:00
Maurice 2dbcc39832 chore(lint): lower the no-explicit-any baseline after the typed region lookup 2026-10-31 03:25:09 +00:00
Maurice 47dad114df test(atlas): cover the per-country region route in the e2e suite 2026-10-31 00:40:23 +00:00
Vini 7277e35a96 serve each country's regions from its own file, so the server no longer holds them all
The Atlas server no longer keeps the admin-1 regions of every country in memory. Each country's regions are now a pre-gzipped file of their own, sent to the map as they are.

**Why:** `GET /addons/atlas/regions/geo?countries=…` built `admin1Store` (every country's region text, kept until restart), then joined the requested countries, `JSON.parse`d them, and Nest stringified them again. On the 512 MB – 1 GB boxes TREK runs on, the first z≥5 view could OOM the server (same shape as #1576).

**What changes:**
- `server/assets/atlas/admin1/<ISO_A2>.geojson.gz`: 198 files, 14.85 MB, the same 3,447 features as `admin1.geojson.gz`.
- New `GET /addons/atlas/regions/geo/:code` with a Zod contract (`regionGeoParamsSchema` in `@trek/shared`: two letters, any case). It sends the country's file as it is, with `Content-Encoding: gzip` and the current 1-day `Cache-Control`, as `countries/geo` does. A country without regions gets an empty FeatureCollection. Anything that is not two letters gets a 400.
- `useAtlas.ts` fetches one URL per uncached country and still rebuilds the layer once. Each country has a stable URL, so a country evicted by `REGION_CACHE_MAX` comes back from the browser cache.
- `getRegionFeatures` reads only the country it needs. `admin1Store` is removed.
- `?countries=` keeps working for cached PWA clients. It joins the per-country files as bytes, without a parse.
- The migrations are untouched. `admin1.geojson.gz` still ships, only for `Migration20200101021500` and `Migration20200101031500`. This costs ~15 MB of disk in the image and no RAM. `build-atlas-geo.mjs` writes both, and ATLAS-BUNDLE-008 keeps them equal.

**Memory** (real `atlas-geo` module, first z≥5 view over Europe = 49 country codes, JS heap + Buffers):

| | peak | kept after |
|---|---|---|
| before, first view (builds the store) | +372 MB | +61 MB |
| before, later views | +115 MB | 0 |
| after, `/regions/geo/:code` | +4.7 MB | 0 |
| after, legacy `?countries=` | +59 MB | 0 |

**Tests:**
- New: `atlas-region-files.test.ts` (moved from `atlas.service.test.ts`, plus join and dedupe cases), the `regionGeoParamsSchema` spec, ATLAS-BUNDLE-007 (the file format the byte join depends on), ATLAS-BUNDLE-008 (bundle and per-country files are equal), ATLAS-016/017/018 (the new route over HTTP, including the 400).
- The `getVisitedRegions` tests (ATLAS-UNIT-019..024) used to pass only when `getRegionGeo`'s `beforeAll` had built the store first. They now also pass on their own.
- The shared, server and client gates pass. Baselines go down only where this change removed code (`no-console`, `no-explicit-any`, `no-swallowed-catch`, file sizes).

**Trade-offs:**
- A first zoom over Europe sends ~49 small parallel requests instead of 1. Over HTTP/1.1 the browser queues them 6 at a time. The total bytes are the same (4.4 MB gz).
- The per-country URLs are unversioned and cached for a day, like `countries/geo`. After an upgrade that changes a country's regions, a browser can show the old shapes for up to 24 h.

Approved on Discord in #github-pr: <paste the thread link here>
Related: #1576, #2559

- [x] Bug fix
- [ ] New feature
- [ ] Breaking change
- [ ] Documentation update

- [ ] I have read the [Contributing Guidelines](https://github.com/liketrek/TREK/wiki/Contributing)
- [ ] My branch is [up to date with `dev`](https://github.com/liketrek/TREK/wiki/Development-environment#3-keep-your-fork-up-to-date)
- [x] This PR targets the `dev` branch, not `main` *(wiki-only PRs are exempt)*
- [x] I have tested my changes locally
- [x] I have added/updated tests that prove my fix is effective or that my feature works
- [x] I have updated documentation if needed
2026-10-31 00:40:23 +00:00
Maurice 70f27085b9 feat(i18n): bring the Hebrew locale up to date with dev and list it in the docs
Translate the 55 keys dev added since the branch was cut (TREK services
allowance, Valhalla routing service, PDF routing progress, overview
distances, Unsplash key hint, tour day limit) and drop the two reservation
toasts dev removed, so he matches en key for key again. Refresh the two
admin strings and the Valhalla hint whose English changed.

Check he in the placeholder spec and the RTL test, and count 28 languages
with Hebrew in the README and the Languages, Environment Variables,
Contributing and Help Center wiki pages.
2026-10-31 00:40:23 +00:00
Dolev Benezri 156dc4a6c2 feat(i18n): complete Hebrew locale for dev
Fill in every domain added since the first Hebrew pass (help, tours,
assistant*, studio*, wanderer*, journey, demo, ferratas and the rest),
retranslate strings whose English changed, and give every count group
its Hebrew one/two forms. Register he as a non-Latin locale for the
untranslated ratchet, add the Hebrew 429 message, and count 28 locales
in the tours locale spec.
2026-10-31 00:40:23 +00:00
Dolev Benezri d159aec78b feat(i18n): add Hebrew (he) locale with RTL support
Full Hebrew translation of every UI domain plus email/notification
templates. Registered in SUPPORTED_LANGUAGES, marked right-to-left,
wired into the client locale loader and the rate-limit message table.
2026-10-31 00:40:23 +00:00
bear 547f0b84b0 fix(mcp): file a transit fare under the transport cost category
transit is not one of the fixed Costs categories, so typeToCostCategory
would put an uncategorised fare under other. Default to transport, the
category every rail and bus booking maps to.
2026-10-31 00:40:23 +00:00
bear 8d10bff616 feat(mcp): price on create_transit_journey, reservation_id on create_budget_item
- create_transit_journey takes price / budget_category, as create_transport
  does: a fare > 0 files the linked expense in the booking's own transaction
  and rides along in metadata.price. The tool now writes through
  ReservationWritesService.createBooking, so its events and booking notice are
  the ones every other booking write sends
- create_budget_item and create_budget_item_with_members take reservation_id,
  the field POST /budget already accepts; create_budget_item now runs
  BudgetWritesService.createItem like its sibling, so a linked booking's
  mirrored price is worked out again before budget:created goes out
- bookingPriceSchema / bookingBudgetCategorySchema in @trek/shared back the
  price fields of all three booking tools (mcp-inline-zod baseline lowered)
- wiki: MCP-Tools-and-Resources describes the new params
2026-10-31 00:40:23 +00:00
Maurice e5048643f8 test(assistant): pin the clock in FE-AI-PICK-004
Trip 7 ran until 2026-10-30, so from 2026-10-31 on the hook ranked it as
past and the test failed. Pin the date to the file's TODAY.
2026-10-31 00:39:38 +00:00
Maurice a156f5be32 fix(chart): keep a blank line before the HTTPRoute section in NOTES.txt
The trimming if swallowed the blank line, so the HTTPRoute note ran
straight on from the Persistence section. Move the blank line inside
the conditional so it only appears with the section.
2026-10-30 23:32:43 +00:00
Demisu 431122d253 refactor(README): remove HTTPRoute configuration section for clarity 2026-10-30 23:32:43 +00:00
Demisu bbc8f141e3 feat(helm): add optional Gateway API HTTPRoute support
Add disabled-by-default HTTPRoute support with configurable parent references,
hostnames, paths, annotations and optional timeouts. Route to the existing TREK
Service and keep Ingress support unchanged, including simultaneous use.

Document configuration and extend the existing Helm Chart & Compose job with
HTTPRoute render variants and strict validation using a pinned CRDs catalog.

Approved on Discord:
https://discord.com/channels/1488298068427411591/1553537637455761500

Validation: strict Helm lint, 37 manifests validated without errors or skipped
resources, and both Compose configuration checks passed locally.
Live Gateway WebSocket and streamed assistant response checks were not performed
because no Kubernetes test cluster was configured.
2026-10-30 23:32:43 +00:00
Maurice 01681f57c7 docs(chart): document extraVolumes and extraVolumeMounts in the Helm install guide
The install guide lists extraEnv and extraEnvFrom but had no word on the
new volume values. Add a Further volumes section with the KItinerary
extractor example and point the Reservations-and-Bookings page at it.
2026-10-30 23:30:54 +00:00
aaronspruit 553808eb83 feat(chart): add extraVolumes and extraVolumeMounts
The chart mounts only the data and uploads volumes, and no value adds
another one. Add two lists that go into the Deployment as written:
extraVolumes for the pod, and extraVolumeMounts for the trek container,
next to the data and uploads mounts. Both lists are empty by default,
so the default render does not change.

The values file shows one use: a ConfigMap of KItinerary extractor
scripts, mounted at /usr/local/share/kitinerary/extractors. The chart
README and the Reservations-and-Bookings wiki page tell Helm and Compose
users how to mount extractors there.

The variants render in the Helm Chart & Compose job sets both values,
so kubeconform checks them.
2026-10-30 23:30:54 +00:00
Maurice 324ee69151 fix(transit): mark the plan fallback's quota counts as independent writes
The empty-result fallback can call Google after Transitous, so lint:tx now sees two googleQuota.record() calls in TransitService.plan. Only one of them runs per request, and each is a call counter written after its own upstream request, so it cannot share a transaction with it.
2026-10-30 23:36:35 +01:00
Maurice c4c63ffd62 docs(transit): describe the empty-result fallback between transit providers
Admin settings, transport, environment and MCP pages still said Transitous
is the only fallback and that Google is billed only when picked. Document
that an empty plan asks the other backend, that the Google fallback uses
only an instance key within the daily limit, and mention it in the
search_transit_routes tool description.
2026-10-30 23:01:17 +01:00
Raz Erlich 209f8fe5cc feat(transit): fall back between configured public transit providers 2026-10-28 08:01:53 +02:00
Maurice 9f155a3191 fix(airports): refresh the bundled airports from OurAirports without dropping shipped codes
Logroño-Agoncillo (RJL) and fifteen other airports gained their IATA code in
OurAirports after the bundled list was built, so the airport search and the
code lookup of create_transport could not find them. The list is rebuilt from
the current data. The build now keeps every code the previous list carried
that upstream no longer lists (a scheduled-service flag flipped back, PBI moved
to a new record), since bookings and MCP calls still name them.

Refs #2897
2026-10-30 22:06:07 +01:00
547 changed files with 31064 additions and 870 deletions
+1
View File
@@ -1,6 +1,7 @@
node_modules
client/node_modules
server/node_modules
shared/node_modules
client/dist
shared/dist
data
+21 -1
View File
@@ -1263,11 +1263,31 @@ jobs:
--set 'extraEnv[0].name=SESSION_DURATION' \
--set 'extraEnv[0].value=7d' \
--set 'extraEnvFrom[0].secretRef.name=trek-smtp' \
--set 'extraVolumes[0].name=kitinerary-extractors' \
--set 'extraVolumes[0].configMap.name=trek-kitinerary-extractors' \
--set 'extraVolumeMounts[0].name=kitinerary-extractors' \
--set 'extraVolumeMounts[0].mountPath=/usr/local/share/kitinerary/extractors' \
--set 'extraVolumeMounts[0].readOnly=true' \
--set probes.liveness=null \
> "$out/variants.yaml"
helm template trek charts/trek \
--set httpRoute.enabled=true \
--set 'httpRoute.parentRefs[0].name=gateway' \
> "$out/http-route.yaml"
helm template trek charts/trek \
--set ingress.enabled=true \
--set fullnameOverride=custom-trek \
--set service.port=8080 \
--set-json 'httpRoute={"enabled":true,"parentRefs":[{"name":"gateway","namespace":"gateway-system","sectionName":"https"}],"hostnames":["trek.example.com"],"paths":["/","/api"],"annotations":{"example.com/note":"custom route"},"timeouts":{"request":"0s","backendRequest":"0s"}}' \
> "$out/http-route-variants.yaml"
- name: Check the manifests against the Kubernetes schemas
run: kubeconform -strict -summary "$RUNNER_TEMP"/rendered/*.yaml
# The pinned Gateway API schema adds HTTPRoute validation without skipping unknown resources.
run: >-
kubeconform -strict -summary
-schema-location default
-schema-location 'https://raw.githubusercontent.com/datreeio/CRDs-catalog/041baf4c1d3740ca21461cab765e7432ecd073ef/{{.Group}}/{{.ResourceKind}}_{{.ResourceAPIVersion}}.json'
"$RUNNER_TEMP"/rendered/*.yaml
- name: Check every compose file
run: |
+2 -1
View File
@@ -91,7 +91,8 @@ ENV KITINERARY_EXTRACTOR_PATH=/usr/local/bin/kitinerary-extractor
COPY --chown=node:node --from=server-builder /app/server/dist ./server/dist
# Runtime data assets read from server/assets at runtime: airports.json (flight
# transport search) and atlas/*.geojson.gz (Atlas country/region map). The build
# transport search) and atlas/*.geojson.gz + atlas/admin1/*.geojson.gz (Atlas
# country/region map). The build
# only emits dist, so these must be copied explicitly or the features silently
# degrade to empty in the image.
COPY --chown=node:node --from=server-builder /app/server/assets ./server/assets
+3 -2
View File
@@ -5,8 +5,9 @@ TREK bundles and uses third-party data that requires attribution.
## geoBoundaries — country & sub-national boundaries
The Atlas map's administrative boundaries (admin-0 countries and admin-1
provinces/counties), shipped at `server/assets/atlas/admin0.geojson.gz` and
`server/assets/atlas/admin1.geojson.gz` and generated by
provinces/counties), shipped at `server/assets/atlas/admin0.geojson.gz`,
`server/assets/atlas/admin1.geojson.gz` and `server/assets/atlas/admin1/<ISO_A2>.geojson.gz`
(the same regions, one file per country) and generated by
`server/scripts/build-atlas-geo.mjs`, are derived from **geoBoundaries**.
> Runfola, D. et al. (2020) geoBoundaries: A global database of political
+1 -1
View File
@@ -200,7 +200,7 @@ Most of what follows is an addon an admin switches on or off. Lists, Costs, Docu
- **Admin panel**: users and the permission matrix, defaults for new users, categories and templates, addons, plugins, storage, notifications, MCP tokens, backups, audit log and releases
- **Backups and storage**: scheduled backups with retention that restore their own secrets, and local or S3-compatible storage per content category with replicas
- **Appearance**: light, dark or follow the OS, seven colour schemes plus a custom accent, transparency, density, reduced motion and text size
- **27 languages**: en, de, es, fr, it, nl, hu, ru, zh, zh-TW, pl, cs, ar (right to left), br, id, tr, ja, ko, uk, gr, sv, vi, ca, az, et, sk, th
- **28 languages**: en, de, es, fr, it, nl, hu, ru, zh, zh-TW, pl, cs, ar (right to left), he (right to left), br, id, tr, ja, ko, uk, gr, sv, vi, ca, az, et, sk, th
- **Help center**: a ? in the top bar with 381 step-by-step guides with screenshots, searched together with the wiki that ships in the image
</td>
+5 -3
View File
@@ -5,9 +5,10 @@ This is a minimal Helm chart for deploying the TREK app.
## Features
- Deploys the TREK container
- Exposes port 3000 via Service
- Optional persistent storage for `/app/data` and `/app/uploads`
- Optional persistent storage for `/app/data` and `/app/uploads`, plus extra volumes and mounts
- Configurable environment variables and secrets
- Optional generic Ingress support
- Optional Gateway API HTTPRoute support
- Configurable health checks (liveness/readiness probes) on `/api/health`
## Helm Repository
@@ -27,7 +28,7 @@ helm install trek trek/trek
Or install directly from the local chart:
```sh
helm install trek ./chart \
helm install trek ./charts/trek \
--set ingress.enabled=true \
--set ingress.hosts[0].host=yourdomain.com
```
@@ -47,7 +48,7 @@ See `values.yaml` for more options.
- `JWT_SECRET` is managed entirely by the server — auto-generated into the data PVC on first start and rotatable via the admin panel (Settings → Danger Zone). No Helm configuration needed.
- `ENCRYPTION_KEY` encrypts stored secrets (API keys, MFA, SMTP, OIDC) at rest. Recommended: set via `secretEnv.ENCRYPTION_KEY` or `existingSecret`. If left empty, the server falls back automatically: existing installs use `data/.jwt_secret` (no action needed on upgrade); fresh installs auto-generate a key persisted to the data PVC.
- Liveness and readiness probes are configurable under `probes`. Overrides are merged over the defaults, so `--set probes.liveness.initialDelaySeconds=60` keeps the `httpGet` handler. When switching to `exec` or `tcpSocket`, clear `httpGet` in the same override. Set `probes.liveness: null` to remove a probe.
- If using ingress, you must manually keep `env.ALLOWED_ORIGINS` and `ingress.hosts` in sync to ensure CORS works correctly. The chart does not sync these automatically.
- If exposing TREK through an Ingress or HTTPRoute, set `env.ALLOWED_ORIGINS` and `env.APP_URL` to the public URL. The chart does not sync these automatically.
- Set `env.ALLOW_INTERNAL_NETWORK: "true"` if Immich or other integrated services are hosted on a private/RFC-1918 address (e.g. a pod on the same cluster or a NAS on your LAN). Loopback (`127.x`) and link-local/metadata addresses (`169.254.x`) remain blocked regardless.
- Set `env.ALLOW_LINK_LOCAL_IPS` to a single link-local address (e.g. `"169.254.1.2"`) only when a service TREK needs sits behind one, such as a host gateway. Cloud metadata addresses (`169.254.169.x`, `169.254.170.x`) cannot be listed.
- `FORCE_HTTPS` is optional. Set `env.FORCE_HTTPS: "true"` only when ingress (or another proxy) terminates TLS. It enables HTTPS redirects, HSTS, CSP `upgrade-insecure-requests`, and forces the session cookie `secure` flag. Requires `TRUST_PROXY` to be set.
@@ -55,3 +56,4 @@ See `values.yaml` for more options.
- `COOKIE_SECURE` is auto-derived (on when `NODE_ENV=production` or `FORCE_HTTPS=true`). Set `env.COOKIE_SECURE: "false"` only during local testing without TLS. **Not recommended for production.**
- Web Push needs no chart settings: TREK generates its key pair on first start and keeps it in the database on the data PVC. To bring your own pair, set `env.VAPID_PUBLIC_KEY` and `secretEnv.VAPID_PRIVATE_KEY` together (and optionally `env.VAPID_SUBJECT`); changing the pair later means every device has to turn push on again.
- Set `env.OIDC_DISCOVERY_URL` to override the auto-constructed OIDC discovery endpoint. Required for providers (e.g. Authentik) that expose it at a non-standard path.
- Use `extraVolumes` and `extraVolumeMounts` to add your own volumes to the pod. To give the booking import more KItinerary extractors, mount a ConfigMap at `/usr/local/share/kitinerary/extractors`, with one `.json` and one `.js` key for each extractor; see the example in `values.yaml`.
+9
View File
@@ -31,3 +31,12 @@
The other values for that volume (size, storageClassName, annotations) are then ignored.
- With `persistence.enabled=false` the volumes use an emptyDir — storage is ephemeral and is lost
when the pod restarts. Use only for testing.
{{- if .Values.httpRoute.enabled }}
6. HTTPRoute:
- The chart creates an HTTPRoute v1 to the existing TREK Service. The Gateway, GatewayClass,
listeners, TLS certificates and allowedRoutes are managed by your cluster operator.
- Ingress and HTTPRoute may be enabled together.
- Timeout fields are Standard Channel in Gateway API v1.2, but controller support varies. Omit
them to use controller defaults; `0s` disables the corresponding timeout where supported.
{{- end }}
+3
View File
@@ -112,6 +112,9 @@ data:
{{- if .Values.env.TREK_PLACES_URL }}
TREK_PLACES_URL: {{ .Values.env.TREK_PLACES_URL | quote }}
{{- end }}
{{- if .Values.env.TREK_PLACES_CONTRIBUTE }}
TREK_PLACES_CONTRIBUTE: {{ .Values.env.TREK_PLACES_CONTRIBUTE | quote }}
{{- end }}
{{- if .Values.env.TREK_SERVICES }}
TREK_SERVICES: {{ .Values.env.TREK_SERVICES | quote }}
{{- end }}
+6
View File
@@ -141,6 +141,9 @@ spec:
mountPath: /app/data
- name: uploads
mountPath: /app/uploads
{{- with .Values.extraVolumeMounts }}
{{- toYaml . | nindent 12 }}
{{- end }}
{{- with (default dict .Values.probes).startup }}
startupProbe:
{{- toYaml . | nindent 12 }}
@@ -168,3 +171,6 @@ spec:
{{- else }}
emptyDir: {}
{{- end }}
{{- with .Values.extraVolumes }}
{{- toYaml . | nindent 8 }}
{{- end }}
+39
View File
@@ -0,0 +1,39 @@
{{- if .Values.httpRoute.enabled -}}
{{- if not .Values.httpRoute.parentRefs }}
{{- fail "httpRoute.parentRefs must include at least one parent" }}
{{- end }}
{{- if not .Values.httpRoute.paths }}
{{- fail "httpRoute.paths must include at least one path" }}
{{- end }}
apiVersion: gateway.networking.k8s.io/v1
kind: HTTPRoute
metadata:
name: {{ include "trek.fullname" . }}
labels:
app: {{ include "trek.name" . }}
{{- with .Values.httpRoute.annotations }}
annotations:
{{- toYaml . | nindent 4 }}
{{- end }}
spec:
parentRefs:
{{- toYaml .Values.httpRoute.parentRefs | nindent 4 }}
{{- with .Values.httpRoute.hostnames }}
hostnames:
{{- toYaml . | nindent 4 }}
{{- end }}
rules:
{{- range $path := .Values.httpRoute.paths }}
- matches:
- path:
type: PathPrefix
value: {{ $path | quote }}
backendRefs:
- name: {{ include "trek.fullname" $ }}
port: {{ $.Values.service.port }}
{{- with $.Values.httpRoute.timeouts }}
timeouts:
{{- toYaml . | nindent 8 }}
{{- end }}
{{- end }}
{{- end }}
+36 -1
View File
@@ -36,7 +36,7 @@ env:
# Browser/OS language is auto-detected first; this is the fallback when no match is found.
# Supported: ar, az, br, ca, cs, de, en, es, et, fr, gr, hu, id, it, ja, ko, nl, pl, ru, sk, sv, th, tr, uk, vi, zh, zh-TW
# ALLOWED_ORIGINS: ""
# NOTE: If using ingress, ensure env.ALLOWED_ORIGINS matches the domains in ingress.hosts for proper CORS configuration.
# NOTE: If using ingress or HTTPRoute, ensure env.ALLOWED_ORIGINS matches the public domains for proper CORS configuration.
# APP_URL: "https://trek.example.com"
# Public base URL of this instance. Required when OIDC is enabled — must match the redirect URI registered with your IdP.
# Also used as the base URL for links in email notifications and other external links.
@@ -113,6 +113,10 @@ env:
# Base URL of a copy of the Places API you run yourself; it has to answer the same /v1 API. Read from
# configuration rather than typed by a user, so an in-cluster address works without ALLOW_INTERNAL_NETWORK.
# Defaults to https://places.liketrek.com.
# TREK_PLACES_CONTRIBUTE: "off"
# Whether an admin may let this installation send the place details its users typed in (website, phone, e-mail,
# opening hours, description, picture) to the TREK Places API. "admin" leaves the choice to the admin panel, where
# it stays off until an admin agrees; "off" takes it away. Defaults to admin.
# TREK_SERVICES: "off"
# Places search identifies this installation with a key it registers by itself on first use and keeps in the
# database. "off" sends no key; searches then use the shared pool. A key issued to you goes under
@@ -260,6 +264,20 @@ extraEnv: []
# name: trek-smtp
extraEnvFrom: []
# Further volumes for the pod. The chart does not create the objects they name.
# extraVolumes:
# - name: kitinerary-extractors
# configMap:
# name: trek-kitinerary-extractors
extraVolumes: []
# Where the trek container mounts them. For example, KItinerary
# loads extractors for the booking import from this path:
# extraVolumeMounts:
# - name: kitinerary-extractors
# mountPath: /usr/local/share/kitinerary/extractors
# readOnly: true
extraVolumeMounts: []
resources:
requests:
cpu: 100m
@@ -280,3 +298,20 @@ ingress:
# - secretName: chart-example-tls
# hosts:
# - chart-example.local
httpRoute:
enabled: false
annotations: {}
parentRefs: []
# - name: gateway
# namespace: gateway-system
# sectionName: https
hostnames: []
# - trek.example.com
paths:
- /
# Timeout fields are Standard Channel in Gateway API v1.2; controller support varies.
# Leave empty for controller defaults. Use "0s" to disable the corresponding timeout.
timeouts: {}
# request: "0s"
# backendRequest: "0s"
+2 -2
View File
@@ -1,11 +1,11 @@
{
"src": {
"@typescript-eslint/no-non-null-assertion": 382,
"@typescript-eslint/no-non-null-assertion": 380,
"@typescript-eslint/no-misused-promises": 847,
"no-console": 88,
"complexity": 218,
"@typescript-eslint/no-explicit-any": 144,
"trek/no-swallowed-catch": 129,
"trek/no-swallowed-catch": 128,
"max-params": 32,
"trek/store-without-selector": 67,
"react-hooks/refs": 555,
+1 -2
View File
@@ -13,7 +13,6 @@
"src/components/Planner/DayPlanSidebar.test.tsx": 5349,
"src/components/Planner/DayPlanSidebar.tsx": 2936,
"src/components/Planner/PlaceFormModal.test.tsx": 2836,
"src/components/Planner/PlaceFormModal.tsx": 1157,
"src/components/Planner/PlaceInspector.tsx": 1290,
"src/components/Studio/TravelElements.tsx": 1559,
"src/components/Studio/countryShapes.ts": 2595,
@@ -22,7 +21,7 @@
"src/pages/JourneyDetailPage.test.tsx": 4030,
"src/pages/LoginPage.tsx": 1348,
"src/pages/TripPlannerPage.tsx": 1128,
"src/pages/atlas/useAtlas.ts": 1211,
"src/pages/atlas/useAtlas.ts": 1210,
"src/pages/tripPlanner/useTripPlanner.roadtrip.test.tsx": 3518,
"src/pages/tripPlanner/useTripPlanner.test.tsx": 3270,
"src/styles/studio.css": 1918
+14
View File
@@ -0,0 +1,14 @@
import type { PlaceContribDecisionRequest, PlaceContribLogQuery } from '@trek/shared';
import apiClient from './client';
/** /api/admin/places-contribute: sharing place details with the TREK Places API. Admin only. */
export const placeContribApi = {
state: (signal?: AbortSignal): Promise<unknown> =>
apiClient.get('/admin/places-contribute', { signal }).then((r) => r.data),
decide: (body: PlaceContribDecisionRequest): Promise<unknown> =>
apiClient.put('/admin/places-contribute/decision', body).then((r) => r.data),
log: (query: Partial<PlaceContribLogQuery>, signal?: AbortSignal): Promise<unknown> =>
apiClient.get('/admin/places-contribute/log', { params: query, signal }).then((r) => r.data),
withdraw: (): Promise<unknown> =>
apiClient.post('/admin/places-contribute/withdraw', { confirm: true }).then((r) => r.data),
};
+1
View File
@@ -22,6 +22,7 @@ const RATE_LIMIT_MESSAGES: Record<string, string> = {
tr: 'Çok fazla deneme. Lütfen daha sonra tekrar deneyin.',
ar: 'محاولات كثيرة جدًا. يرجى المحاولة لاحقًا.',
az: 'Həddindən çox cəhd edildi. Bir az sonra yenidən cəhd edin.',
he: 'יותר מדי ניסיונות. נסו שוב מאוחר יותר.',
id: 'Terlalu banyak percobaan. Coba lagi nanti.',
ja: '試行回数が多すぎます。時間をおいて再度お試しください。',
ko: '시도 횟수가 너무 많습니다. 잠시 후 다시 시도해 주세요.',
@@ -0,0 +1,80 @@
// FE-ADMIN-CONTRIB-LOG-001 to FE-ADMIN-CONTRIB-LOG-004
import userEvent from '@testing-library/user-event';
import type { PlaceContribLogEntry } from '@trek/shared';
import { http, HttpResponse } from 'msw';
import { describe, expect, it, vi } from 'vitest';
import { server } from '../../../tests/helpers/msw/server';
import { render, screen, waitFor } from '../../../tests/helpers/render';
import PlaceContribLog from './PlaceContribLog';
vi.mock('../../i18n', async (importOriginal) => ({
...(await importOriginal<typeof import('../../i18n')>()),
useTranslation: () => ({ t: (key: string) => key, locale: 'en-US' }),
}));
const ENTRY: PlaceContribLogEntry = {
id: 1,
day: '2026-10-29',
key: 'osm:n123',
placeName: 'Café Luitpold',
field: 'phone',
valueSummary: '+49 89 242 8750',
result: 'accepted',
reason: null,
};
function serve(entries: PlaceContribLogEntry[], total = entries.length) {
const queries: URLSearchParams[] = [];
server.use(
http.get('/api/admin/places-contribute/log', ({ request }) => {
queries.push(new URL(request.url).searchParams);
return HttpResponse.json({
entries,
total,
page: Number(new URL(request.url).searchParams.get('page') ?? 1),
perPage: 20,
});
})
);
return queries;
}
describe('PlaceContribLog', () => {
it('FE-ADMIN-CONTRIB-LOG-001: lists the place, the value, the field and the result', async () => {
serve([ENTRY]);
render(<PlaceContribLog />);
expect(await screen.findByText('Café Luitpold')).toBeInTheDocument();
expect(screen.getByText('+49 89 242 8750')).toBeInTheDocument();
expect(screen.getByText('admin.contribute.field.phone')).toBeInTheDocument();
expect(screen.getByText('admin.contribute.result.accepted')).toBeInTheDocument();
});
it('FE-ADMIN-CONTRIB-LOG-002: an empty log says nothing was sent', async () => {
serve([]);
render(<PlaceContribLog />);
expect(await screen.findByText('admin.contribute.log.empty')).toBeInTheDocument();
});
it('FE-ADMIN-CONTRIB-LOG-003: pages through a long log', async () => {
const queries = serve([ENTRY], 45);
render(<PlaceContribLog />);
await userEvent.click(await screen.findByRole('button', { name: /common\.showMore/ }));
expect(await screen.findByText('1 / 3')).toBeInTheDocument();
await userEvent.click(screen.getByRole('button', { name: 'admin.contribute.log.next' }));
await waitFor(() => expect(queries[queries.length - 1]?.get('page')).toBe('2'));
expect(queries[queries.length - 1]?.get('perPage')).toBe('20');
});
it('FE-ADMIN-CONTRIB-LOG-004: shows the newest five until the list is opened', async () => {
serve(Array.from({ length: 8 }, (_, i) => ({ ...ENTRY, id: i + 1, placeName: `Place ${i + 1}` })));
render(<PlaceContribLog />);
expect(await screen.findByText('Place 5')).toBeInTheDocument();
expect(screen.queryByText('Place 6')).not.toBeInTheDocument();
const toggle = screen.getByRole('button', { name: 'common.showMore (3)' });
expect(toggle).toHaveAttribute('aria-expanded', 'false');
await userEvent.click(toggle);
expect(screen.getByText('Place 8')).toBeInTheDocument();
await userEvent.click(screen.getByRole('button', { name: 'common.showLess' }));
expect(screen.queryByText('Place 8')).not.toBeInTheDocument();
});
});
@@ -0,0 +1,187 @@
import {
PLACE_CONTRIB_FIELDS,
type PlaceContribField,
type PlaceContribLogResponse,
type PlaceContribLogResult,
} from '@trek/shared';
import { ChevronDown, ChevronLeft, ChevronRight } from 'lucide-react';
import { useEffect, useState } from 'react';
import { useTranslation } from '../../i18n';
import { placeContribRepo } from '../../repo/placeContribRepo';
import { PillSelect } from '../shared/dialogParts';
import { fs } from '../shared/DialogShell';
import { fieldLabel } from './placeContribModel';
const PER_PAGE = 20;
/** Rows shown before the list is opened; a busy log should not push the page down. */
const FOLDED = 5;
const RESULTS: PlaceContribLogResult[] = ['accepted', 'duplicate', 'rejected', 'withheld', 'retracted'];
const RESULT_LOOK: Record<PlaceContribLogResult, string> = {
accepted: 'bg-success-soft text-success',
duplicate: 'bg-surface-tertiary text-content-muted',
rejected: 'bg-danger-soft text-danger',
withheld: 'bg-surface-tertiary text-content-muted',
retracted: 'bg-warning-soft text-warning',
};
/**
* What this installation sent, newest first: the place, the field, a short
* form of the value and what the service made of it. Read only while the fold
* is open, a page at a time, and only the newest FOLDED rows until opened.
*/
export default function PlaceContribLog() {
const { t, locale } = useTranslation();
const [page, setPage] = useState(1);
const [result, setResult] = useState<PlaceContribLogResult | 'all'>('all');
const [field, setField] = useState<PlaceContribField | 'all'>('all');
const [data, setData] = useState<PlaceContribLogResponse | null>(null);
const [open, setOpen] = useState(false);
// The query that failed to load, so a new page or filter clears the message by itself.
const query = `${page}|${result}|${field}`;
const [failedQuery, setFailedQuery] = useState<string | null>(null);
const failed = failedQuery === query;
useEffect(() => {
const controller = new AbortController();
placeContribRepo
.log(
{
page,
perPage: PER_PAGE,
...(result === 'all' ? {} : { result }),
...(field === 'all' ? {} : { field }),
},
controller.signal
)
.then(setData, () => {
if (!controller.signal.aborted) setFailedQuery(`${page}|${result}|${field}`);
});
return () => controller.abort();
}, [page, result, field]);
const pages = data ? Math.max(1, Math.ceil(data.total / PER_PAGE)) : 1;
const foldable = !!data && (data.entries.length > FOLDED || pages > 1);
const rows = data ? (open || !foldable ? data.entries : data.entries.slice(0, FOLDED)) : [];
const day = new Intl.DateTimeFormat(locale, { day: 'numeric', month: 'short' });
return (
<div className="flex flex-col gap-2.5">
<div className="flex flex-wrap gap-2">
<PillSelect<PlaceContribLogResult | 'all'>
quiet
label={t('admin.contribute.log.result')}
value={result}
onChange={(v) => {
setResult(v);
setPage(1);
}}
options={[
{ value: 'all', label: t('admin.contribute.log.allResults') },
...RESULTS.map((r) => ({ value: r, label: t(`admin.contribute.result.${r}`) })),
]}
/>
<PillSelect<PlaceContribField | 'all'>
quiet
label={t('admin.contribute.log.field')}
value={field}
onChange={(v) => {
setField(v);
setPage(1);
}}
options={[
{ value: 'all', label: t('admin.contribute.log.allFields') },
...PLACE_CONTRIB_FIELDS.map((f) => ({ value: f, label: fieldLabel(t, f) })),
]}
/>
</div>
{failed && (
<p className="m-0 text-danger" style={fs(12, 'body')}>
{t('admin.contribute.log.failed')}
</p>
)}
{data && data.entries.length === 0 && (
<p className="m-0 py-3 text-center text-content-faint" style={fs(12, 'body')}>
{t('admin.contribute.log.empty')}
</p>
)}
{data && data.entries.length > 0 && (
<ul className="m-0 list-none divide-y divide-edge-faint overflow-hidden rounded-[12px] border border-edge-faint bg-surface-card p-0">
{rows.map((e) => (
<li key={e.id} className="flex flex-wrap items-center gap-x-2.5 gap-y-1 px-3 py-2">
<span className="w-12 flex-none tabular-nums text-content-faint" style={fs(11.5)}>
{day.format(new Date(`${e.day}T12:00:00`))}
</span>
<span className="min-w-0 flex-1">
<span className="block truncate font-medium text-content" style={fs(12.5, 'body')}>
{e.placeName}
</span>
{e.valueSummary && (
<span className="block truncate text-content-muted" style={fs(11.5)}>
{e.valueSummary}
</span>
)}
</span>
<span
className="inline-flex flex-none items-center rounded-full bg-surface-secondary px-2 py-[2px] text-content-secondary"
style={fs(11)}
>
{fieldLabel(t, e.field)}
</span>
<span
className={`inline-flex flex-none items-center rounded-full px-2 py-[2px] font-semibold ${RESULT_LOOK[e.result]}`}
style={fs(11)}
title={e.reason ?? undefined}
>
{t(`admin.contribute.result.${e.result}`)}
</span>
</li>
))}
</ul>
)}
{foldable && (
<button
type="button"
aria-expanded={open}
onClick={() => setOpen((o) => !o)}
className="inline-flex items-center gap-1 self-start font-medium text-content-muted hover:text-content"
style={fs(12, 'body')}
>
<ChevronDown
size={14}
aria-hidden="true"
className={open ? 'rotate-180 transition-transform' : 'transition-transform'}
/>
{open ? t('common.showLess') : `${t('common.showMore')} (${(data?.total ?? 0) - FOLDED})`}
</button>
)}
{data && open && pages > 1 && (
<div className="flex items-center justify-end gap-2 text-content-muted" style={fs(12, 'body')}>
<button
type="button"
disabled={page <= 1}
onClick={() => setPage((p) => p - 1)}
aria-label={t('admin.contribute.log.previous')}
className="grid h-7 w-7 place-items-center rounded-lg border border-edge-faint bg-surface-card disabled:opacity-40"
>
<ChevronLeft size={14} aria-hidden="true" />
</button>
<span className="tabular-nums">
{page} / {pages}
</span>
<button
type="button"
disabled={page >= pages}
onClick={() => setPage((p) => p + 1)}
aria-label={t('admin.contribute.log.next')}
className="grid h-7 w-7 place-items-center rounded-lg border border-edge-faint bg-surface-card disabled:opacity-40"
>
<ChevronRight size={14} aria-hidden="true" />
</button>
</div>
)}
</div>
);
}
@@ -0,0 +1,204 @@
// FE-ADMIN-CONTRIB-001 to FE-ADMIN-CONTRIB-011
import userEvent from '@testing-library/user-event';
import type { PlaceContribDecisionRequest, PlaceContribState } from '@trek/shared';
import { http, HttpResponse } from 'msw';
import { describe, expect, it, vi } from 'vitest';
import { server } from '../../../tests/helpers/msw/server';
import { render, screen, waitFor, within } from '../../../tests/helpers/render';
import PlaceContribPanel from './PlaceContribPanel';
// The keys themselves, so a test fails on a missing or renamed key rather than on wording.
vi.mock('../../i18n', async (importOriginal) => ({
...(await importOriginal<typeof import('../../i18n')>()),
useTranslation: () => ({ t: (key: string) => key, locale: 'en-US' }),
}));
const ON = { website: true, phone: true, email: true, opening_hours: true, description: true, image: true };
const UNDECIDED: PlaceContribState = {
termsVersion: 1,
ceiling: 'admin',
eligible: true,
ineligibleReason: null,
consent: { enabled: false, fields: ON, termsVersion: null, decision: null, decidedBy: null, decidedAt: null },
showPrompt: true,
snoozedUntil: null,
active: false,
counts: { accepted: 0, duplicate: 0, rejected: 0, withheld: 0, retracted: 0 },
lastSuccessDay: null,
queue: { size: 0, cap: 5000, full: false },
pauseReason: null,
registrationOpen: false,
};
const AGREED: PlaceContribState = {
...UNDECIDED,
showPrompt: false,
active: true,
consent: {
enabled: true,
fields: ON,
termsVersion: 1,
decision: 'agreed',
decidedBy: 1,
decidedAt: '2026-10-30T10:00:00Z',
},
counts: { accepted: 42, duplicate: 3, rejected: 1, withheld: 5, retracted: 0 },
lastSuccessDay: '2026-10-29',
queue: { size: 7, cap: 5000, full: false },
};
/** Serves `state`, records every decision and answers it with `answer`. */
function serve(
state: PlaceContribState,
answer: (body: PlaceContribDecisionRequest) => PlaceContribState = () => state
) {
const decisions: PlaceContribDecisionRequest[] = [];
server.use(
http.get('/api/admin/places-contribute', () => HttpResponse.json(state)),
http.put('/api/admin/places-contribute/decision', async ({ request }) => {
const body = (await request.json()) as PlaceContribDecisionRequest;
decisions.push(body);
return HttpResponse.json(answer(body));
}),
http.get('/api/admin/places-contribute/log', () =>
HttpResponse.json({ entries: [], total: 0, page: 1, perPage: 20 })
)
);
return decisions;
}
describe('PlaceContribPanel', () => {
it('FE-ADMIN-CONTRIB-001: an undecided admin gets the prompt with every field switched on', async () => {
serve(UNDECIDED);
render(<PlaceContribPanel />);
const dialog = await screen.findByRole('dialog');
expect(within(dialog).getByText('admin.contribute.prompt.title')).toBeInTheDocument();
for (const field of Object.keys(ON)) {
expect(within(dialog).getByRole('button', { name: `admin.contribute.field.${field}` })).toHaveAttribute(
'aria-pressed',
'true'
);
}
expect(within(dialog).getByText('admin.contribute.never.notes')).toBeInTheDocument();
expect(within(dialog).getByText('admin.contribute.never.providers')).toBeInTheDocument();
});
it('FE-ADMIN-CONTRIB-002: nothing is decided until a button is pressed, and Agree sends the switches it shows', async () => {
const decisions = serve(UNDECIDED, () => AGREED);
render(<PlaceContribPanel />);
const dialog = await screen.findByRole('dialog');
expect(decisions).toHaveLength(0);
await userEvent.click(within(dialog).getByRole('button', { name: 'admin.contribute.field.image' }));
await userEvent.click(within(dialog).getByRole('button', { name: 'admin.contribute.prompt.agree' }));
await waitFor(() => expect(decisions).toHaveLength(1));
expect(decisions[0]).toEqual({ action: 'agree', termsVersion: 1, fields: { ...ON, image: false } });
await waitFor(() => expect(screen.queryByRole('dialog')).toBeNull());
expect(screen.getByText('admin.contribute.status.active')).toBeInTheDocument();
});
it('FE-ADMIN-CONTRIB-003: Agree is unavailable with every field off', async () => {
serve(UNDECIDED);
render(<PlaceContribPanel />);
const dialog = await screen.findByRole('dialog');
for (const field of Object.keys(ON)) {
await userEvent.click(within(dialog).getByRole('button', { name: `admin.contribute.field.${field}` }));
}
expect(within(dialog).getByRole('button', { name: 'admin.contribute.prompt.agree' })).toBeDisabled();
});
it('FE-ADMIN-CONTRIB-004: "not now" snoozes and "no" declines for the current terms', async () => {
const decisions = serve(UNDECIDED, () => ({ ...UNDECIDED, showPrompt: false }));
const { unmount } = render(<PlaceContribPanel />);
await userEvent.click(
within(await screen.findByRole('dialog')).getByRole('button', { name: 'admin.contribute.prompt.snooze' })
);
await waitFor(() => expect(decisions).toEqual([{ action: 'snooze' }]));
unmount();
render(<PlaceContribPanel />);
await userEvent.click(
within(await screen.findByRole('dialog')).getByRole('button', { name: 'admin.contribute.prompt.decline' })
);
await waitFor(() => expect(decisions[1]).toEqual({ action: 'decline', termsVersion: 1 }));
});
it('FE-ADMIN-CONTRIB-005: closing the prompt decides nothing', async () => {
const decisions = serve(UNDECIDED);
render(<PlaceContribPanel />);
await screen.findByRole('dialog');
await userEvent.keyboard('{Escape}');
await waitFor(() => expect(screen.queryByRole('dialog')).toBeNull());
expect(decisions).toHaveLength(0);
});
it('FE-ADMIN-CONTRIB-006: an agreement shows its figures and a switch per field', async () => {
serve(AGREED);
render(<PlaceContribPanel />);
expect(await screen.findByText('admin.contribute.status.active')).toBeInTheDocument();
expect(screen.getByText('42')).toBeInTheDocument();
expect(screen.getByText('7')).toBeInTheDocument();
expect(screen.getByRole('button', { name: 'admin.contribute.field.phone' })).toHaveAttribute(
'aria-pressed',
'true'
);
expect(screen.queryByRole('dialog')).toBeNull();
});
it('FE-ADMIN-CONTRIB-007: switching a field off sends the new switches', async () => {
const decisions = serve(AGREED);
render(<PlaceContribPanel />);
await userEvent.click(await screen.findByRole('button', { name: 'admin.contribute.field.description' }));
await waitFor(() => expect(decisions).toEqual([{ action: 'fields', fields: { ...ON, description: false } }]));
});
it('FE-ADMIN-CONTRIB-008: the master switch asks before it stops sharing', async () => {
const decisions = serve(AGREED, () => ({
...AGREED,
active: false,
consent: { ...AGREED.consent, enabled: false, decision: 'off' },
}));
render(<PlaceContribPanel />);
await userEvent.click(await screen.findByRole('button', { name: 'admin.contribute.title' }));
expect(decisions).toHaveLength(0);
await userEvent.click(screen.getByRole('button', { name: 'admin.contribute.offConfirm' }));
await waitFor(() => expect(decisions).toEqual([{ action: 'off' }]));
});
it('FE-ADMIN-CONTRIB-009: an installation that cannot share says why and has no prompt', async () => {
serve({ ...UNDECIDED, eligible: false, ineligibleReason: 'custom_places_url', showPrompt: false });
render(<PlaceContribPanel />);
expect(await screen.findByText('admin.contribute.ineligible.custom_places_url')).toBeInTheDocument();
expect(screen.getByRole('button', { name: 'admin.contribute.title' })).toBeDisabled();
expect(screen.queryByRole('dialog')).toBeNull();
});
it('FE-ADMIN-CONTRIB-010: open registration is named in the prompt', async () => {
serve({ ...UNDECIDED, registrationOpen: true });
render(<PlaceContribPanel />);
expect(
await within(await screen.findByRole('dialog')).findByText('admin.contribute.prompt.openRegistration')
).toBeInTheDocument();
});
it('FE-ADMIN-CONTRIB-011: asks again while the key is still being fetched, and the prompt follows', async () => {
vi.useFakeTimers({ shouldAdvanceTime: true });
try {
let reads = 0;
server.use(
http.get('/api/admin/places-contribute', () => {
reads += 1;
return HttpResponse.json(
reads === 1 ? { ...UNDECIDED, eligible: false, ineligibleReason: 'no_key', showPrompt: false } : UNDECIDED
);
})
);
render(<PlaceContribPanel />);
expect(await screen.findByText('admin.contribute.ineligible.no_key')).toBeInTheDocument();
await vi.advanceTimersByTimeAsync(3_000);
expect(await screen.findByRole('dialog')).toBeInTheDocument();
expect(reads).toBe(2);
} finally {
vi.useRealTimers();
}
});
});
@@ -0,0 +1,200 @@
import type { PlaceContribField, PlaceContribState } from '@trek/shared';
import { ChevronRight, HeartHandshake, Undo2 } from 'lucide-react';
import { useState } from 'react';
import { useTranslation } from '../../i18n';
import type { TranslationFn } from '../../types';
import { getApiErrorMessage } from '../../utils/apiError';
import { SettingsCard, StatusPill } from '../Settings/settingsKit';
import ToggleSwitch from '../Settings/ToggleSwitch';
import ConfirmDialog from '../shared/ConfirmDialog';
import { fs } from '../shared/DialogShell';
import { useToast } from '../shared/Toast';
import { FigureBadge } from '../Tours/paddle/FigureBadge';
import PlaceContribLog from './PlaceContribLog';
import {
contribNote,
contribStatus,
fieldEntries,
fieldLabel,
refusalReason,
type ContribStatus,
} from './placeContribModel';
import PlaceContribPrompt from './PlaceContribPrompt';
import { usePlaceContrib } from './usePlaceContrib';
const PILL_TONE: Record<ContribStatus, 'success' | 'warning' | 'neutral'> = {
active: 'success',
paused: 'warning',
off: 'neutral',
unavailable: 'neutral',
};
function Figures({ state, t }: { state: PlaceContribState; t: TranslationFn }) {
const { locale } = useTranslation();
const number = new Intl.NumberFormat(locale);
const last = state.lastSuccessDay
? new Intl.DateTimeFormat(locale, { day: 'numeric', month: 'short' }).format(
new Date(`${state.lastSuccessDay}T12:00:00`)
)
: t('admin.contribute.never');
return (
<div className="flex flex-wrap gap-1.5">
<FigureBadge
label={t('admin.contribute.figure.accepted')}
value={number.format(state.counts.accepted)}
info={t('admin.contribute.figure.acceptedInfo')}
/>
<FigureBadge
label={t('admin.contribute.figure.queue')}
value={number.format(state.queue.size)}
tone={state.queue.full ? 'warning' : 'neutral'}
info={state.queue.full ? t('admin.contribute.figure.queueFull') : undefined}
/>
<FigureBadge label={t('admin.contribute.figure.last')} value={last} />
</div>
);
}
/**
* Sharing place details with the TREK Places API, inside the TREK API card:
* one switch for the installation, one per field, the transmission log and the
* way to take everything back. Turning it on for the first time opens the same
* prompt an admin gets on the first visit, so an agreement always comes from it.
*/
export default function PlaceContribPanel() {
const { t } = useTranslation();
const toast = useToast();
const contrib = usePlaceContrib();
const { state } = contrib;
const [prompting, setPrompting] = useState<boolean | null>(null);
const [confirm, setConfirm] = useState<'off' | 'withdraw' | null>(null);
if (!state) return null;
const status = contribStatus(state);
const agreed = state.consent.decision === 'agreed' && state.consent.termsVersion === state.termsVersion;
// The prompt opens by itself once per visit while the server asks for it.
const showPrompt = prompting ?? state.showPrompt;
const fail = (err: unknown) => {
const reason = refusalReason(err);
toast.error(
reason === 'terms_outdated' || reason === 'no_field'
? t(`admin.contribute.refused.${reason}`)
: getApiErrorMessage(err, t('common.error'))
);
};
const toggleField = (field: PlaceContribField) => {
const fields = { ...state.consent.fields, [field]: !state.consent.fields[field] };
if (!Object.values(fields).some(Boolean)) {
setConfirm('off');
return;
}
contrib.decide({ action: 'fields', fields }).catch(fail);
};
const withdraw = () => {
setConfirm(null);
contrib.withdraw().then((r) => {
const total = Object.values(r.withdrawn).reduce((a, b) => a + b, 0);
toast.success(t('admin.contribute.withdrawn', { total }));
}, fail);
};
return (
<SettingsCard
flush
icon={HeartHandshake}
title={t('admin.contribute.title')}
badge={<StatusPill tone={PILL_TONE[status]}>{t(`admin.contribute.status.${status}`)}</StatusPill>}
hint={contribNote(t, state)}
action={
<ToggleSwitch
on={agreed && state.consent.enabled}
label={t('admin.contribute.title')}
disabled={!state.eligible || contrib.busy}
onToggle={() => (agreed && state.consent.enabled ? setConfirm('off') : setPrompting(true))}
/>
}
bodyClassName="flex flex-col gap-3 p-4"
>
{agreed && state.consent.enabled && (
<>
<Figures state={state} t={t} />
<ul className="m-0 grid list-none grid-cols-2 gap-1.5 p-0 max-sm:grid-cols-1">
{fieldEntries(state.consent.fields).map(([field, on]) => (
<li
key={field}
className="flex items-center justify-between gap-3 rounded-[12px] border border-edge-faint bg-surface-card px-3 py-1.5"
>
<span className={on ? 'text-content' : 'text-content-faint'} style={fs(12.5, 'body')}>
{fieldLabel(t, field)}
</span>
<ToggleSwitch
on={on}
label={fieldLabel(t, field)}
disabled={contrib.busy}
onToggle={() => toggleField(field)}
/>
</li>
))}
</ul>
</>
)}
{(agreed || state.consent.decision === 'off') && (
<details className="group overflow-hidden rounded-[12px] border border-edge-faint bg-surface-card">
{/* The admin page's fold head (pages/admin/FoldSummary), which a component cannot import. */}
<summary className="flex cursor-pointer list-none items-center gap-2.5 px-3.5 py-2.5 hover:bg-surface-hover focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-[color:var(--text-primary)] [&::-webkit-details-marker]:hidden">
<ChevronRight
size={15}
strokeWidth={2}
className="flex-none text-content-faint transition-transform group-open:rotate-90"
aria-hidden="true"
/>
<span className="font-medium text-content" style={fs(12.5, 'body')}>
{t('admin.contribute.log.title')}
</span>
</summary>
<div className="flex flex-col gap-3 border-t border-edge-faint p-3">
<PlaceContribLog />
<button
type="button"
disabled={contrib.busy}
onClick={() => setConfirm('withdraw')}
className="inline-flex items-center gap-1.5 self-start rounded-lg border border-edge-faint bg-surface-card px-3 py-1.5 font-medium text-danger hover:bg-danger-soft disabled:opacity-40"
style={fs(12.5, 'body')}
>
<Undo2 size={14} aria-hidden="true" />
{t('admin.contribute.withdraw')}
</button>
</div>
</details>
)}
{showPrompt && state.eligible && (
<PlaceContribPrompt state={state} contrib={contrib} onClose={() => setPrompting(false)} />
)}
<ConfirmDialog
isOpen={confirm === 'off'}
onClose={() => setConfirm(null)}
onConfirm={() => {
setConfirm(null);
contrib.decide({ action: 'off' }).catch(fail);
}}
title={t('admin.contribute.offTitle')}
message={t('admin.contribute.offMessage')}
confirmLabel={t('admin.contribute.offConfirm')}
/>
<ConfirmDialog
isOpen={confirm === 'withdraw'}
onClose={() => setConfirm(null)}
onConfirm={withdraw}
title={t('admin.contribute.withdrawTitle')}
message={t('admin.contribute.withdrawMessage')}
confirmLabel={t('admin.contribute.withdraw')}
danger
/>
</SettingsCard>
);
}
@@ -0,0 +1,198 @@
import type { PlaceContribFieldSwitches, PlaceContribState } from '@trek/shared';
import { Check, HeartHandshake, ShieldCheck, TriangleAlert, X } from 'lucide-react';
import { useState } from 'react';
import { useTranslation } from '../../i18n';
import { getApiErrorMessage } from '../../utils/apiError';
import ToggleSwitch from '../Settings/ToggleSwitch';
import {
DialogButton,
DialogFooter,
DialogHeader,
DialogShell,
DialogTile,
FooterSpacer,
fs,
NEUTRAL_TINT,
} from '../shared/DialogShell';
import { useToast } from '../shared/Toast';
import { ALL_FIELDS_ON, fieldEntries, fieldLabel, refusalReason } from './placeContribModel';
import type { usePlaceContrib } from './usePlaceContrib';
const NEVER = ['notes', 'files', 'trips', 'people', 'providers'] as const;
/**
* The question an admin gets once: share what this installation's users type
* about places with every other TREK. Asked warmly and with every field already
* on, because saying yes is the point of asking; but nothing leaves before the
* admin presses Agree, and "not now" and "no" are as easy to reach.
*
* Closing the dialog decides nothing: it comes back on the next visit until one
* of the three buttons is pressed.
*/
export default function PlaceContribPrompt({
state,
contrib,
onClose,
}: {
state: PlaceContribState;
contrib: ReturnType<typeof usePlaceContrib>;
onClose: () => void;
}) {
const { t } = useTranslation();
const toast = useToast();
const [fields, setFields] = useState<PlaceContribFieldSwitches>(() =>
state.consent.decision === 'agreed' || state.consent.decision === 'off' ? state.consent.fields : ALL_FIELDS_ON
);
const none = !Object.values(fields).some(Boolean);
const run = async (body: Parameters<typeof contrib.decide>[0], done?: string) => {
try {
await contrib.decide(body);
if (done) toast.success(done);
onClose();
} catch (err) {
const reason = refusalReason(err);
toast.error(
reason === 'terms_outdated' || reason === 'no_field'
? t(`admin.contribute.refused.${reason}`)
: getApiErrorMessage(err, t('common.error'))
);
}
};
return (
<DialogShell
onClose={onClose}
labelledBy="place-contrib-prompt-title"
width="detail"
blocked={contrib.busy}
header={
<DialogHeader
tile={
<DialogTile>
<HeartHandshake size={22} className="text-content" aria-hidden="true" />
</DialogTile>
}
tint={NEUTRAL_TINT}
labelId="place-contrib-prompt-title"
eyebrow="TREK Places API"
title={t('admin.contribute.prompt.title')}
onClose={onClose}
/>
}
footer={
<DialogFooter>
<DialogButton
disabled={contrib.busy}
onClick={() => void run({ action: 'decline', termsVersion: state.termsVersion })}
>
{t('admin.contribute.prompt.decline')}
</DialogButton>
<FooterSpacer />
<DialogButton disabled={contrib.busy} onClick={() => void run({ action: 'snooze' })}>
{t('admin.contribute.prompt.snooze')}
</DialogButton>
<DialogButton
variant="primary"
autoFocus
disabled={contrib.busy || none}
icon={<HeartHandshake size={15} aria-hidden="true" />}
onClick={() =>
void run(
{ action: 'agree', termsVersion: state.termsVersion, fields },
t('admin.contribute.prompt.thanks')
)
}
>
{t('admin.contribute.prompt.agree')}
</DialogButton>
</DialogFooter>
}
>
<div className="flex flex-col gap-2">
<p className="m-0 leading-relaxed text-content" style={fs(14, 'body')}>
{t('admin.contribute.prompt.lead')}
</p>
<p className="m-0 leading-relaxed text-content-secondary" style={fs(13, 'body')}>
{t('admin.contribute.prompt.why')}
</p>
</div>
<section className="flex flex-col gap-2" aria-labelledby="place-contrib-prompt-fields">
<h3 id="place-contrib-prompt-fields" className="m-0 font-semibold text-content" style={fs(13, 'body')}>
{t('admin.contribute.prompt.whatLabel')}
</h3>
<ul className="m-0 grid list-none grid-cols-2 gap-1.5 p-0 max-sm:grid-cols-1">
{fieldEntries(fields).map(([field, on]) => (
<li
key={field}
className="flex items-center justify-between gap-3 rounded-[12px] border border-edge-faint bg-surface-secondary px-3 py-2"
>
<span className="flex min-w-0 items-center gap-2 text-content" style={fs(13, 'body')}>
<Check
size={14}
strokeWidth={2.4}
className={on ? 'text-success' : 'text-content-faint opacity-40'}
aria-hidden="true"
/>
<span className="truncate">{fieldLabel(t, field)}</span>
</span>
<ToggleSwitch
on={on}
label={fieldLabel(t, field)}
onToggle={() => setFields((f) => ({ ...f, [field]: !f[field] }))}
/>
</li>
))}
</ul>
<p className="m-0 leading-normal text-content-faint" style={fs(11.5)}>
{t('admin.contribute.prompt.imageNote')}
</p>
</section>
<section
className="flex flex-col gap-2 rounded-[14px] border border-edge-faint bg-surface-secondary p-3"
aria-labelledby="place-contrib-prompt-never"
>
<h3
id="place-contrib-prompt-never"
className="m-0 flex items-center gap-1.5 font-semibold text-content"
style={fs(13, 'body')}
>
<ShieldCheck size={15} className="text-success" aria-hidden="true" />
{t('admin.contribute.prompt.neverLabel')}
</h3>
<ul className="m-0 flex list-none flex-wrap gap-1.5 p-0">
{NEVER.map((item) => (
<li
key={item}
className="inline-flex items-center gap-1 rounded-full border border-edge-faint bg-surface-card px-2.5 py-[3px] font-medium text-content-secondary"
style={fs(11.5)}
>
<X size={12} strokeWidth={2.4} className="text-content-faint" aria-hidden="true" />
{t(`admin.contribute.never.${item}`)}
</li>
))}
</ul>
<p className="m-0 leading-normal text-content-muted" style={fs(12, 'body')}>
{t('admin.contribute.prompt.how')}
</p>
</section>
{state.registrationOpen && (
<p
className="m-0 flex items-start gap-2 rounded-[12px] bg-warning-soft px-3 py-2 leading-normal text-warning"
style={fs(12, 'body')}
role="note"
>
<TriangleAlert size={15} className="mt-[1px] flex-none" aria-hidden="true" />
{t('admin.contribute.prompt.openRegistration')}
</p>
)}
<p className="m-0 text-content-faint" style={fs(11.5)}>
{t('admin.contribute.prompt.footnote')}
</p>
</DialogShell>
);
}
@@ -1,11 +1,12 @@
import type { ServiceAllowance, ServiceIdentityState, ServiceIdentityStatus, ServiceQuotaView } from '@trek/shared';
import { MapPin, RefreshCw, Route, Search, type LucideIcon } from 'lucide-react';
import { MapPin, RefreshCw, Route, Search, Signal, type LucideIcon } from 'lucide-react';
import { useRef, useState } from 'react';
import { useTranslation } from '../../i18n';
import { useSettingsStore } from '../../store/settingsStore';
import type { TranslationFn } from '../../types';
import { getApiErrorMessage } from '../../utils/apiError';
import { formatClockTime } from '../../utils/formatters';
import { SettingsCard } from '../Settings/settingsKit';
import ConfirmDialog from '../shared/ConfirmDialog';
import { useToast } from '../shared/Toast';
import { FigureBadge } from '../Tours/paddle/FigureBadge';
@@ -121,7 +122,7 @@ function stateHint(t: TranslationFn, status: ServiceIdentityStatus | null, faile
export default function ServiceIdentityPanel({ managed = false }: { managed?: boolean }) {
const { t } = useTranslation();
const toast = useToast();
const panel = useRef<HTMLElement>(null);
const panel = useRef<HTMLDivElement>(null);
const { status, failed, regenerating, regenerate } = useServiceIdentity(panel);
const [confirming, setConfirming] = useState(false);
const resetAt = useResetTime(status);
@@ -140,57 +141,66 @@ export default function ServiceIdentityPanel({ managed = false }: { managed?: bo
const canRegenerate = !managed && status !== null && status.keySource !== 'env' && status.state !== 'off';
return (
<section
ref={panel}
aria-label={t('admin.trekApi.quota.title')}
className="flex flex-col gap-3 rounded-xl border border-edge-faint bg-surface-secondary p-3"
>
<div className="flex flex-wrap items-center justify-between gap-2">
<p className="m-0 inline-flex h-[26px] items-center gap-2 rounded-full bg-surface-card px-2.5 text-caption font-semibold text-content shadow-sm">
<span aria-hidden="true" className={`h-2 w-2 flex-none rounded-full ${STATE_DOT[status?.state ?? 'off']}`} />
{status ? t(`admin.trekApi.quota.state.${status.state}`) : t('admin.trekApi.quota.title')}
</p>
<div className="flex flex-wrap items-center gap-1.5">
{status?.tier && <FigureBadge value={t(`admin.trekApi.quota.tier.${status.tier}`)} />}
{status?.keySource === 'env' && (
<FigureBadge
label={t('admin.trekApi.quota.key')}
value="TREK_SERVICES_KEY"
info={t('admin.trekApi.quota.envKey')}
<div ref={panel}>
<SettingsCard
flush
icon={Signal}
title={t('admin.trekApi.quota.title')}
badge={
<span className="inline-flex items-center gap-1.5 rounded-full bg-surface-card px-2 py-[2px] text-caption font-semibold text-content shadow-sm">
<span
aria-hidden="true"
className={`h-2 w-2 flex-none rounded-full ${STATE_DOT[status?.state ?? 'off']}`}
/>
)}
{resetAt && <FigureBadge label={t('admin.trekApi.quota.resets')} value={resetAt} />}
</div>
</div>
{status ? t(`admin.trekApi.quota.state.${status.state}`) : '…'}
</span>
}
action={
<>
{status?.tier && <FigureBadge value={t(`admin.trekApi.quota.tier.${status.tier}`)} />}
{status?.keySource === 'env' && (
<FigureBadge
label={t('admin.trekApi.quota.key')}
value="TREK_SERVICES_KEY"
info={t('admin.trekApi.quota.envKey')}
/>
)}
{resetAt && <FigureBadge label={t('admin.trekApi.quota.resets')} value={resetAt} />}
</>
}
>
{status && status.services.length > 0 && (
<ul
aria-label={t('admin.trekApi.quota.title')}
className="m-0 grid list-none grid-cols-1 gap-2 p-0 sm:grid-cols-3"
>
{status.services.map((allowance) => (
<ServiceTile key={allowance.service} allowance={allowance} />
))}
</ul>
)}
{hint && <p className="m-0 text-caption leading-snug text-content-muted">{hint}</p>}
{status && status.services.length > 0 && (
<ul
aria-label={t('admin.trekApi.quota.title')}
className="m-0 grid list-none grid-cols-1 gap-2 p-0 sm:grid-cols-3"
>
{status.services.map((allowance) => (
<ServiceTile key={allowance.service} allowance={allowance} />
))}
</ul>
)}
{hint && <p className="m-0 text-caption leading-snug text-content-muted">{hint}</p>}
{canRegenerate && (
<button
type="button"
onClick={() => setConfirming(true)}
disabled={regenerating}
className="inline-flex items-center gap-1.5 self-start rounded-lg text-caption font-medium text-content-secondary hover:text-content disabled:opacity-50"
>
<RefreshCw
size={13}
strokeWidth={2}
className={regenerating ? 'motion-safe:animate-spin' : ''}
aria-hidden="true"
/>
{t('admin.trekApi.quota.regenerate')}
</button>
)}
{/* The one action, on a rule of its own below the figures. */}
{canRegenerate && (
<div className="-mx-4 -mb-4 flex items-center justify-end border-t border-edge-faint px-4 py-2.5">
<button
type="button"
onClick={() => setConfirming(true)}
disabled={regenerating}
className="inline-flex items-center gap-1.5 rounded-lg border border-edge-faint bg-surface-card px-2.5 py-1 text-caption font-medium text-content-secondary shadow-sm hover:bg-surface-hover hover:text-content disabled:opacity-50"
>
<RefreshCw
size={13}
strokeWidth={2}
className={regenerating ? 'motion-safe:animate-spin' : ''}
aria-hidden="true"
/>
{t('admin.trekApi.quota.regenerate')}
</button>
</div>
)}
</SettingsCard>
<ConfirmDialog
isOpen={confirming}
@@ -201,6 +211,6 @@ export default function ServiceIdentityPanel({ managed = false }: { managed?: bo
confirmLabel={t('admin.trekApi.quota.regenerate')}
danger={false}
/>
</section>
</div>
);
}
@@ -0,0 +1,45 @@
import {
PLACE_CONTRIB_FIELDS,
type PlaceContribField,
type PlaceContribFieldSwitches,
type PlaceContribState,
} from '@trek/shared';
import type { TranslationFn } from '../../types';
/** Every switch on: what the prompt proposes, and what an installation that never decided reads as. */
export const ALL_FIELDS_ON: PlaceContribFieldSwitches = {
website: true,
phone: true,
email: true,
opening_hours: true,
description: true,
image: true,
};
export const fieldLabel = (t: TranslationFn, field: PlaceContribField): string => t(`admin.contribute.field.${field}`);
/** The switches as a list, in the order the contract names the fields. */
export const fieldEntries = (switches: PlaceContribFieldSwitches): [PlaceContribField, boolean][] =>
PLACE_CONTRIB_FIELDS.map((field) => [field, switches[field]]);
export type ContribStatus = 'active' | 'paused' | 'off' | 'unavailable';
/** Where sharing stands, as the pill beside the title says it. */
export function contribStatus(state: PlaceContribState): ContribStatus {
if (!state.eligible) return 'unavailable';
if (!state.active) return 'off';
return state.pauseReason ? 'paused' : 'active';
}
/** The sentence under the title: why it cannot run, why it waits, or what it does. */
export function contribNote(t: TranslationFn, state: PlaceContribState): string {
if (!state.eligible && state.ineligibleReason) return t(`admin.contribute.ineligible.${state.ineligibleReason}`);
if (state.active && state.pauseReason) return t(`admin.contribute.pause.${state.pauseReason}`);
return t(state.active ? 'admin.contribute.noteActive' : 'admin.contribute.noteOff');
}
/** The refusal a decision can meet, as the server names it in `reason`, or null for any other failure. */
export function refusalReason(err: unknown): string | null {
const reason = (err as { response?: { data?: { reason?: unknown } } } | null)?.response?.data?.reason;
return typeof reason === 'string' && reason ? reason : null;
}
@@ -0,0 +1,31 @@
// FE-ADMIN-CONTRIBHOOK-001
import { act, renderHook, waitFor } from '@testing-library/react';
import type { PlaceContribState } from '@trek/shared';
import { afterEach, describe, expect, it, vi } from 'vitest';
import { placeContribRepo } from '../../repo/placeContribRepo';
import { usePlaceContrib } from './usePlaceContrib';
const STATE = { ineligibleReason: null, active: true } as unknown as PlaceContribState;
afterEach(() => {
vi.restoreAllMocks();
});
describe('usePlaceContrib', () => {
it('FE-ADMIN-CONTRIBHOOK-001: a withdrawal that went through is answered even when the state cannot be read again', async () => {
const state = vi.spyOn(placeContribRepo, 'state').mockResolvedValueOnce(STATE);
vi.spyOn(placeContribRepo, 'withdraw').mockResolvedValue({ withdrawn: { website: 2 }, cleared: 1 });
const { result } = renderHook(() => usePlaceContrib());
await waitFor(() => expect(result.current.state).toBe(STATE));
state.mockRejectedValueOnce(new Error('offline'));
let answer: unknown;
await act(async () => {
answer = await result.current.withdraw();
});
expect(answer).toEqual({ withdrawn: { website: 2 }, cleared: 1 });
expect(result.current.state).toBe(STATE);
expect(result.current.busy).toBe(false);
});
});
@@ -0,0 +1,65 @@
import type { PlaceContribDecisionRequest, PlaceContribState } from '@trek/shared';
import { useCallback, useEffect, useState } from 'react';
import { placeContribRepo } from '../../repo/placeContribRepo';
const KEY_RETRIES = 6;
const KEY_RETRY_MS = 3_000;
/**
* The admin's decision on sharing place details. Read once when the settings
* tab opens, so the prompt can come up without the card being scrolled to;
* every decision answers the new state, which replaces the old one.
*/
export function usePlaceContrib() {
const [state, setState] = useState<PlaceContribState | null>(null);
const [failed, setFailed] = useState(false);
const [busy, setBusy] = useState(false);
useEffect(() => {
const controller = new AbortController();
let timer: ReturnType<typeof setTimeout> | undefined;
// A fresh installation fetches its key on first use, so the first answer can
// be no_key; asking again a few times lets the prompt appear once it landed.
const read = (tries: number) => {
placeContribRepo.state(controller.signal).then(
(next) => {
setState(next);
if (next.ineligibleReason === 'no_key' && tries > 1) timer = setTimeout(() => read(tries - 1), KEY_RETRY_MS);
},
() => {
if (!controller.signal.aborted) setFailed(true);
}
);
};
read(KEY_RETRIES);
return () => {
controller.abort();
clearTimeout(timer);
};
}, []);
const decide = useCallback(async (body: PlaceContribDecisionRequest): Promise<PlaceContribState> => {
setBusy(true);
try {
const next = await placeContribRepo.decide(body);
setState(next);
return next;
} finally {
setBusy(false);
}
}, []);
const withdraw = useCallback(async () => {
setBusy(true);
try {
const result = await placeContribRepo.withdraw();
// The withdrawal went through; a failed re-read keeps the old state rather than reporting it failed.
await placeContribRepo.state().then(setState, () => undefined);
return result;
} finally {
setBusy(false);
}
}, []);
return { state, failed, busy, decide, withdraw };
}
@@ -20,7 +20,10 @@ const trip = (id: number, start: string | null, end: string | null) => ({
end_date: end,
});
afterEach(() => vi.restoreAllMocks());
afterEach(() => {
vi.useRealTimers();
vi.restoreAllMocks();
});
describe('rankPickerTrips', () => {
it('FE-AI-PICK-001: the running trip leads, then the soonest to come, then the latest past one', () => {
@@ -59,6 +62,9 @@ describe('rankPickerTrips', () => {
describe('useAssistantTripPicker', () => {
it('FE-AI-PICK-004: loads the trips once and ranks them; a failed load offers none', async () => {
// The hook ranks against the real clock; pin it so trip 7 keeps running.
vi.useFakeTimers({ shouldAdvanceTime: true, toFake: ['Date'] });
vi.setSystemTime(new Date(`${TODAY}T12:00:00`));
const list = vi
.spyOn(tripRepo, 'list')
.mockResolvedValueOnce({ trips: [trip(7, '2026-10-01', '2026-10-30') as Trip], archivedTrips: [] });
@@ -1,6 +1,6 @@
import { useEffect, useId, useRef, useState } from 'react'
import { Copy, Mail, Phone, RotateCcw, X } from 'lucide-react'
import type { PlaceOpeningHours } from '@trek/shared'
import type { PlaceClientOrigin, PlaceOpeningHours } from '@trek/shared'
import CustomTimePicker from '../shared/CustomTimePicker'
import { Tooltip } from '../shared/Tooltip'
import { DialogSection, fs } from '../shared/DialogShell'
@@ -16,7 +16,8 @@ interface Props {
email: string
/** The stored hours text (JSON), empty when the place has none of its own. */
openingHours: string
onChange: (field: 'phone' | 'email' | 'opening_hours', value: string) => void
/** `origin` is set when the hours were taken over from the details lookup rather than typed. */
onChange: (field: 'phone' | 'email' | 'opening_hours', value: string, origin?: PlaceClientOrigin) => void
/**
* The hours the place details column looked up, as a week. A place without
* hours of its own takes them over on its own; one that has some gets a
@@ -51,11 +52,11 @@ export function PlaceContactFields({ id: anchorId, phone, email, openingHours, o
if (openingHours) setEditing(true)
}, [openingHours])
const setWeek = (next: PlaceOpeningHours) => {
const setWeek = (next: PlaceOpeningHours, origin?: PlaceClientOrigin) => {
setDraft(next)
const text = writeWeek(cleanWeek(next))
written.current = text
onChange('opening_hours', text)
onChange('opening_hours', text, origin)
}
const setDay = (i: number, patch: Partial<PlaceOpeningHours[number]>) =>
setWeek(week.map((day, d) => (d === i ? { ...day, ...patch } : day)))
@@ -68,7 +69,7 @@ export function PlaceContactFields({ id: anchorId, phone, email, openingHours, o
if (!suggestedHours || adopted.current === suggestedHours) return
adopted.current = suggestedHours
if (written.current) return
setWeek(suggestedHours)
setWeek(suggestedHours, 'enrichment')
setEditing(true)
// setWeek only reads refs and setters; the lookup is the trigger.
}, [suggestedHours])
@@ -99,7 +100,7 @@ export function PlaceContactFields({ id: anchorId, phone, email, openingHours, o
<div className="flex items-center gap-1">
{canTakeOver && (
<Tooltip label={t('places.hoursFromDetails')}>
<button type="button" onClick={() => setWeek(suggestedHours!)} aria-label={t('places.hoursFromDetails')}
<button type="button" onClick={() => setWeek(suggestedHours!, 'enrichment')} aria-label={t('places.hoursFromDetails')}
className="grid h-7 w-7 place-items-center rounded-full text-content-faint hover:bg-surface-hover hover:text-content">
<RotateCcw size={13} strokeWidth={2} />
</button>
@@ -308,49 +308,17 @@ export default function PlaceDetailsColumn({
t={t}
/>
<FactList facts={data?.facts ?? []} dialog={dialog} t={t} />
<DescriptionBlock description={data?.description ?? null} dialog={dialog} t={t} />
<DescriptionBlock
description={data?.description ?? null}
dialog={dialog}
t={t}
onAdopt={() => data?.description && onAdoptDescription(data.description.text)}
adoptBlocked={hasDescription}
adoptBlockedId={adoptBlockedId}
/>
</>
)}
</div>
{/* Pinned, not scrolled. Adopting the text is the only thing this column
asks the reader to do, and it used to sit below a description long
enough to push it out of view — the button was there, just never
where anyone looked. */}
{selection && state === 'ready' && !data?.disabled && data?.description && (
<div className={dialog ? 'shrink-0 border-t border-edge-faint p-2.5' : 'shrink-0 border-t border-edge p-2.5'}>
{dialog ? (
// White like the dialog's other secondary buttons. While it is
// blocked the line under it says why, so it needs no tooltip, and
// that line is its description for assistive tech.
<button
type="button"
onClick={() => onAdoptDescription(data.description!.text)}
disabled={hasDescription}
aria-describedby={hasDescription ? adoptBlockedId : undefined}
className={WHITE_BUTTON}
style={fs(13, 'body')}
>
<ArrowRight className="w-3.5 h-3.5" />
{t('places.details.adopt')}
</button>
) : (
<button
type="button"
onClick={() => onAdoptDescription(data.description!.text)}
disabled={hasDescription}
title={hasDescription ? t('places.details.adoptBlocked') : undefined}
className="w-full inline-flex items-center justify-center gap-1.5 rounded-lg px-3 py-2 text-body font-medium bg-accent-subtle text-accent-on hover:bg-accent hover:text-accent-text disabled:opacity-50 disabled:hover:bg-accent-subtle disabled:hover:text-accent-on transition-colors"
>
<ArrowRight className="w-3.5 h-3.5" />
{t('places.details.adopt')}
</button>
)}
{hasDescription && (
<p id={dialog ? adoptBlockedId : undefined} className="mt-1 text-center text-caption text-content-faint">{t('places.details.adoptBlocked')}</p>
)}
</div>
)}
</aside>
)
}
@@ -402,6 +370,8 @@ function descriptionSourceLabel(
return 'Wikivoyage'
case 'wikipedia':
return 'Wikipedia'
case 'community':
return 'TREK Community'
case 'website':
try {
return new URL(sourceUrl || '').hostname.replace(/^www\./, '')
@@ -649,10 +619,16 @@ function DescriptionBlock({
description,
dialog = false,
t,
onAdopt,
adoptBlocked,
adoptBlockedId,
}: {
description: MapsPlaceEnrichmentResult['description']
dialog?: boolean
t: TranslationFn
onAdopt: () => void
adoptBlocked: boolean
adoptBlockedId: string
}): React.ReactElement | null {
if (!description) return null
@@ -690,6 +666,23 @@ function DescriptionBlock({
)}
{description.license && (dialog ? <span>{description.license}</span> : ` · ${description.license}`)}
</p>
{/* Right under the text it copies, so the reader finds it where they
just read. While the form already has a description, the line under
it says why it is off and doubles as its description for assistive tech. */}
<button
type="button"
onClick={onAdopt}
disabled={adoptBlocked}
aria-describedby={adoptBlocked ? adoptBlockedId : undefined}
className={dialog ? WHITE_BUTTON : 'w-full inline-flex items-center justify-center gap-1.5 rounded-lg px-3 py-2 text-body font-medium bg-accent-subtle text-accent-on hover:bg-accent hover:text-accent-text disabled:opacity-50 disabled:hover:bg-accent-subtle disabled:hover:text-accent-on transition-colors'}
style={dialog ? fs(13, 'body') : undefined}
>
<ArrowRight className="w-3.5 h-3.5" />
{t('places.details.adopt')}
</button>
{adoptBlocked && (
<p id={adoptBlockedId} className="text-center text-caption text-content-faint">{t('places.details.adoptBlocked')}</p>
)}
</div>
</Block>
)
@@ -0,0 +1,220 @@
import { Loader2, MapPin, Navigation, Plus, Search } from 'lucide-react';
import { useEffect, useRef, useState, type ReactNode } from 'react';
import type { Category, Place } from '../../types';
import { safeHexColor } from '../../utils/safeColor';
import type { StopKind } from '../Roadtrip/stopKinds';
import { getCategoryIcon } from '../shared/categoryIcons';
import { PillSelect } from '../shared/dialogParts';
import { PILL } from '../shared/DialogShell';
import { NavigationMenu } from '../shared/NavigationMenu';
import { Tooltip } from '../shared/Tooltip';
import { getNavigationTargets, openNavigationTarget } from './placeNavigation';
type Translate = (key: string, params?: Record<string, string | number>) => string;
/** The round pill of the head band: a + or a map pin, an icon and nothing else. */
const ROUND_PILL_BUTTON =
'grid h-[26px] w-[26px] flex-none place-items-center rounded-full bg-surface-card text-content-muted shadow-sm ring-1 ring-edge-faint transition-colors hover:text-content';
interface NewCategoryRow {
open: boolean;
setOpen: (open: boolean) => void;
name: string;
setName: (name: string) => void;
create: () => Promise<void>;
inputId: string;
}
/**
* The head band's pill row. The category to pick, with a round + beside it that
* turns the two into a field for a new one; for a stop on a drive, its kind in
* place of both. Then where the picked place came from, and a spinner while a
* pick is still being looked up.
*/
export function HeaderPills({
kind,
categories,
categoryId,
onCategory,
newCategory,
pickedSource,
busy,
navPlace,
refresh,
t,
}: {
kind?: StopKind;
categories: Category[] | null;
categoryId: string;
onCategory: (id: string) => void;
newCategory: NewCategoryRow;
pickedSource: string | null;
busy: boolean;
/** The place as the form holds it, once it has a position: opens it in a map app (#2178). */
navPlace: NavigablePlace | null;
/** Newer details for a saved place, when a fresh lookup has them (PlaceRefreshPill). */
refresh?: ReactNode;
t: Translate;
}) {
// When the new-category field closes, the field or the button that closed it
// goes with it, and the focus would drop out of the dialog. It comes back to
// the + that opened the field, as a picker's focus comes back to its pill.
const plusRef = useRef<HTMLButtonElement | null>(null);
const wasOpen = useRef(newCategory.open);
useEffect(() => {
const closed = wasOpen.current && !newCategory.open;
wasOpen.current = newCategory.open;
if (!closed) return;
const active = document.activeElement;
if (!active || active === document.body || !active.isConnected) plusRef.current?.focus();
}, [newCategory.open]);
const noCategory = {
label: t('places.noCategory'),
icon: <MapPin size={13} strokeWidth={2.2} className="text-content-faint" />,
};
const options = [
{ value: '', ...noCategory },
...(categories || []).map((c) => {
const Icon = getCategoryIcon(c.icon);
// A string like form.category_id, so the picked option hands back the same
// kind of value the form already keeps.
return {
value: String(c.id),
label: c.name,
icon: <Icon size={13} strokeWidth={2.2} style={{ color: safeHexColor(c.color, '') || 'var(--text-muted)' }} />,
};
}),
];
let lead: ReactNode;
if (kind) {
lead = (
<span className={PILL}>
<kind.Icon size={13} strokeWidth={2.2} style={{ color: kind.color }} />
{t(kind.labelKey)}
</span>
);
} else if (newCategory.open) {
lead = <NewCategoryField {...newCategory} t={t} />;
} else {
lead = (
<>
<PillSelect
label={t('places.formCategory')}
value={categoryId}
onChange={onCategory}
options={options}
fallback={noCategory}
/>
<Tooltip label={t('places.newCategory')}>
<button
ref={plusRef}
type="button"
onClick={() => newCategory.setOpen(true)}
aria-label={t('places.newCategory')}
className={ROUND_PILL_BUTTON}
>
<Plus size={13} strokeWidth={2.4} />
</button>
</Tooltip>
</>
);
}
return (
<>
{lead}
{pickedSource && (
<span className={PILL}>
<Search size={12} strokeWidth={2.2} className="text-content-faint" aria-hidden="true" />
{pickedSource}
</span>
)}
{navPlace && <OpenInMapsPill place={navPlace} t={t} />}
{refresh}
{busy && (
<span className={PILL} role="status" aria-label={t('places.loadingDetails')}>
<Loader2 size={13} className="animate-spin text-content-faint" aria-hidden="true" />
<span className="font-medium text-content-muted">{t('places.loadingDetails')}</span>
</span>
)}
</>
);
}
type NavigablePlace = Pick<Place, 'name' | 'address' | 'lat' | 'lng' | 'google_place_id' | 'google_ftid'>;
/**
* A look at the picked place in a real map before it is saved (#2178): its reviews, its
* photos, whether it is the right branch. The same apps the inspector offers, one tap
* straight away when only one applies.
*/
function OpenInMapsPill({ place, t }: { place: NavigablePlace; t: Translate }) {
const [open, setOpen] = useState(false);
const anchorRef = useRef<HTMLSpanElement>(null);
const targets = getNavigationTargets(place);
if (targets.length === 0) return null;
return (
<span ref={anchorRef} className="inline-flex">
<Tooltip label={t('places.openInMaps')}>
<button
type="button"
aria-label={t('places.openInMaps')}
aria-haspopup={targets.length > 1 ? 'menu' : undefined}
aria-expanded={targets.length > 1 ? open : undefined}
onClick={() => {
if (targets.length === 1) openNavigationTarget(targets[0]);
else setOpen((o) => !o);
}}
className={ROUND_PILL_BUTTON}
>
<Navigation size={13} strokeWidth={2.2} />
</button>
</Tooltip>
{open && <NavigationMenu targets={targets} anchor={anchorRef.current} onClose={() => setOpen(false)} />}
</span>
);
}
/** The new category's name, typed where the category pill was, with its OK and Cancel beside it. */
function NewCategoryField({ inputId, name, setName, create, setOpen, t }: NewCategoryRow & { t: Translate }) {
return (
// One parent for the field and both of its buttons.
<span className="inline-flex flex-wrap items-center gap-1.5">
<input
id={inputId}
type="text"
autoFocus
value={name}
onChange={(e) => setName(e.target.value)}
onKeyDown={(e) => {
// Enter confirms the name, like OK; it never reaches the place's own save.
if (e.key === 'Enter') {
e.preventDefault();
void create();
}
// Escape closes the field, like Cancel, and only the field: marked
// handled, the dialog around it leaves it alone and keeps what is typed.
if (e.key === 'Escape') {
e.preventDefault();
setOpen(false);
}
}}
aria-label={t('places.newCategory')}
placeholder={t('places.categoryNamePlaceholder')}
className="w-48 min-w-0 rounded-full bg-surface-card px-3 py-1 text-content shadow-sm outline-none ring-1 ring-edge-faint placeholder:text-content-faint focus:ring-2 focus:ring-[color:var(--text-primary)]"
/>
<button
type="button"
onClick={() => void create()}
className="rounded-full bg-accent px-3 py-1 font-semibold text-accent-text hover:opacity-90"
>
{t('common.ok')}
</button>
<button type="button" onClick={() => setOpen(false)} className={`${PILL} hover:opacity-80`}>
{t('common.cancel')}
</button>
</span>
);
}
@@ -1,4 +1,5 @@
import type { Assignment, Place, RoadtripStopType } from '@trek/shared'
import type { Assignment, Place, PlaceFieldOrigins, RoadtripStopType } from '@trek/shared'
import { originsAfterPick, resultOrigin } from './placeFieldOrigins'
import { pendingImagePayload, type PendingImagePayload, type PendingPlaceImage } from './placeImageChoice'
import type { PlaceDetailsSelection } from './PlaceDetailsColumn'
@@ -43,6 +44,9 @@ export interface PlaceFormData {
// suggests how long that kind of pause usually takes, and the full form should not
// throw the suggestion away on the way through. Editing a stay is the rail's job.
duration_minutes?: number
// Which shareable fields the user typed and which a pick or the details column filled
// (placeFieldOrigins.ts). Rides along to the save as `fieldOrigins`; never shown.
fieldOrigins?: PlaceFieldOrigins
}
export function isGoogleMapsUrl(input: string): boolean {
@@ -237,6 +241,8 @@ export function mergeResult(
autoFilled: Set<ResultField>,
): PlaceFormData {
const next = { ...prev } as PlaceFormData & Record<string, string | undefined>
const written: string[] = []
const cleared: string[] = []
for (const field of RESULT_FIELDS) {
const raw = result[field]
@@ -245,15 +251,19 @@ export function mergeResult(
if (value) {
next[field] = value
autoFilled.add(field)
written.push(field)
} else if (autoFilled.has(field)) {
// Belonged to the place that is no longer selected.
next[field] = ''
autoFilled.delete(field)
cleared.push(field)
}
// Otherwise the user put it there; leave it alone.
}
return next
// What the pick wrote is the provider's, not the user's, wherever it ends up.
const merged: PlaceFormData = next
return { ...merged, fieldOrigins: originsAfterPick(prev.fieldOrigins, written, cleared, resultOrigin(result)) }
}
// #1152: a manually-added place is treated as a likely duplicate of an existing
+14 -162
View File
@@ -1,5 +1,5 @@
import { useState, useEffect, useRef, useMemo, useCallback, useId, type ReactNode } from 'react'
import type { RoadtripStopType, TourListItem } from '@trek/shared'
import type { PlaceClientOrigin, RoadtripStopType, TourListItem } from '@trek/shared'
import NoteFormatToolbar from '../shared/NoteFormatToolbar'
import { useAuthStore } from '../../store/authStore'
import { useAddonStore } from '../../store/addonStore'
@@ -12,7 +12,7 @@ import { PendingFiles, PlaceImageSection } from './PlaceFormMedia'
import { usePlaceImageField } from './usePlaceImageField'
import { useToast } from '../shared/Toast'
import { Tooltip } from '../shared/Tooltip'
import { Search, Loader2, Plus, RotateCcw, MapPin, Navigation, LocateFixed, PencilLine } from 'lucide-react'
import { Search, RotateCcw, LocateFixed, PencilLine } from 'lucide-react'
import { useTranslation } from '../../i18n'
import { PlaceContactFields } from './PlaceContactFields'
import { weekFromPeriods } from './placeHours'
@@ -24,8 +24,6 @@ import {
import { useNewCategory, usePlaceForm } from './usePlaceForm'
import { usePlaceSearch } from './usePlaceSearch'
import { guessCategoryId } from '@trek/shared'
import { getNavigationTargets, openNavigationTarget } from './placeNavigation'
import { NavigationMenu } from '../shared/NavigationMenu'
import { offersGoogleRetry } from '../../utils/placeSource'
import { safeHexColor } from '../../utils/safeColor'
import { useLocationBias } from '../../hooks/useLocationBias'
@@ -36,14 +34,17 @@ import { NumericInput } from '../shared/NumericInput'
import { formatDistance } from '../../utils/units'
import ServiceStopSection from '../Roadtrip/ServiceStopSection'
import { DEFAULT_SERVICE_KIND, serviceStopChoice, type ServiceStopMode } from '../Roadtrip/manualStop'
import { STOP_KIND_BY_KEY, type StopKind } from '../Roadtrip/stopKinds'
import { STOP_KIND_BY_KEY } from '../Roadtrip/stopKinds'
import { getCategoryIcon } from '../shared/categoryIcons'
import {
DialogShell, DialogHeader, DialogTile, DialogSection, DialogFooter, FooterSpacer, DialogButton, NEUTRAL_TINT, PILL, fs,
DialogShell, DialogHeader, DialogTile, DialogSection, DialogFooter, FooterSpacer, DialogButton, NEUTRAL_TINT, fs,
} from '../shared/DialogShell'
import { EditorField, GRID_2, INPUT, LABEL, PANEL, PillSelect, TEXTAREA } from '../shared/dialogParts'
import { EditorField, GRID_2, INPUT, LABEL, PANEL, TEXTAREA } from '../shared/dialogParts'
import { SoftPill, tintOf } from './planParts'
import { TimeSection } from './PlaceFormTimeSection'
import { HeaderPills } from './PlaceFormHeaderPills'
import { PlaceRefreshPill } from './PlaceRefreshPill'
import { usePlaceRefresh } from './usePlaceRefresh'
// The submit payload mirrors the form, but lat/lng are parsed to numbers and
// category_id is normalised, plus any files chosen before the place existed.
@@ -278,6 +279,7 @@ function usePlaceFormModal(props: PlaceFormModalProps) {
setPickedSource(null)
},
})
const refresh = usePlaceRefresh({ place, form, language: search.language })
/**
* What a stop on a drive might be a second copy of, said while the form is being filled.
@@ -292,9 +294,9 @@ function usePlaceFormModal(props: PlaceFormModalProps) {
return findDuplicatePlace(form, places, { byName: false, byOsmId: true })?.name ?? null
}, [serviceStop, place, form, places])
const handleChange = (field: string, value: string) => {
const handleChange = (field: string, value: string, origin?: PlaceClientOrigin) => {
if (field === 'category_id') categoryGuessedRef.current = false
changeField(field, value)
changeField(field, value, origin)
}
// What is around the pin the form holds (#976).
@@ -425,6 +427,7 @@ function usePlaceFormModal(props: PlaceFormModalProps) {
t,
language: search.language,
locale,
refresh,
timeFormat,
googleAnswers: search.googleAnswers,
placesEnrichEnabled,
@@ -483,10 +486,6 @@ const SIDE_BUTTON = 'grid w-[38px] flex-none place-items-center rounded-[10px] t
* for them; this gives them the eyebrow every other field here has.
*/
const SERVICE_STOP_LABELS = '[&_label]:mb-[5px] [&_label]:block [&_label]:font-geist [&_label]:text-[length:calc(9.5px*var(--fs-scale-caption,1))] [&_label]:font-bold [&_label]:uppercase [&_label]:tracking-[.08em] [&_label]:text-content-faint'
/** A round white button in the head band's pill row, as tall as the pills beside it. */
const ROUND_PILL_BUTTON = 'grid h-[26px] w-[26px] flex-none place-items-center rounded-full bg-surface-card text-content-muted shadow-sm ring-1 ring-edge-faint transition-colors hover:text-content'
type Translate = (key: string, params?: Record<string, string | number>) => string
export default function PlaceFormModal(props: PlaceFormModalProps) {
const S = usePlaceFormModal(props)
@@ -570,6 +569,7 @@ export default function PlaceFormModal(props: PlaceFormModalProps) {
inputId: `${fieldId}-new-category`,
}}
pickedSource={S.pickedSource}
refresh={<PlaceRefreshPill {...S.refresh} onApply={handleChange} locale={S.locale} t={t} />}
busy={isSearchingMaps}
navPlace={form.lat && form.lng ? {
name: form.name, address: form.address, lat: Number(form.lat), lng: Number(form.lng),
@@ -917,7 +917,7 @@ export default function PlaceFormModal(props: PlaceFormModalProps) {
email={form.email ?? ''}
openingHours={form.opening_hours ?? ''}
suggestedHours={S.detailsHours}
onChange={(field, value) => handleChange(field, value)}
onChange={(field, value, origin) => handleChange(field, value, origin)}
/>
{/* Costs — create / view the expense linked to this place (#1298).
@@ -947,154 +947,6 @@ export default function PlaceFormModal(props: PlaceFormModalProps) {
)
}
interface NewCategoryRow {
open: boolean
setOpen: (open: boolean) => void
name: string
setName: (name: string) => void
create: () => Promise<void>
inputId: string
}
/**
* The head band's pill row. The category to pick, with a round + beside it that
* turns the two into a field for a new one; for a stop on a drive, its kind in
* place of both. Then where the picked place came from, and a spinner while a
* pick is still being looked up.
*/
function HeaderPills({ kind, categories, categoryId, onCategory, newCategory, pickedSource, busy, navPlace, t }: {
kind?: StopKind
categories: Category[] | null
categoryId: string
onCategory: (id: string) => void
newCategory: NewCategoryRow
pickedSource: string | null
busy: boolean
/** The place as the form holds it, once it has a position: opens it in a map app (#2178). */
navPlace: NavigablePlace | null
t: Translate
}) {
// When the new-category field closes, the field or the button that closed it
// goes with it, and the focus would drop out of the dialog. It comes back to
// the + that opened the field, as a picker's focus comes back to its pill.
const plusRef = useRef<HTMLButtonElement | null>(null)
const wasOpen = useRef(newCategory.open)
useEffect(() => {
const closed = wasOpen.current && !newCategory.open
wasOpen.current = newCategory.open
if (!closed) return
const active = document.activeElement
if (!active || active === document.body || !active.isConnected) plusRef.current?.focus()
}, [newCategory.open])
const noCategory = { label: t('places.noCategory'), icon: <MapPin size={13} strokeWidth={2.2} className="text-content-faint" /> }
const options = [
{ value: '', ...noCategory },
...(categories || []).map(c => {
const Icon = getCategoryIcon(c.icon)
// A string like form.category_id, so the picked option hands back the same
// kind of value the form already keeps.
return { value: String(c.id), label: c.name, icon: <Icon size={13} strokeWidth={2.2} style={{ color: safeHexColor(c.color, '') || 'var(--text-muted)' }} /> }
}),
]
let lead: ReactNode
if (kind) {
lead = <span className={PILL}><kind.Icon size={13} strokeWidth={2.2} style={{ color: kind.color }} />{t(kind.labelKey)}</span>
} else if (newCategory.open) {
lead = <NewCategoryField {...newCategory} t={t} />
} else {
lead = (
<>
<PillSelect label={t('places.formCategory')} value={categoryId} onChange={onCategory} options={options} fallback={noCategory} />
<Tooltip label={t('places.newCategory')}>
<button ref={plusRef} type="button" onClick={() => newCategory.setOpen(true)} aria-label={t('places.newCategory')} className={ROUND_PILL_BUTTON}>
<Plus size={13} strokeWidth={2.4} />
</button>
</Tooltip>
</>
)
}
return (
<>
{lead}
{pickedSource && (
<span className={PILL}>
<Search size={12} strokeWidth={2.2} className="text-content-faint" aria-hidden="true" />
{pickedSource}
</span>
)}
{navPlace && <OpenInMapsPill place={navPlace} t={t} />}
{busy && (
<span className={PILL} role="status" aria-label={t('places.loadingDetails')}>
<Loader2 size={13} className="animate-spin text-content-faint" aria-hidden="true" />
<span className="font-medium text-content-muted">{t('places.loadingDetails')}</span>
</span>
)}
</>
)
}
type NavigablePlace = Pick<Place, 'name' | 'address' | 'lat' | 'lng' | 'google_place_id' | 'google_ftid'>
/**
* A look at the picked place in a real map before it is saved (#2178): its reviews, its
* photos, whether it is the right branch. The same apps the inspector offers, one tap
* straight away when only one applies.
*/
function OpenInMapsPill({ place, t }: { place: NavigablePlace; t: Translate }) {
const [open, setOpen] = useState(false)
const anchorRef = useRef<HTMLSpanElement>(null)
const targets = getNavigationTargets(place)
if (targets.length === 0) return null
return (
<span ref={anchorRef} className="inline-flex">
<Tooltip label={t('places.openInMaps')}>
<button type="button" aria-label={t('places.openInMaps')} aria-haspopup={targets.length > 1 ? 'menu' : undefined}
aria-expanded={targets.length > 1 ? open : undefined}
onClick={() => { if (targets.length === 1) openNavigationTarget(targets[0]); else setOpen(o => !o) }}
className={ROUND_PILL_BUTTON}>
<Navigation size={13} strokeWidth={2.2} />
</button>
</Tooltip>
{open && <NavigationMenu targets={targets} anchor={anchorRef.current} onClose={() => setOpen(false)} />}
</span>
)
}
/** The new category's name, typed where the category pill was, with its OK and Cancel beside it. */
function NewCategoryField({ inputId, name, setName, create, setOpen, t }: NewCategoryRow & { t: Translate }) {
return (
// One parent for the field and both of its buttons.
<span className="inline-flex flex-wrap items-center gap-1.5">
<input
id={inputId}
type="text"
autoFocus
value={name}
onChange={e => setName(e.target.value)}
onKeyDown={e => {
// Enter confirms the name, like OK; it never reaches the place's own save.
if (e.key === 'Enter') { e.preventDefault(); void create() }
// Escape closes the field, like Cancel, and only the field: marked
// handled, the dialog around it leaves it alone and keeps what is typed.
if (e.key === 'Escape') { e.preventDefault(); setOpen(false) }
}}
aria-label={t('places.newCategory')}
placeholder={t('places.categoryNamePlaceholder')}
className="w-48 min-w-0 rounded-full bg-surface-card px-3 py-1 text-content shadow-sm outline-none ring-1 ring-edge-faint placeholder:text-content-faint focus:ring-2 focus:ring-[color:var(--text-primary)]"
/>
<button type="button" onClick={() => void create()} className="rounded-full bg-accent px-3 py-1 font-semibold text-accent-text hover:opacity-90">
{t('common.ok')}
</button>
<button type="button" onClick={() => setOpen(false)} className={`${PILL} hover:opacity-80`}>
{t('common.cancel')}
</button>
</span>
)
}
/** A Markdown field: its label, the formatting bar on the same line, the text under both. */
function MarkdownField({ id, label, value, onChange, placeholder, maxLength }: {
id: string
@@ -0,0 +1,39 @@
// FE-PLANNER-REFRESHPILL-001 to FE-PLANNER-REFRESHPILL-003
import userEvent from '@testing-library/user-event';
import { describe, expect, it, vi } from 'vitest';
import { render, screen, within } from '../../../tests/helpers/render';
import { PlaceRefreshPill } from './PlaceRefreshPill';
import type { RefreshCandidate } from './placeRefresh';
const t = (key: string) => key;
const CANDIDATES: RefreshCandidate[] = [
{ field: 'phone', current: '', next: '+49 381 87398063', preselected: true },
{ field: 'website', current: 'https://old.example', next: 'https://www.thao-vinh.de/', preselected: false },
];
describe('PlaceRefreshPill', () => {
it('FE-PLANNER-REFRESHPILL-001: nothing shows while the details match the place', () => {
const { container } = render(<PlaceRefreshPill candidates={[]} origin="osm" onApply={vi.fn()} t={t} />);
expect(container).toBeEmptyDOMElement();
});
it('FE-PLANNER-REFRESHPILL-002: the pill counts the differences; empty fields are ticked, filled ones say they replace', async () => {
render(<PlaceRefreshPill candidates={CANDIDATES} origin="osm" onApply={vi.fn()} t={t} />);
const pill = screen.getByRole('button', { name: /places\.refresh\.pill/ });
expect(within(pill).getByText('2')).toBeInTheDocument();
await userEvent.click(pill);
expect(screen.getByRole('button', { name: 'places.formPhone' })).toHaveAttribute('aria-pressed', 'true');
expect(screen.getByRole('button', { name: 'places.formWebsite' })).toHaveAttribute('aria-pressed', 'false');
expect(screen.getByText('places.refresh.replaces')).toBeInTheDocument();
});
it('FE-PLANNER-REFRESHPILL-003: confirming takes over only the ticked fields, with the provider as origin', async () => {
const onApply = vi.fn();
render(<PlaceRefreshPill candidates={CANDIDATES} origin="osm" onApply={onApply} t={t} />);
await userEvent.click(screen.getByRole('button', { name: /places\.refresh\.pill/ }));
await userEvent.click(screen.getByRole('button', { name: 'places.refresh.apply' }));
expect(onApply).toHaveBeenCalledTimes(1);
expect(onApply).toHaveBeenCalledWith('phone', '+49 381 87398063', 'osm');
});
});
@@ -0,0 +1,133 @@
import type { PlaceClientOrigin } from '@trek/shared';
import { RefreshCw } from 'lucide-react';
import { useState } from 'react';
import ToggleSwitch from '../Settings/ToggleSwitch';
import ConfirmDialog from '../shared/ConfirmDialog';
import { fs, PILL } from '../shared/DialogShell';
import { hoursLines } from './placeHours';
import type { RefreshCandidate, RefreshField } from './placeRefresh';
type Translate = (key: string, params?: Record<string, string | number>) => string;
const LABEL: Record<RefreshField, string> = {
description: 'places.formDescription',
website: 'places.formWebsite',
phone: 'places.formPhone',
email: 'places.formEmail',
opening_hours: 'inspector.openingHours',
};
/** A value as the list shows it: hours as one line per day, the rest as stored. */
function shown(field: RefreshField, value: string, locale: string | undefined, t: Translate): string[] {
if (!value) return [t('places.refresh.empty')];
if (field === 'opening_hours') return hoursLines(value, locale, t('places.hoursClosed')) ?? [value];
return [value];
}
/**
* A saved place's details that TREK knows better now: a pill in the head band
* when a fresh lookup differs from what the place holds, and a list to pick
* from. An empty field is ticked, a filled one is the person's to decide, and
* nothing is taken over before they confirm. The form saves as usual after.
*/
export function PlaceRefreshPill({
candidates,
origin,
onApply,
locale,
t,
}: {
candidates: RefreshCandidate[];
origin: PlaceClientOrigin;
/** Sets one field in the form, with the provider as its origin. */
onApply: (field: RefreshField, value: string, origin: PlaceClientOrigin) => void;
locale?: string;
t: Translate;
}) {
const [open, setOpen] = useState(false);
const [picked, setPicked] = useState<ReadonlySet<RefreshField>>(new Set());
if (candidates.length === 0) return null;
const show = () => {
setPicked(new Set(candidates.filter((c) => c.preselected).map((c) => c.field)));
setOpen(true);
};
const toggle = (field: RefreshField) =>
setPicked((now) => {
const next = new Set(now);
if (next.has(field)) next.delete(field);
else next.add(field);
return next;
});
const apply = () => {
for (const c of candidates) if (picked.has(c.field)) onApply(c.field, c.next, origin);
setOpen(false);
};
return (
<>
<button type="button" onClick={show} className={`${PILL} hover:opacity-80`}>
<RefreshCw size={12} strokeWidth={2.2} className="text-content-faint" aria-hidden="true" />
{t('places.refresh.pill')}
<span
className="inline-flex h-[18px] min-w-[18px] items-center justify-center rounded-full bg-accent px-1 font-semibold tabular-nums text-accent-text"
style={fs(10.5)}
>
{candidates.length}
</span>
</button>
<ConfirmDialog
isOpen={open}
onClose={() => setOpen(false)}
onConfirm={apply}
title={t('places.refresh.title')}
message={t('places.refresh.intro')}
confirmLabel={t('places.refresh.apply')}
danger={false}
>
<ul className="m-0 flex list-none flex-col gap-2 p-0">
{candidates.map((c) => (
<li
key={c.field}
className="flex items-start gap-3 rounded-[12px] border border-edge-faint bg-surface-secondary px-3 py-2.5"
>
<div className="min-w-0 flex-1">
<p className="m-0 font-semibold text-content" style={fs(12.5, 'body')}>
{t(LABEL[c.field])}
</p>
<div className="mt-1 grid grid-cols-2 gap-2" style={fs(11.5)}>
<div className="min-w-0 text-content-faint">
<p className="m-0 font-semibold uppercase tracking-[.06em]" style={fs(9.5)}>
{t('places.refresh.now')}
</p>
{shown(c.field, c.current, locale, t).map((line) => (
<p key={line} className={c.field === 'description' ? 'm-0 line-clamp-3' : 'm-0 truncate'}>
{line}
</p>
))}
</div>
<div className="min-w-0 text-content">
<p className="m-0 font-semibold uppercase tracking-[.06em] text-content-faint" style={fs(9.5)}>
{t('places.refresh.new')}
</p>
{shown(c.field, c.next, locale, t).map((line) => (
<p key={line} className={c.field === 'description' ? 'm-0 line-clamp-3' : 'm-0 truncate'}>
{line}
</p>
))}
</div>
</div>
{!c.preselected && (
<p className="m-0 mt-1 text-warning" style={fs(11)}>
{t('places.refresh.replaces')}
</p>
)}
</div>
<ToggleSwitch on={picked.has(c.field)} label={t(LABEL[c.field])} onToggle={() => toggle(c.field)} />
</li>
))}
</ul>
</ConfirmDialog>
</>
);
}
@@ -91,6 +91,27 @@ beforeEach(() => {
})
describe('TransitSearchPanel', () => {
it.each(['google', 'transitous'] as const)('updates attribution when a later search returns %s fallback routes', async (provider) => {
const user = userEvent.setup()
const onAdd = vi.fn().mockResolvedValue({})
const previous = provider === 'google' ? 'transitous' : 'google'
transitApiMock.plan
.mockResolvedValueOnce({ itineraries: [ITINERARY], provider: previous })
.mockResolvedValueOnce({ itineraries: [ITINERARY], provider })
render(<TransitSearchPanel {...makeProps({ onAdd })} />)
await pickFromAndTo(user)
await user.click(screen.getByRole('button', { name: /^Search$/ }))
await screen.findByText(previous === 'google' ? 'Google Maps' : 'Transitous')
await user.click(screen.getByRole('button', { name: /^Search$/ }))
expect(await screen.findByText(provider === 'google' ? 'Google Maps' : 'Transitous')).toBeInTheDocument()
expect(screen.queryByText(previous === 'google' ? 'Google Maps' : 'Transitous')).not.toBeInTheDocument()
await user.click(await screen.findByText(/08:30 – 09:00/))
await user.click(await screen.findByRole('button', { name: 'Add to day' }))
await waitFor(() => expect(onAdd).toHaveBeenCalledWith(expect.objectContaining({
metadata: expect.objectContaining({ transit: expect.objectContaining({ provider }) }),
})))
})
it('FE-PLANNER-TRANSIT-001: renders from/to pickers, modes and preferences', () => {
render(<TransitSearchPanel {...makeProps()} />)
expect(screen.getAllByPlaceholderText('Search stop or station…')).toHaveLength(2)
@@ -1,4 +1,4 @@
// FE-PLANNER-ENRICHCACHE-001 to FE-PLANNER-ENRICHCACHE-005: the session cache the editor's
// FE-PLANNER-ENRICHCACHE-001 to FE-PLANNER-ENRICHCACHE-007: the session cache the editor's
// details column and the view's photo gallery share, so a place is asked about once.
import type { MapsPlaceEnrichmentResult } from '@trek/shared';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
@@ -25,15 +25,22 @@ afterEach(() => {
describe('placeEnrichment', () => {
it('FE-PLANNER-ENRICHCACHE-001: the key names the version, the place (or its coordinates) and the language', () => {
expect(cacheKeyFor(SELECTION, 'de')).toBe('enrich_v4_way:1_de');
expect(cacheKeyFor({ lat: 1.5, lng: 2, name: 'Pin' }, 'en')).toBe('enrich_v4_coords:1.5:2_en');
expect(cacheKeyFor(SELECTION, 'de')).toBe('enrich_v5_way:1_de');
expect(cacheKeyFor({ lat: 1.5, lng: 2, name: 'Pin' }, 'en')).toBe('enrich_v5_coords:1.5:2_en');
});
it('FE-PLANNER-ENRICHCACHE-006: a place of the index served with another community version is another answer', () => {
const gers = { placeId: 'gers:abc', lat: 1, lng: 2, name: 'Cafe', details: { community_version: 3 } };
expect(cacheKeyFor(gers, 'de')).toBe('enrich_v5_gers:abc_c3_de');
expect(cacheKeyFor({ ...gers, details: { community_version: 4 } }, 'de')).not.toBe(cacheKeyFor(gers, 'de'));
expect(cacheKeyFor({ ...gers, details: {} }, 'de')).toBe('enrich_v5_gers:abc_de');
});
it('FE-PLANNER-ENRICHCACHE-002: nothing is cached before it is stored, then both caches hold it', () => {
expect(readCachedEnrichment(SELECTION, 'de')).toBeUndefined();
storeEnrichment(SELECTION, 'de', RESULT);
expect(readCachedEnrichment(SELECTION, 'de')).toBe(RESULT);
expect(JSON.parse(sessionStorage.getItem('enrich_v4_way:1_de') ?? '')).toEqual(RESULT);
expect(JSON.parse(sessionStorage.getItem('enrich_v5_way:1_de') ?? '').value).toEqual(RESULT);
// Another language is another answer.
expect(readCachedEnrichment(SELECTION, 'en')).toBeUndefined();
});
@@ -59,4 +66,16 @@ describe('placeEnrichment', () => {
expect(() => storeEnrichment(SELECTION, 'de', RESULT)).not.toThrow();
expect(readCachedEnrichment(SELECTION, 'de')).toBe(RESULT);
});
it('FE-PLANNER-ENRICHCACHE-007: an answer is reused for ten minutes, then asked again', () => {
const now = vi.spyOn(Date, 'now').mockReturnValue(1_000_000);
storeEnrichment(SELECTION, 'de', RESULT);
now.mockReturnValue(1_000_000 + 9 * 60 * 1000);
expect(readCachedEnrichment(SELECTION, 'de')).toBe(RESULT);
now.mockReturnValue(1_000_000 + 10 * 60 * 1000);
expect(readCachedEnrichment(SELECTION, 'de')).toBeUndefined();
// Gone from the session too: a reload does not bring it back.
__clearEnrichmentCacheForTests();
expect(readCachedEnrichment(SELECTION, 'de')).toBeUndefined();
});
});
@@ -19,23 +19,37 @@ export interface PlaceDetailsSelection {
* pay for the provider fan-out twice, and the gallery must reuse the pictures
* the editor already fetched for the same place.
*/
const enrichmentCache = new Map<string, MapsPlaceEnrichmentResult>();
const enrichmentCache = new Map<string, Stored>();
/** A kept answer and when it was fetched. */
interface Stored {
at: number;
value: MapsPlaceEnrichmentResult;
}
/**
* How long a kept answer is reused. A saved place reopened for editing carries
* no community version, so its key never changes: without an end, a picture
* another installation contributed would stay out of this tab until it closed.
* The server keeps an empty answer for the same ten minutes.
*/
const KEEP_MS = 10 * 60 * 1000;
/** Test seam: the module-level cache otherwise leaks between cases. */
export function __clearEnrichmentCacheForTests(): void {
enrichmentCache.clear();
}
function readSession(key: string): MapsPlaceEnrichmentResult | undefined {
function readSession(key: string): Stored | undefined {
try {
const raw = sessionStorage.getItem(key);
return raw ? (JSON.parse(raw) as MapsPlaceEnrichmentResult) : undefined;
return raw ? (JSON.parse(raw) as Stored) : undefined;
} catch {
return undefined;
}
}
function writeSession(key: string, value: MapsPlaceEnrichmentResult): void {
function writeSession(key: string, value: Stored): void {
try {
sessionStorage.setItem(key, JSON.stringify(value));
} catch {
@@ -48,11 +62,15 @@ function writeSession(key: string, value: MapsPlaceEnrichmentResult): void {
* without it the tab that was open while the fix shipped keeps replaying the
* answer the fix was about — and reports it as still broken.
*/
const ENRICH_CACHE_V = 4;
const ENRICH_CACHE_V = 5;
export function cacheKeyFor(selection: PlaceDetailsSelection, language: string): string {
const id = selection.placeId || `coords:${selection.lat}:${selection.lng}`;
return `enrich_v${ENRICH_CACHE_V}_${id}_${language}`;
// A place of the TREK index names the version of the community values it is
// served with; a new version is a new answer, not the one this tab kept.
const version = selection.details?.community_version;
const community = typeof version === 'number' ? `_c${version}` : '';
return `enrich_v${ENRICH_CACHE_V}_${id}${community}_${language}`;
}
/** The answer if it was already fetched this session, else undefined. */
@@ -62,8 +80,12 @@ export function readCachedEnrichment(
): MapsPlaceEnrichmentResult | undefined {
const key = cacheKeyFor(selection, language);
const cached = enrichmentCache.get(key) ?? readSession(key);
if (cached) enrichmentCache.set(key, cached);
return cached;
if (!cached || typeof cached.at !== 'number' || Date.now() - cached.at >= KEEP_MS) {
enrichmentCache.delete(key);
return undefined;
}
enrichmentCache.set(key, cached);
return cached.value;
}
export function storeEnrichment(
@@ -72,6 +94,7 @@ export function storeEnrichment(
value: MapsPlaceEnrichmentResult
): void {
const key = cacheKeyFor(selection, language);
enrichmentCache.set(key, value);
writeSession(key, value);
const stored = { at: Date.now(), value };
enrichmentCache.set(key, stored);
writeSession(key, stored);
}
@@ -0,0 +1,52 @@
// FE-PLANNER-ORIGINS-001 to FE-PLANNER-ORIGINS-005: where the place form's shareable fields
// got their values, as the save reports it in fieldOrigins.
import { describe, expect, it } from 'vitest';
import { DEFAULT_FORM, mergeResult, type ResultField } from './PlaceFormModal.helpers';
import { originsAfterPick, resultOrigin, withOrigin } from './placeFieldOrigins';
describe('placeFieldOrigins', () => {
it('FE-PLANNER-ORIGINS-001: names the provider a result came from by the ids it carries', () => {
expect(resultOrigin({ osm_id: 'gers:abc' })).toBe('trek');
expect(resultOrigin({ source: 'trek-places' })).toBe('trek');
expect(resultOrigin({ amap_poi_id: 'amap:B1' })).toBe('amap');
expect(resultOrigin({ google_place_id: 'ChIJ1', osm_id: 'node:1' })).toBe('google');
expect(resultOrigin({ osm_id: 'way:2' })).toBe('osm');
expect(resultOrigin({ name: 'Pin' })).toBe('enrichment');
});
it('FE-PLANNER-ORIGINS-002: sets and forgets one shareable field, the picture under its own name', () => {
expect(withOrigin(undefined, 'website', 'user')).toEqual({ website: 'user' });
expect(withOrigin({ website: 'user' }, 'image_url', 'enrichment')).toEqual({
website: 'user',
image: 'enrichment',
});
expect(withOrigin({ website: 'user', image: 'enrichment' }, 'image_url', null)).toEqual({ website: 'user' });
});
it('FE-PLANNER-ORIGINS-003: a field that is not shared leaves the origins as they were', () => {
const origins = { phone: 'user' as const };
expect(withOrigin(origins, 'name', 'user')).toBe(origins);
expect(withOrigin(undefined, 'notes', 'user')).toBeUndefined();
});
it('FE-PLANNER-ORIGINS-004: a pick owns what it wrote and drops what it cleared', () => {
expect(originsAfterPick({ website: 'user', phone: 'google' }, ['name', 'website'], ['phone'], 'osm')).toEqual({
website: 'osm',
});
});
it('FE-PLANNER-ORIGINS-005: mergeResult records the pick, and a typed field it leaves alone keeps its origin', () => {
const autoFilled = new Set<ResultField>(['phone']);
const prev = {
...DEFAULT_FORM,
phone: '+49 1',
email: 'me@x.de',
fieldOrigins: { phone: 'trek' as const, email: 'user' as const },
};
const next = mergeResult(prev, { name: 'Cafe', website: 'https://cafe.example', osm_id: 'node:4' }, autoFilled);
expect(next.website).toBe('https://cafe.example');
expect(next.phone).toBe('');
expect(next.fieldOrigins).toEqual({ email: 'user', website: 'osm' });
});
});
@@ -0,0 +1,68 @@
import type { PlaceClientOrigin, PlaceContribField, PlaceFieldOrigins } from '@trek/shared';
/**
* Where the place form's shareable fields got their values, for the
* `fieldOrigins` a create or update carries: `user` for what was typed, the
* provider for what a search pick, a map POI or the details column filled in.
* The server keeps the record of it (and decides for MCP, plugins and imports),
* so this only has to say what the form saw; nothing here is shown.
*/
const SHAREABLE: ReadonlySet<string> = new Set<PlaceContribField>([
'website',
'phone',
'email',
'opening_hours',
'description',
'image',
]);
/** The form field a shareable detail lives in (`image_url` is the picture). */
function contribFieldOf(formField: string): PlaceContribField | null {
const field = formField === 'image_url' ? 'image' : formField;
return SHAREABLE.has(field) ? (field as PlaceContribField) : null;
}
/**
* Which provider a picked search result or a prefilled POI came from, read off
* the ids it carries: the TREK index, Amap, Google, OpenStreetMap.
*/
export function resultOrigin(result: Record<string, unknown>): PlaceClientOrigin {
const osmId = typeof result.osm_id === 'string' ? result.osm_id : '';
if (result.source === 'trek-places' || osmId.startsWith('gers:')) return 'trek';
if (typeof result.amap_poi_id === 'string' && result.amap_poi_id) return 'amap';
if (typeof result.google_place_id === 'string' && result.google_place_id) return 'google';
if (osmId) return 'osm';
return 'enrichment';
}
/**
* The origins with one form field set (or, for `null`, forgotten: a value that
* belonged to the last pick and was cleared). A field that is not shareable
* leaves them as they are.
*/
export function withOrigin(
origins: PlaceFieldOrigins | undefined,
formField: string,
origin: PlaceClientOrigin | null
): PlaceFieldOrigins | undefined {
const field = contribFieldOf(formField);
if (!field) return origins;
const next: PlaceFieldOrigins = { ...origins };
if (origin) next[field] = origin;
else delete next[field];
return next;
}
/** The origins after a search pick wrote or cleared these form fields. */
export function originsAfterPick(
origins: PlaceFieldOrigins | undefined,
written: readonly string[],
cleared: readonly string[],
origin: PlaceClientOrigin
): PlaceFieldOrigins | undefined {
let next = origins;
for (const field of written) next = withOrigin(next, field, origin);
for (const field of cleared) next = withOrigin(next, field, null);
return next;
}
@@ -23,6 +23,7 @@ describe('placePhotoCredit', () => {
expect(sourceLabelFor('google')).toBe('Google');
expect(sourceLabelFor('wikipedia')).toBe('Wikipedia');
expect(sourceLabelFor('wikimedia')).toBe('Wikimedia Commons');
expect(sourceLabelFor('community')).toBe('TREK Community');
});
it('FE-PLANNER-PHOTOCREDIT-002: the author is credited, and the provider when there is none', () => {
@@ -12,6 +12,7 @@ export function creditOf(photo: PlacePhotoCandidate): string {
export function sourceLabelFor(source: PlacePhotoCandidate['source']): string {
if (source === 'google') return 'Google';
if (source === 'wikipedia') return 'Wikipedia';
if (source === 'community') return 'TREK Community';
return 'Wikimedia Commons';
}
@@ -0,0 +1,71 @@
// FE-PLANNER-REFRESH-001 to FE-PLANNER-REFRESH-007
import { describe, expect, it } from 'vitest';
import { DEFAULT_FORM, type PlaceFormData } from './PlaceFormModal.helpers';
import { refreshCandidates } from './placeRefresh';
const form = (over: Partial<PlaceFormData> = {}): PlaceFormData => ({ ...DEFAULT_FORM, ...over });
// Mo-Fr 10:30-20:00, as the details lookup hands periods out (day 0 is Sunday).
const PERIODS = [1, 2, 3, 4, 5].map((day) => ({
open: { day, hour: 10, minute: 30 },
close: { day, hour: 20, minute: 0 },
}));
describe('refreshCandidates', () => {
it('FE-PLANNER-REFRESH-001: an empty field the lookup fills is offered and ticked', () => {
const got = refreshCandidates(form(), { phone: '+49 381 87398063', website: 'www.thao-vinh.de' });
expect(got).toEqual([
expect.objectContaining({ field: 'website', current: '', preselected: true }),
expect.objectContaining({ field: 'phone', current: '', next: '+49 381 87398063', preselected: true }),
]);
expect(got[0]?.next).toMatch(/^https:\/\/www\.thao-vinh\.de\/?$/);
});
it('FE-PLANNER-REFRESH-002: a value the person has is offered only when it differs, and not ticked', () => {
const got = refreshCandidates(form({ phone: '0381 1111' }), { phone: '+49 381 2222' });
expect(got).toEqual([{ field: 'phone', current: '0381 1111', next: '+49 381 2222', preselected: false }]);
});
it('FE-PLANNER-REFRESH-003: the same value in another spelling is no difference', () => {
expect(
refreshCandidates(
form({ phone: '+49 381 873 98 063', website: 'https://www.helgas-kitchen.de/', email: 'Info@Luna.de' }),
{
phone: '+4938187398063',
website: 'https://www.helgas-kitchen.de',
email: 'info@luna.de',
}
)
).toEqual([]);
});
it('FE-PLANNER-REFRESH-004: hours come as the stored week, and the same week is no difference', () => {
const [hours] = refreshCandidates(form(), { opening_periods: PERIODS });
expect(hours?.field).toBe('opening_hours');
expect(JSON.parse(hours?.next ?? '[]')).toHaveLength(7);
expect(refreshCandidates(form({ opening_hours: hours?.next }), { opening_periods: PERIODS })).toEqual([]);
});
it('FE-PLANNER-REFRESH-006: a description comes from the index object or the OSM summary', () => {
const text = 'An Asian restaurant in Evershagen.';
expect(refreshCandidates(form(), { description: { text, source: 'community' } })).toEqual([
{ field: 'description', current: '', next: text, preselected: true },
]);
expect(refreshCandidates(form(), { summary: text, summary_source: 'community' })).toEqual([
{ field: 'description', current: '', next: text, preselected: true },
]);
});
it('FE-PLANNER-REFRESH-007: the same description under the editor markup is no difference', () => {
const text = 'An Asian restaurant in Evershagen.';
expect(refreshCandidates(form({ description: `<p>${text}</p>` }), { summary: text })).toEqual([]);
expect(refreshCandidates(form({ description: 'Our favourite.' }), { summary: text })).toEqual([
{ field: 'description', current: 'Our favourite.', next: text, preselected: false },
]);
});
it('FE-PLANNER-REFRESH-005: what the lookup does not know is never offered, so nothing is emptied', () => {
expect(refreshCandidates(form({ phone: '0381 1111', website: 'https://a.example' }), {})).toEqual([]);
expect(refreshCandidates(form(), null)).toEqual([]);
});
});
@@ -0,0 +1,77 @@
import { normalizePlaceWebsite, parsePlaceHours } from '@trek/shared';
import type { PlaceFormData } from './PlaceFormModal.helpers';
import { cleanWeek, weekFromPeriods, writeWeek } from './placeHours';
/** The details a saved place can take over from a fresh lookup. */
const REFRESH_FIELDS = ['description', 'website', 'phone', 'email', 'opening_hours'] as const;
export type RefreshField = (typeof REFRESH_FIELDS)[number];
/** One field where the lookup says something else than the place holds now. */
export interface RefreshCandidate {
field: RefreshField;
/** What the form holds, as stored; empty when it holds nothing. */
current: string;
/** What the lookup has, in the form's own format (hours as the stored week). */
next: string;
/** An empty field takes the new value without asking; a filled one is the person's call. */
preselected: boolean;
}
type Details = Record<string, unknown>;
const text = (value: unknown): string => (typeof value === 'string' ? value.trim() : '');
/** A description as plain words: the editor stores markup, the lookup sends text. */
const plain = (value: string): string =>
value
.replace(/<[^>]*>/g, ' ')
.replace(/[*_`~#>]/g, '')
.replace(/\s+/g, ' ')
.trim();
/** The lookup's value of a field, written the way the form stores it. */
function freshValue(field: RefreshField, details: Details): string {
if (field === 'website') return normalizePlaceWebsite(text(details.website)) ?? '';
// An index place carries its description as an object, an OSM place as the summary.
if (field === 'description') {
const own = details.description as { text?: unknown } | null | undefined;
return text(own?.text) || text(details.summary);
}
if (field === 'opening_hours') {
const week = weekFromPeriods(details.opening_periods as Parameters<typeof weekFromPeriods>[0]);
return week ? writeWeek(cleanWeek(week)) : '';
}
return text(details[field]);
}
/** Two values that say the same in a different spelling count as one. */
function sameValue(field: RefreshField, a: string, b: string): boolean {
if (field === 'phone') return a.replace(/[^\d+]/g, '') === b.replace(/[^\d+]/g, '');
if (field === 'website')
return (normalizePlaceWebsite(a) ?? a).replace(/\/$/, '').toLowerCase() === b.replace(/\/$/, '').toLowerCase();
if (field === 'email') return a.toLowerCase() === b.toLowerCase();
if (field === 'description') return plain(a) === plain(b);
if (field === 'opening_hours') {
const week = parsePlaceHours(a);
return (week ? writeWeek(cleanWeek(week)) : a) === b;
}
return a === b;
}
/**
* The fields where a fresh lookup of a saved place differs from what the form
* holds. A field the lookup knows nothing about is never offered: refreshing
* must not empty what the place already has.
*/
export function refreshCandidates(form: PlaceFormData, details: Details | null | undefined): RefreshCandidate[] {
if (!details) return [];
const out: RefreshCandidate[] = [];
for (const field of REFRESH_FIELDS) {
const next = freshValue(field, details);
if (!next) continue;
const current = (form[field] ?? '').trim();
if (current && sameValue(field, current, next)) continue;
out.push({ field, current, next, preselected: current === '' });
}
return out;
}
@@ -326,3 +326,38 @@ describe('useNewCategory', () => {
expect(result.current.name).toBe('Bar');
});
});
// FE-PLANNER-PLFORM-030 to FE-PLANNER-PLFORM-033: which fields the user typed and which a
// pick, a map POI or the details column filled, for the save's fieldOrigins.
describe('usePlaceForm field origins', () => {
it('FE-PLANNER-PLFORM-030: a typed shareable field is the user own; other fields report nothing', () => {
const { result } = setup();
act(() => result.current.handleChange('website', 'https://mine.example'));
act(() => result.current.handleChange('name', 'Mine'));
expect(result.current.form.fieldOrigins).toEqual({ website: 'user' });
});
it('FE-PLANNER-PLFORM-031: a map POI owns what it prefilled, until the user types over it', () => {
const { result } = setup();
const prefill = { lat: 1, lng: 2, name: 'Cafe', website: 'https://cafe.example', phone: '+49 1', osm_id: 'node:9' };
act(() => result.current.openForm(DEFAULT_FORM, null, prefill));
expect(result.current.form.fieldOrigins).toEqual({ website: 'osm', phone: 'osm' });
act(() => result.current.handleChange('phone', '+49 2'));
expect(result.current.form.fieldOrigins).toEqual({ website: 'osm', phone: 'user' });
});
it('FE-PLANNER-PLFORM-032: an adopted description and a picked photo are the details column own', () => {
const { result } = setup();
act(() => result.current.adoptDescription('A museum by the river.'));
act(() => result.current.pickImage('/api/maps/place-photo/x/bytes'));
expect(result.current.form.fieldOrigins).toEqual({ description: 'enrichment', image: 'enrichment' });
act(() => result.current.removeImage());
expect(result.current.form.fieldOrigins).toEqual({ description: 'enrichment' });
});
it('FE-PLANNER-PLFORM-033: hours taken over from the lookup say so', () => {
const { result } = setup();
act(() => result.current.handleChange('opening_hours', '[]', 'enrichment'));
expect(result.current.form.fieldOrigins).toEqual({ opening_hours: 'enrichment' });
});
});
+30 -9
View File
@@ -1,3 +1,4 @@
import type { PlaceClientOrigin } from '@trek/shared';
import type React from 'react';
import { useEffect, useRef, useState } from 'react';
@@ -15,9 +16,17 @@ import {
type PlacePrefill,
type ResultField,
} from './PlaceFormModal.helpers';
import { originsAfterPick, resultOrigin, withOrigin } from './placeFieldOrigins';
import type { PendingPlaceImage } from './placeImageChoice';
type Translate = ReturnType<typeof useTranslation>['t'];
/** The form with another picture, and with it the origin of that picture; null where the save route decides it. */
const withImage = (
prev: PlaceFormData,
image: string | null | undefined,
origin: PlaceClientOrigin | null = null
): PlaceFormData => ({ ...prev, image_url: image, fieldOrigins: withOrigin(prev.fieldOrigins, 'image_url', origin) });
type Toast = ReturnType<typeof useToast>;
export interface PlaceFormOptions {
@@ -70,18 +79,24 @@ export function usePlaceForm({ t, toast, canUploadFiles }: PlaceFormOptions) {
place: Parameters<typeof openingDetailsSelection>[0],
prefill: PlacePrefill | null | undefined
) => {
setForm(next);
autoFilledRef.current = openingAutoFilled(place, prefill);
const autoFilled = openingAutoFilled(place, prefill);
// A map POI's website and phone are the provider's, like a search pick's.
const origins = prefill
? originsAfterPick(next.fieldOrigins, [...autoFilled], [], resultOrigin(prefill))
: undefined;
setForm(origins ? { ...next, fieldOrigins: origins } : next);
autoFilledRef.current = autoFilled;
setDetailsSelection(openingDetailsSelection(place, prefill));
setPendingFiles([]);
setPendingImage(null);
setDuplicateWarning(null);
};
const handleChange = (field: string, value: string) => {
/** A field set in the form: typed by hand unless the caller says it took a looked-up value over. */
const handleChange = (field: string, value: string, origin: PlaceClientOrigin = 'user') => {
// Typed by hand, so the next pick must not clear it.
autoFilledRef.current.delete(field as ResultField);
setForm((prev) => ({ ...prev, [field]: value }));
setForm((prev) => ({ ...prev, [field]: value, fieldOrigins: withOrigin(prev.fieldOrigins, field, origin) }));
};
const addFiles = (files: File[]) => setPendingFiles((prev) => [...prev, ...files]);
@@ -110,29 +125,35 @@ export function usePlaceForm({ t, toast, canUploadFiles }: PlaceFormOptions) {
/** A source's photo picked in the details column, or the place's own picture again. */
const pickImage = (url: string | null) => {
setPendingImage(null);
setForm((prev) => ({ ...prev, image_url: url ?? undefined }));
setForm((prev) => withImage(prev, url ?? undefined, url ? 'enrichment' : null));
};
/** A picture from the device, shown at once and uploaded when the form is saved. */
const stageUpload = (file: File) => {
setPendingImage({ kind: 'upload', file, preview: URL.createObjectURL(file) });
setForm((prev) => ({ ...prev, image_url: undefined }));
// The upload route records the picture as the user's itself.
setForm((prev) => withImage(prev, undefined));
};
/** An image already attached to the place, made its picture when the form is saved. */
const stageAttached = (file: TripFile) => {
setPendingImage({ kind: 'attached', file });
setForm((prev) => ({ ...prev, image_url: undefined }));
setForm((prev) => withImage(prev, undefined));
};
/** No picture at all: the save drops the place's own one. */
const removeImage = () => {
setPendingImage(null);
setForm((prev) => ({ ...prev, image_url: null }));
setForm((prev) => withImage(prev, null));
};
/** The details column's description, taken over into the form. */
const adoptDescription = (text: string) => setForm((prev) => ({ ...prev, description: text }));
const adoptDescription = (text: string) =>
setForm((prev) => ({
...prev,
description: text,
fieldOrigins: withOrigin(prev.fieldOrigins, 'description', 'enrichment'),
}));
/**
* #1152: the first save of a new place warns when the trip seems to have it already;
@@ -0,0 +1,38 @@
// FE-PLANNER-REFRESHHOOK-001 to FE-PLANNER-REFRESHHOOK-002
import { renderHook, waitFor } from '@testing-library/react';
import { afterEach, describe, expect, it, vi } from 'vitest';
import { placeDetailsRepo } from '../../repo/placeDetailsRepo';
import type { Place } from '../../types';
import { DEFAULT_FORM, type PlaceFormData } from './PlaceFormModal.helpers';
import { usePlaceRefresh } from './usePlaceRefresh';
const SAVED = { id: 1, name: 'Café Luna', google_place_id: 'g-luna', osm_id: null } as unknown as Place;
const DETAILS: Record<string, Record<string, unknown>> = {
'g-luna': { website: 'https://cafe-luna.de' },
'g-sole': { website: 'https://sole.example', phone: '+39 06 1234' },
};
afterEach(() => {
vi.restoreAllMocks();
});
describe('usePlaceRefresh', () => {
it('FE-PLANNER-REFRESHHOOK-001: a saved place is compared with its own fresh details', async () => {
const details = vi.spyOn(placeDetailsRepo, 'details').mockImplementation(async (id) => DETAILS[id] ?? null);
const form: PlaceFormData = { ...DEFAULT_FORM };
const { result } = renderHook(() => usePlaceRefresh({ place: SAVED, form, language: 'de' }));
await waitFor(() => expect(result.current.candidates).toHaveLength(1));
expect(details).toHaveBeenCalledWith('g-luna', 'de');
expect(result.current.candidates[0]).toMatchObject({ field: 'website', current: '' });
});
it('FE-PLANNER-REFRESHHOOK-002: after another place is picked in the search box, its details are the ones compared', async () => {
const details = vi.spyOn(placeDetailsRepo, 'details').mockImplementation(async (id) => DETAILS[id] ?? null);
const form: PlaceFormData = { ...DEFAULT_FORM, google_place_id: 'g-sole', website: 'https://sole.example' };
const { result } = renderHook(() => usePlaceRefresh({ place: SAVED, form, language: 'de' }));
await waitFor(() => expect(result.current.candidates).toHaveLength(1));
expect(details).not.toHaveBeenCalledWith('g-luna', 'de');
expect(result.current.candidates[0]).toMatchObject({ field: 'phone', next: '+39 06 1234' });
});
});
@@ -0,0 +1,55 @@
import type { PlaceClientOrigin } from '@trek/shared';
import { useEffect, useMemo, useState } from 'react';
import { placeDetailsRepo } from '../../repo/placeDetailsRepo';
import type { Place } from '../../types';
import type { PlaceFormData } from './PlaceFormModal.helpers';
import { resultOrigin } from './placeFieldOrigins';
import { refreshCandidates, type RefreshCandidate } from './placeRefresh';
/**
* The id the details lookup takes for a saved place: its Google id, else its
* OSM or index id. A place picked anew in the search box brings its own ids
* into the form, and those win, so the details compared are the picked place's.
*/
function detailIdOf(place: Place | null | undefined, form: PlaceFormData): string | null {
if (!place) return null;
return form.google_place_id || form.osm_id || place.google_place_id || place.osm_id || null;
}
/**
* Fresh details for a place being edited, and the fields where they differ
* from the form. Asked once per opened place and language; a place without a
* provider id, and a new place, have nothing to refresh from.
*/
export function usePlaceRefresh({
place,
form,
language,
}: {
place: Place | null | undefined;
form: PlaceFormData;
language: string;
}): { candidates: RefreshCandidate[]; origin: PlaceClientOrigin } {
const detailId = detailIdOf(place, form);
// Keyed by what was asked, so a stale answer for another place is never read.
const [fresh, setFresh] = useState<{ key: string; details: Record<string, unknown> } | null>(null);
const key = detailId ? `${detailId}|${language}` : null;
useEffect(() => {
if (!detailId || !key) return;
let live = true;
placeDetailsRepo.details(detailId, language).then(
(details) => {
if (live && details) setFresh({ key, details });
},
() => undefined
);
return () => {
live = false;
};
}, [detailId, key, language]);
const details = fresh && fresh.key === key ? fresh.details : null;
const candidates = useMemo(() => refreshCandidates(form, details), [form, details]);
return { candidates, origin: details ? resultOrigin(details) : 'enrichment' };
}
@@ -38,7 +38,7 @@ export function SettingsHeader({ icon: Icon, title, subtitle, actions }: {
* badge and an action on the right) and its body below. `tone` tints the band:
* neutral for ordinary groups, danger for the destructive ones.
*/
export function SettingsCard({ icon: Icon, title, hint, badge, action, tone = 'neutral', children, id, bodyClassName }: {
export function SettingsCard({ icon: Icon, title, hint, badge, action, tone = 'neutral', children, id, bodyClassName, flush = false }: {
icon?: IconLike
title: ReactNode
/** One line under the title in the band. */
@@ -50,10 +50,12 @@ export function SettingsCard({ icon: Icon, title, hint, badge, action, tone = 'n
id?: string
/** Replaces the body's padded column. */
bodyClassName?: string
/** Inside another card: no gap below, the parent spaces its children. */
flush?: boolean
}) {
const tint = tone === 'danger' ? 'color-mix(in srgb, var(--danger) 9%, transparent)' : NEUTRAL_TINT
return (
<section id={id} className="mb-5 overflow-hidden rounded-2xl border border-edge-faint bg-surface-secondary">
<section id={id} className={`${flush ? '' : 'mb-5 '}overflow-hidden rounded-2xl border border-edge-faint bg-surface-secondary`}>
<div className="flex items-center gap-3 border-b border-edge-faint px-4 py-3" style={{ background: tint }}>
{Icon && (
<span className={`grid h-8 w-8 flex-none place-items-center rounded-[10px] bg-surface-card shadow-sm ${tone === 'danger' ? 'text-danger' : 'text-content-secondary'}`}>
@@ -35,7 +35,7 @@ export function FigureBadge({
style={fs(11)}
>
{icon}
<span className="truncate">{value}</span>
<span className="whitespace-nowrap">{value}</span>
</span>
</span>
);
+1
View File
@@ -34,6 +34,7 @@ const localeLoaders: Record<SupportedLanguageCode, () => Promise<{ default: Tran
id: () => import('@trek/shared/i18n/id'),
ar: () => import('@trek/shared/i18n/ar'),
az: () => import('@trek/shared/i18n/az'),
he: () => import('@trek/shared/i18n/he'),
br: () => import('@trek/shared/i18n/br'),
cs: () => import('@trek/shared/i18n/cs'),
sk: () => import('@trek/shared/i18n/sk'),
+3 -3
View File
@@ -215,7 +215,7 @@ function useDefaultAtlasHandlers() {
// country features override this handler via server.use(...).
http.get('/api/addons/atlas/countries/geo', () => HttpResponse.json({ type: 'FeatureCollection', features: [] })),
// Handler for region GeoJSON fetch (triggered by loadRegionsForViewport when intersects=true)
http.get('/api/addons/atlas/regions/geo', () => HttpResponse.json({ features: [] })),
http.get('/api/addons/atlas/regions/geo/:code', () => HttpResponse.json({ features: [] })),
);
}
@@ -1589,7 +1589,7 @@ describe('AtlasPage', () => {
);
server.use(
http.get('/api/addons/atlas/regions/geo', () => HttpResponse.json({ features: [] })),
http.get('/api/addons/atlas/regions/geo/:code', () => HttpResponse.json({ features: [] })),
);
render(<AtlasPage />);
@@ -1746,7 +1746,7 @@ describe('AtlasPage', () => {
type: 'FeatureCollection',
features: [{ type: 'Feature', properties: { ISO_A2: 'FR', ADM0_A3: 'FRA', ISO_A3: 'FRA', NAME: 'France', ADMIN: 'France' }, geometry: null }],
})),
http.get('/api/addons/atlas/regions/geo', () => HttpResponse.json({
http.get('/api/addons/atlas/regions/geo/:code', () => HttpResponse.json({
type: 'FeatureCollection',
features: [{ type: 'Feature', properties: { iso_a2: 'FR', iso_3166_2: 'FR-IDF', name: 'Île-de-France', name_en: 'Île-de-France', admin: 'France' }, geometry: null }],
})),
@@ -25,6 +25,9 @@ function renderTab(overrides: Record<string, unknown> = {}) {
}
/** The card (a settingsKit SettingsCard, a <section>) whose <h2> matches the given heading text. */
/** The card with the TREK services, the providers and the search log, apart from the keys. */
const SERVICES = 'Place search and routing';
function card(heading: string | RegExp): HTMLElement {
return screen.getByRole('heading', { name: heading }).closest<HTMLElement>('section')!;
}
@@ -305,14 +308,14 @@ describe('AdminSettingsTab', () => {
// failing, which is quiet enough to be mistaken for the provider working.
renderTab({ placesProvider: 'amap', hasAmapKey: false });
expect(
within(card('API Keys')).getByText(/TREK index and OpenStreetMap alone/i),
within(card(SERVICES)).getByText(/TREK index and OpenStreetMap alone/i),
).toBeInTheDocument();
});
it('FE-ADMSET-022d: saving the provider goes through updateAppSettings, not the keys', () => {
const admin = renderTab({ placesProvider: 'auto' });
// A CustomSelect: the trigger shows the current choice, the menu is portaled.
fireEvent.click(within(card('API Keys')).getByRole('button', { name: 'Automatic' }));
fireEvent.click(within(card(SERVICES)).getByRole('button', { name: 'Automatic' }));
fireEvent.click(screen.getByRole('button', { name: 'Amap (高德地图)' }));
expect(admin.handleSavePlacesProvider).toHaveBeenCalledWith('amap');
});
@@ -322,10 +325,9 @@ describe('AdminSettingsTab', () => {
// still the admin's call (server managed.ts lists places_provider as theirs).
renderTab({ managed: true, placesProvider: 'auto' });
const keys = within(card('API Keys'));
expect(keys.queryByLabelText('Google Maps API Key')).not.toBeInTheDocument();
expect(keys.queryByLabelText(/Amap/)).not.toBeInTheDocument();
expect(keys.getByRole('button', { name: 'Automatic' })).toBeInTheDocument();
expect(screen.queryByRole('heading', { name: 'API Keys' })).not.toBeInTheDocument();
expect(screen.queryByLabelText('Google Maps API Key')).not.toBeInTheDocument();
expect(within(card(SERVICES)).getByRole('button', { name: 'Automatic' })).toBeInTheDocument();
});
it('FE-ADMSET-022f: an operator key keeps the managed install quiet', () => {
@@ -334,7 +336,7 @@ describe('AdminSettingsTab', () => {
renderTab({ managed: true, placesProvider: 'google', mapsKey: '', hasMapsKey: true });
expect(
within(card('API Keys')).queryByText(/falls back to OpenStreetMap/i),
within(card(SERVICES)).queryByText(/falls back to OpenStreetMap/i),
).not.toBeInTheDocument();
});
@@ -479,10 +481,10 @@ describe('AdminSettingsTab', () => {
expect(hint.textContent).toMatch(/provider/i);
});
it('FE-ADMSET-031: the API keys card leads with the TREK index and no weather panel', () => {
it('FE-ADMSET-031: the place search card leads with the TREK index and no weather panel', () => {
renderTab();
const keys = card('API Keys');
const keys = card(SERVICES);
expect(within(keys).getByRole('img', { name: 'TREK Places API' })).toBeInTheDocument();
expect(within(keys).getByText('Recommended default')).toBeInTheDocument();
// Weather needs no key, so it left a card about keys. The panel itself lives
+125 -120
View File
@@ -2,7 +2,7 @@ import React from 'react'
import { adminApi } from '../../api/client'
import { getApiErrorMessage } from '../../types'
import {
AlertTriangle, CheckCircle, Eye, EyeOff, FileType, Fingerprint, KeyRound, Loader2, LockKeyhole, LogIn,
AlertTriangle, CheckCircle, Compass, Eye, EyeOff, FileType, Fingerprint, KeyRound, Loader2, LockKeyhole, LogIn,
RefreshCw, Save, ShieldCheck, XCircle,
} from 'lucide-react'
import ToggleSwitch from '../../components/Settings/ToggleSwitch'
@@ -350,9 +350,7 @@ export default function AdminSettingsTab({ admin, t }: AdminSettingsTabProps): R
/>
</SettingsCard>
)}
</div>
<div className="min-w-0">
{/* Allowed File Types */}
<SettingsCard icon={FileType} title={t('admin.fileTypes')} hint={t('admin.fileTypesHint')}>
<div>
@@ -372,24 +370,134 @@ export default function AdminSettingsTab({ admin, t }: AdminSettingsTabProps): R
onClick={saveFileTypes}
/>
</SettingsCard>
</div>
{/* API Keys.
The card itself stays on a managed install: the TREK index needs no key,
and which keyed provider answers place search is the admin's call there
too (server managed.ts). What folds away is the operator's: the keys,
what a lookup costs, and the per-place Google switches. Those switches
sit under the keys rather than flat beside them because they are set
once and then never touched, and side by side a rarely-used option
looked as important as the key it depends on. Weather is a quiet row
for the same reason in reverse: it had the loudest treatment on the
card and is the one thing here with nothing to configure. */}
<div className="min-w-0">
{/* Place search and routing: TREK's own services first, then which provider
answers search and transit, and the search log. Apart from the keys, so a
keyless install reads its whole setup in one card. Everything here saves
as it is changed. */}
<SettingsCard icon={Compass} title={t('admin.servicesCard.title')} hint={t('admin.servicesCard.hint')}>
<TrekApiCard t={t} managed={managed} />
{!managed && (<>
{/* Transit Backend (#1699) — Transitous has no GTFS for much of Asia,
so an install can point transit search at Google instead, on the
same key. Falls back to Transitous when no key resolves. A block of
its own rather than a row inside the Google one: picking Transitous
is a decision about a provider that has nothing to do with a key. */}
<ProviderBlock title={t('admin.transitProvider.title')}>
<SettingsHint>{t('admin.transitProvider.subtitle')}</SettingsHint>
{/* The app's own select rather than the browser's: a native option list
is drawn by the OS, so it ignores the scheme, the radius and the
text-size setting the rest of this card follows. The menu portals to
the body, which is what lets it escape the card's overflow-hidden. */}
<CustomSelect
value={transitProvider}
onChange={async value => {
// A native select stayed silent when the option already selected was
// picked again; this one reports every pick, and a no-op PUT is still
// a write on an audited settings route.
if (value === transitProvider) return
const next = value === 'google' ? 'google' : 'transitous'
const previous = transitProvider
setTransitProviderState(next)
try {
const saved = await adminApi.updateTransitProvider(next)
setTransitGoogleKeySource(saved.googleKeySource)
} catch (err: unknown) {
// The select springs back on its own; without a word that reads
// as a broken control, not as a save that failed.
setTransitProviderState(previous)
toast.error(getApiErrorMessage(err, t('common.error')))
}
}}
options={[
{ value: 'transitous', label: t('admin.transitProvider.transitous') },
{ value: 'google', label: t('admin.transitProvider.google') },
]}
/>
<SettingsHint className="-mt-1.5">
{transitProvider === 'google' ? t('admin.transitProvider.googleHint') : t('admin.transitProvider.transitousHint')}
</SettingsHint>
{/* Picking Google without a key that resolves changes nothing — the
request-time fallback is silent, so this is the only place it can
be said. 'user-row' is the subtler half: the resolver's last step
is the caller's own row, so a personal key serves this admin and
nobody else. */}
{transitProvider === 'google' && transitGoogleKeySource === null && (
<Callout>{t('admin.transitProvider.noKeyWarning')}</Callout>
)}
{transitProvider === 'google' && transitGoogleKeySource === 'user-row' && (
<Callout>{t('admin.transitProvider.personalKeyWarning')}</Callout>
)}
</ProviderBlock>
</>)}
{/* Which keyed provider answers place search. Outside the managed guard
on purpose: the operator owns the credentials, but what their users
search against is still the admin's call (see server managed.ts). */}
<ProviderBlock title={t('admin.placesProvider.title')}>
<SettingsHint>{t('admin.placesProvider.subtitle')}</SettingsHint>
<div className={savingPlacesProvider ? 'opacity-60' : undefined}>
<CustomSelect
value={placesProvider}
disabled={savingPlacesProvider}
onChange={value => {
if (value === placesProvider) return
void handleSavePlacesProvider(String(value))
}}
options={[
{ value: 'auto', label: t('admin.placesProvider.auto') },
{ value: 'google', label: t('admin.placesProvider.google') },
{ value: 'amap', label: t('admin.placesProvider.amap') },
{ value: 'openstreetmap', label: t('admin.placesProvider.openstreetmap') },
]}
/>
</div>
{/* A provider chosen without a key behind it answers with
OpenStreetMap rather than failing, which is quiet enough to be
mistaken for the provider working. Say so. Asked of app-config
and not of the fields above: those are empty on a managed
install and on an operator key that came from the environment,
and saying "falls back to OpenStreetMap" to an admin whose
search works is worse than saying nothing. */}
{((placesProvider === 'google' && !hasMapsKey) || (placesProvider === 'amap' && !hasAmapKey)) && (
<Callout>{t('admin.placesProvider.missingKey')}</Callout>
)}
</ProviderBlock>
{/* The search log sits with the index rather than with a provider:
it records which result somebody picked, so a candidate index can
be judged against real searches later. Off unless switched on,
and nothing it records leaves the instance. */}
<SettingRows>
<SettingRow
label={t('admin.placeShadow.title')}
hint={t('admin.placeShadow.subtitle')}
control={
<ToggleSwitch
on={placeShadowEnabled}
label={t('admin.placeShadow.title')}
onToggle={() => togglePlaceShadow(!placeShadowEnabled)}
/>
}
/>
</SettingRows>
</SettingsCard>
{/* API Keys: only the keyed providers, Google, Unsplash and Amap. They are
the operator's on a managed install, so the card is not shown there;
which provider answers search stays the admin's call in the card above
(server managed.ts). The per-place Google switches sit under the key
because they are set once and then never touched. */}
{!managed && (
<SettingsCard icon={KeyRound} title={t('admin.apiKeys')} hint={t('admin.apiKeysHint')}>
{/* Three comparable blocks, in the order we would have people choose
them. Weather moved out entirely: it needs no key and had nothing
to configure, so it had no business in a card about keys. */}
<TrekApiCard t={t} managed={managed} />
{!managed && (<>
<ProviderBlock title={t('admin.mapsKey')}>
{/* Said before the field, not after it. Someone about to paste a key
should read this while deciding, not once they already have. */}
@@ -530,113 +638,10 @@ export default function AdminSettingsTab({ admin, t }: AdminSettingsTabProps): R
/>
<SettingsHint className="-mt-1.5">{t('admin.amapKeyHint')}</SettingsHint>
</ProviderBlock>
{/* Transit Backend (#1699) — Transitous has no GTFS for much of Asia,
so an install can point transit search at Google instead, on the
same key. Falls back to Transitous when no key resolves. A block of
its own rather than a row inside the Google one: picking Transitous
is a decision about a provider that has nothing to do with a key. */}
<ProviderBlock title={t('admin.transitProvider.title')}>
<SettingsHint>{t('admin.transitProvider.subtitle')}</SettingsHint>
{/* The app's own select rather than the browser's: a native option list
is drawn by the OS, so it ignores the scheme, the radius and the
text-size setting the rest of this card follows. The menu portals to
the body, which is what lets it escape the card's overflow-hidden. */}
<CustomSelect
value={transitProvider}
onChange={async value => {
// A native select stayed silent when the option already selected was
// picked again; this one reports every pick, and a no-op PUT is still
// a write on an audited settings route.
if (value === transitProvider) return
const next = value === 'google' ? 'google' : 'transitous'
const previous = transitProvider
setTransitProviderState(next)
try {
const saved = await adminApi.updateTransitProvider(next)
setTransitGoogleKeySource(saved.googleKeySource)
} catch (err: unknown) {
// The select springs back on its own; without a word that reads
// as a broken control, not as a save that failed.
setTransitProviderState(previous)
toast.error(getApiErrorMessage(err, t('common.error')))
}
}}
options={[
{ value: 'transitous', label: t('admin.transitProvider.transitous') },
{ value: 'google', label: t('admin.transitProvider.google') },
]}
/>
<SettingsHint className="-mt-1.5">
{transitProvider === 'google' ? t('admin.transitProvider.googleHint') : t('admin.transitProvider.transitousHint')}
</SettingsHint>
{/* Picking Google without a key that resolves changes nothing — the
request-time fallback is silent, so this is the only place it can
be said. 'user-row' is the subtler half: the resolver's last step
is the caller's own row, so a personal key serves this admin and
nobody else. */}
{transitProvider === 'google' && transitGoogleKeySource === null && (
<Callout>{t('admin.transitProvider.noKeyWarning')}</Callout>
)}
{transitProvider === 'google' && transitGoogleKeySource === 'user-row' && (
<Callout>{t('admin.transitProvider.personalKeyWarning')}</Callout>
)}
</ProviderBlock>
</>)}
{/* Which keyed provider answers place search. Outside the managed guard
on purpose: the operator owns the credentials, but what their users
search against is still the admin's call (see server managed.ts). */}
<ProviderBlock title={t('admin.placesProvider.title')}>
<SettingsHint>{t('admin.placesProvider.subtitle')}</SettingsHint>
<div className={savingPlacesProvider ? 'opacity-60' : undefined}>
<CustomSelect
value={placesProvider}
disabled={savingPlacesProvider}
onChange={value => {
if (value === placesProvider) return
void handleSavePlacesProvider(String(value))
}}
options={[
{ value: 'auto', label: t('admin.placesProvider.auto') },
{ value: 'google', label: t('admin.placesProvider.google') },
{ value: 'amap', label: t('admin.placesProvider.amap') },
{ value: 'openstreetmap', label: t('admin.placesProvider.openstreetmap') },
]}
/>
</div>
{/* A provider chosen without a key behind it answers with
OpenStreetMap rather than failing, which is quiet enough to be
mistaken for the provider working. Say so. Asked of app-config
and not of the fields above: those are empty on a managed
install and on an operator key that came from the environment,
and saying "falls back to OpenStreetMap" to an admin whose
search works is worse than saying nothing. */}
{((placesProvider === 'google' && !hasMapsKey) || (placesProvider === 'amap' && !hasAmapKey)) && (
<Callout>{t('admin.placesProvider.missingKey')}</Callout>
)}
</ProviderBlock>
{/* The search log sits with the index rather than with a provider:
it records which result somebody picked, so a candidate index can
be judged against real searches later. Off unless switched on,
and nothing it records leaves the instance. */}
<SettingRows>
<SettingRow
label={t('admin.placeShadow.title')}
hint={t('admin.placeShadow.subtitle')}
control={
<ToggleSwitch
on={placeShadowEnabled}
label={t('admin.placeShadow.title')}
onToggle={() => togglePlaceShadow(!placeShadowEnabled)}
/>
}
/>
</SettingRows>
{!managed && <SaveBar onClick={handleSaveApiKeys} saving={savingKeys} label={t('common.save')} />}
<SaveBar onClick={handleSaveApiKeys} saving={savingKeys} label={t('common.save')} />
</SettingsCard>
)}
</div>
</div>
+2
View File
@@ -5,6 +5,7 @@ import { fs } from '../../components/shared/DialogShell'
import { StatusPill } from '../../components/Settings/settingsKit'
import FoldSummary from './FoldSummary'
import ServiceIdentityPanel from '../../components/Admin/ServiceIdentityPanel'
import PlaceContribPanel from '../../components/Admin/PlaceContribPanel'
import type { TranslationFn } from '../../types'
import {
TREK_API_SOURCES as SOURCES,
@@ -83,6 +84,7 @@ export default function TrekApiCard({ t, managed = false }: TrekApiCardProps): R
</ul>
<ServiceIdentityPanel managed={managed} />
<PlaceContribPanel />
</div>
<details className="group border-t border-edge-faint">
+3 -3
View File
@@ -274,7 +274,7 @@ function installAtlasHandlers(over: Partial<Record<string, unknown>> = {}) {
http.get('/api/addons/atlas/bucket-list', () => HttpResponse.json({ items: over.bucket ?? [] })),
http.get('/api/addons/atlas/regions', () => HttpResponse.json({ regions: over.regions ?? {} })),
http.get('/api/addons/atlas/countries/geo', () => HttpResponse.json(over.geo ?? { type: 'FeatureCollection', features: [] })),
http.get('/api/addons/atlas/regions/geo', () => HttpResponse.json(over.regionGeo ?? { features: [] })),
http.get('/api/addons/atlas/regions/geo/:code', () => HttpResponse.json(over.regionGeo ?? { features: [] })),
http.get('/api/atlas-layers', () => HttpResponse.json({ layers: over.layers ?? [] })),
);
}
@@ -1053,8 +1053,8 @@ describe('useAtlas', () => {
await waitFor(() => expect(atlas.atlas_country_options.length).toBe(seen.length));
const requested: string[] = [];
server.use(http.get('/api/addons/atlas/regions/geo', ({ request }) => {
requested.push(new URL(request.url).searchParams.get('countries') ?? '');
server.use(http.get('/api/addons/atlas/regions/geo/:code', ({ params }) => {
requested.push(String(params.code));
return HttpResponse.json(regionGeo);
}));
+10 -10
View File
@@ -317,18 +317,18 @@ export function useAtlas() {
}
if (!toLoad.length) return
for (const code of toLoad) pendingRegionCodes.current.add(code)
apiClient.get(`/addons/atlas/regions/geo?countries=${toLoad.join(',')}`)
// One stable URL per country, so a country evicted by REGION_CACHE_MAX or seen on an earlier
// visit comes back from the browser cache. Every request settles; the layer rebuilds once.
void Promise.all(toLoad.map(c => apiClient.get(`/addons/atlas/regions/geo/${c}`)
.then(geoRes => {
const geo = geoRes.data
if (!geo?.features) return
let added = false
for (const c of toLoad) {
const features = geo.features.filter((f: any) => f.properties?.iso_a2?.toUpperCase() === c)
if (features.length > 0) { regionGeoCache.current[c] = { type: 'FeatureCollection', features }; touchRegionCode(c); added = true }
}
if (added) { evictRegionCache(); setRegionGeoLoaded(v => v + 1) }
const features = (geoRes.data?.features || []).filter((f: any) => f.properties?.iso_a2?.toUpperCase() === c)
if (features.length === 0) return false
regionGeoCache.current[c] = { type: 'FeatureCollection', features }
touchRegionCode(c)
return true
})
.catch(() => {})
.catch(() => false)))
.then(added => { if (added.some(Boolean)) { evictRegionCache(); setRegionGeoLoaded(v => v + 1) } })
.finally(() => { for (const code of toLoad) pendingRegionCodes.current.delete(code) })
}
loadRegionsForViewportRef.current = loadRegionsForViewport
+39
View File
@@ -0,0 +1,39 @@
import {
placeContribLogResponseSchema,
placeContribStateSchema,
placeContribWithdrawResponseSchema,
type PlaceContribDecisionRequest,
type PlaceContribLogQuery,
type PlaceContribLogResponse,
type PlaceContribState,
type PlaceContribWithdrawResponse,
} from '@trek/shared';
import { placeContribApi } from '../api/placeContrib';
import { requireOnline } from './onlineOnly';
/**
* The installation's decision on sharing place details, and what it sent.
* **Online-only, no Dexie table**, like the service identity beside it: a
* consent read from a stale copy would be worse than no answer.
*/
export const placeContribRepo = {
async state(signal?: AbortSignal): Promise<PlaceContribState> {
requireOnline();
return placeContribStateSchema.parse(await placeContribApi.state(signal));
},
async decide(body: PlaceContribDecisionRequest): Promise<PlaceContribState> {
requireOnline();
return placeContribStateSchema.parse(await placeContribApi.decide(body));
},
async log(query: Partial<PlaceContribLogQuery>, signal?: AbortSignal): Promise<PlaceContribLogResponse> {
requireOnline();
return placeContribLogResponseSchema.parse(await placeContribApi.log(query, signal));
},
async withdraw(): Promise<PlaceContribWithdrawResponse> {
requireOnline();
return placeContribWithdrawResponseSchema.parse(await placeContribApi.withdraw());
},
};
+16
View File
@@ -0,0 +1,16 @@
import { mapsApi } from '../api/client';
import { requireOnline } from './onlineOnly';
/**
* A provider's details of a place, looked up fresh (Google, the TREK index or
* OpenStreetMap, by the id the place carries). **Online-only, no Dexie table:**
* the point of asking is the current answer, and a cached one would offer the
* same values again as if they were new.
*/
export const placeDetailsRepo = {
async details(placeId: string, lang: string): Promise<Record<string, unknown> | null> {
requireOnline();
const answer = (await mapsApi.details(placeId, lang)) as { place?: Record<string, unknown> | null } | null;
return answer?.place ?? null;
},
};
+16 -1
View File
@@ -1,4 +1,4 @@
// FE-REPO-PLACE-001 to FE-REPO-PLACE-013
// FE-REPO-PLACE-001 to FE-REPO-PLACE-013, FE-REPO-PLACE-030
// Offline write paths (mutation queue + optimistic Dexie rows) and the bulk
// online paths, which tests/unit/repo/placeRepo.test.ts does not touch.
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'
@@ -51,6 +51,21 @@ describe('placeRepo.create — offline', () => {
})
})
describe('placeRepo — field origins offline', () => {
it('FE-REPO-PLACE-030: the queued body carries fieldOrigins for the replay, the optimistic row does not', async () => {
const { place } = await placeRepo.create(3, { name: 'Cafe', website: 'https://cafe.example', fieldOrigins: { website: 'user' } })
const cached = await offlineDb.places.get(place.id)
expect(cached).not.toHaveProperty('fieldOrigins')
expect(place).not.toHaveProperty('fieldOrigins')
await placeRepo.update(3, place.id, { phone: '+49 1', fieldOrigins: { phone: 'user' } })
const mutations = await queue()
expect(mutations.find(m => m.method === 'POST')?.body).toEqual({ name: 'Cafe', website: 'https://cafe.example', fieldOrigins: { website: 'user' } })
expect(mutations.find(m => m.method === 'PUT')?.body).toEqual({ phone: '+49 1', fieldOrigins: { phone: 'user' } })
expect(await offlineDb.places.get(place.id)).not.toHaveProperty('fieldOrigins')
})
})
describe('placeRepo.update — offline', () => {
it('FE-REPO-PLACE-003: merges into the cached row and sends the concurrency token', async () => {
await offlineDb.places.put(buildPlace({ id: 90, trip_id: 3, name: 'Old', updated_at: '2026-01-01T00:00:00.000Z' }))
+12 -2
View File
@@ -5,6 +5,16 @@ import { isEffectivelyOffline } from '../sync/networkMode'
import { onlineThenCache } from './withOfflineFallback'
import type { Place } from '../types'
/**
* What of a write the optimistic row keeps. `fieldOrigins` says which fields the
* user typed; it travels in the queued body for the server's origin tracking and
* is no column of the place.
*/
function placeRow(data: Record<string, unknown>): Record<string, unknown> {
const { fieldOrigins: _origins, ...row } = data
return row
}
export const placeRepo = {
async list(tripId: number | string, params?: Record<string, unknown>): Promise<{ places: Place[] }> {
return onlineThenCache(
@@ -25,7 +35,7 @@ export const placeRepo = {
if (isEffectivelyOffline()) {
const tempId = nextTempId()
const tempPlace: Place = {
...(data as Partial<Place>),
...(placeRow(data) as Partial<Place>),
id: tempId,
trip_id: Number(tripId),
name: (data.name as string) ?? 'New place',
@@ -56,7 +66,7 @@ export const placeRepo = {
// a row without it is invisible and never cleaned up.
const optimistic: Place = {
...(existing ?? {} as Place),
...(data as Partial<Place>),
...(placeRow(data) as Partial<Place>),
id: Number(id),
trip_id: Number(tripId),
}
@@ -166,4 +166,24 @@ export const adminHandlers = [
http.get('/api/admin/service-identity', () => {
return HttpResponse.json({ state: 'legacy', tier: 'legacy', keySource: null, services: [], lastSeenAt: null });
}),
// Sharing place details, inside the same card: not eligible, so no prompt opens in other tests.
http.get('/api/admin/places-contribute', () => {
const fields = { website: true, phone: true, email: true, opening_hours: true, description: true, image: true };
return HttpResponse.json({
termsVersion: 1,
ceiling: 'admin',
eligible: false,
ineligibleReason: 'not_production',
consent: { enabled: false, fields, termsVersion: null, decision: null, decidedBy: null, decidedAt: null },
showPrompt: false,
snoozedUntil: null,
active: false,
counts: { accepted: 0, duplicate: 0, rejected: 0, withheld: 0, retracted: 0 },
lastSuccessDay: null,
queue: { size: 0, cap: 5000, full: false },
pauseReason: null,
registrationOpen: false,
});
}),
];
+2 -1
View File
@@ -75,8 +75,9 @@ describe('getIntlLanguage', () => {
// ── FE-COMP-I18N-007/008: isRtlLanguage ──────────────────────────────────────
describe('isRtlLanguage', () => {
it('FE-COMP-I18N-007: returns true only for Arabic', () => {
it('FE-COMP-I18N-007: returns true for Arabic and Hebrew', () => {
expect(isRtlLanguage('ar')).toBe(true)
expect(isRtlLanguage('he')).toBe(true)
})
it('FE-COMP-I18N-008: returns false for all other supported languages', () => {
+1
View File
@@ -61,6 +61,7 @@ services:
# - UNSPLASH_ACCESS_KEY= # Optional. Unsplash Access Key for trip-cover / place-image search. Without one, TREK uses Unsplash's unauthenticated endpoint, which some datacenter/VPS IPs are blocked from (#1449). Free key at unsplash.com/developers. Can also be set per-admin in Admin > Settings; the env var overrides that.
# - TREK_PLACES_ENABLED=false # Optional. Place search (suggestions, full search, category buttons, Road trip search, import geocoding, offline downloads, and the OpenStreetMap ways and horse routes Tours reads) asks the TREK Places API at https://places.liketrek.com by default, so the server makes outbound requests to that host. Set false to search the way it did before 4.3.0 (OpenStreetMap, or your Google/Amap key) and send nothing there. No switch in the admin panel on purpose: whether searches leave the instance is decided here. (default: true)
# - TREK_PLACES_URL=https://places.liketrek.com # Optional. Base URL of a copy of the Places API you run yourself; it has to answer the same /v1 API. Read from configuration rather than typed by a user, so an address on your LAN or Docker network works without ALLOW_INTERNAL_NETWORK. (default: https://places.liketrek.com)
# - TREK_PLACES_CONTRIBUTE=admin # Optional. Whether an admin may let this installation send the place details its users typed in (website, phone, e-mail, opening hours, description, picture) to the TREK Places API, so every installation gets better details. admin leaves the choice to the admin panel, where it stays off until an admin agrees; off takes it away and nothing is ever sent. (default: admin)
# - TREK_SERVICES=off # Optional. Places search identifies this installation with a key it registers by itself on first use. off sends no key; searches then use the shared pool. (default: auto)
# - TREK_SERVICES_KEY= # Optional. A key issued for this installation; it wins over the stored one and turns self-registration off.
# - TREK_PHOTON_URL=https://photon.liketrek.com # Optional. The address search of the TREK services. With a key, search and reverse lookups ask it before Nominatim and fall back to Nominatim when it does not answer; never asked when NOMINATIM_URL is set. (default: https://photon.liketrek.com)
+1
View File
@@ -70,6 +70,7 @@ DEMO_MODE=false # Demo mode: resets data hourly
# TREK_PLACES_ENABLED=false # Whether place search asks the TREK Places API at https://places.liketrek.com: suggestions, the full search, the category buttons on the map, the Road trip search along the route, import geocoding, offline downloads, and the OpenStreetMap ways and horse routes Tours reads. It is on by default and has no switch in the admin panel, because whether searches leave the instance is a deployment decision. Set false to search the way it did before 4.3.0 (OpenStreetMap, or your Google/Amap key) and send nothing to that host. (default: true)
# TREK_PLACES_URL=https://places.liketrek.com # Base URL of a copy of the Places API you run yourself; it has to answer the same /v1 API. Read from configuration rather than typed by a user, so an address on your LAN or Docker network works without ALLOW_INTERNAL_NETWORK. (default: https://places.liketrek.com)
# TREK_PLACES_CONTRIBUTE=admin # Whether an admin may let this installation send place details its users typed in (website, phone, e-mail, opening hours, description, picture) to the TREK Places API, so every installation gets better details. admin shows the choice in the admin panel, where it stays off until an admin agrees; off takes the choice away and nothing is ever sent. Nothing is sent outside NODE_ENV=production, in demo mode, with a custom TREK_PLACES_URL or with TREK_SERVICES=off. (default: admin)
# TREK_SERVICES=auto # How this installation identifies itself to the TREK services. On first use it registers itself in the background and keeps a key in the database; nothing to click, no account. off sends no key, and searches use the shared pool. (default: auto)
# TREK_SERVICES_KEY= # A key issued to you for this installation. Wins over the stored one and turns self-registration off; meant for hosted and pre-provisioned instances. (default: none)
# TREK_SERVICES_HOSTS=places.liketrek.com,photon.liketrek.com,valhalla.liketrek.com # Comma-separated hosts that receive the installation key over https. No other host ever sees it. (default: places.liketrek.com,photon.liketrek.com,valhalla.liketrek.com)
File diff suppressed because one or more lines are too long
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.

Some files were not shown because too many files have changed in this diff Show More