mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-11-28 15:40:06 +00:00
Compare commits
128 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 97a624c74e | |||
| 058c3b3909 | |||
| 7f3ead2c85 | |||
| 1553be3d5b | |||
| fc891c16b2 | |||
| bcad069705 | |||
| 610845e84d | |||
| 4705d88933 | |||
| ed134fdef3 | |||
| 8c5e7373d3 | |||
| 5b27624c33 | |||
| ac0f8f052d | |||
| 81b66d3170 | |||
| 9bfdd10638 | |||
| bbc9c72168 | |||
| 5c5c468489 | |||
| 5685cdfe13 | |||
| 82ded80978 | |||
| 46a2fd2bbb | |||
| ff676c8fc2 | |||
| 0b6a77eeb5 | |||
| 7c6189f504 | |||
| 6bbe597719 | |||
| 218304179c | |||
| a6328cef3b | |||
| 96d8b5c664 | |||
| b5350287a4 | |||
| dbe0b847bd | |||
| fc1022a452 | |||
| 8b008a74fe | |||
| 1fa5c8cec2 | |||
| 443a4fd488 | |||
| 8d5d34fbb3 | |||
| 57fb2cf47b | |||
| 20d10d765d | |||
| fd6d1969f5 | |||
| 8c0cca536a | |||
| dd1a117b92 | |||
| 59b8d00373 | |||
| 9ea489ac97 | |||
| 17c56326e9 | |||
| f3bdcf7ffb | |||
| e7b900d309 | |||
| ffd9338217 | |||
| 2186d8b230 | |||
| 06aaddc34d | |||
| 6f669920f1 | |||
| 1fb20a542c | |||
| d8be9a40e7 | |||
| 512584b4f1 | |||
| 985998e757 | |||
| 742c0dd72d | |||
| efd34df038 | |||
| 321980c95b | |||
| d4595269b5 | |||
| 32de7adbf6 | |||
| fef7ac4587 | |||
| 7a57c58dd0 | |||
| 3dd63331bc | |||
| 20c8457f18 | |||
| eaef3c014e | |||
| f02c0e088b | |||
| 2915ea573a | |||
| 407de33560 | |||
| addcbe4801 | |||
| a9fd443b63 | |||
| b8dffdbb13 | |||
| 3b42ffa67b | |||
| 2ea1c99e31 | |||
| d383d3527b | |||
| 05843c8e5b | |||
| 19270adef8 | |||
| f9ab280b7e | |||
| c88d3abc5e | |||
| 10d95a39ac | |||
| 7d802081ce | |||
| 7586126797 | |||
| 9fa2bef101 | |||
| ed1bba9371 | |||
| 3c1cf8b347 | |||
| 1ed77870f9 | |||
| 22ee4dbac7 | |||
| 6926591112 | |||
| 66382e791b | |||
| 32837afe2e | |||
| 05f4c84885 | |||
| 6905729ab6 | |||
| 85aa1c91ff | |||
| de9901d941 | |||
| 95a0cd2f77 | |||
| f922068a8e | |||
| 5c5d85ef60 | |||
| d83e98366b | |||
| 756eae39ff | |||
| 4f66a344ca | |||
| 96b2778c2f | |||
| 98c883b4e8 | |||
| df82208bd5 | |||
| 18867d9499 | |||
| 13910464e5 | |||
| 903868c08c | |||
| 434baaf6fd | |||
| d9d901e52d | |||
| 50cb9364f6 | |||
| b6c50eb146 | |||
| c1c77d89b5 | |||
| 70af8132ef | |||
| 85182d2f52 | |||
| c65e9bf76e | |||
| 3754518d37 | |||
| eed5f75487 | |||
| f29112698e | |||
| d556d706b7 | |||
| 71673085bb | |||
| 19a01d493b | |||
| 462f08727c | |||
| 58298703e1 | |||
| 17e75947f0 | |||
| 4f1e29b02c | |||
| d1ee3ceccb | |||
| 69a976e942 | |||
| f928f4b1ca | |||
| aa79d6286a | |||
| eeff0398a7 | |||
| 7fe4fbb683 | |||
| afbeef64c2 | |||
| 293ec89db4 | |||
| 8809654a43 |
@@ -26,15 +26,48 @@ updates:
|
||||
prefix: chore(deps)
|
||||
prefix-development: chore(deps-dev)
|
||||
groups:
|
||||
# Packages that release in lockstep move together, so a PR never pins
|
||||
# half of them on one version and half on the next.
|
||||
# better-sqlite3 and kysely are pinned exactly by @mikro-orm/sqlite and
|
||||
# share its connection, so they move with MikroORM.
|
||||
mikro-orm:
|
||||
patterns: ['@mikro-orm/*', better-sqlite3, kysely]
|
||||
update-types: [minor, patch]
|
||||
nestjs:
|
||||
patterns: ['@nestjs/*']
|
||||
update-types: [minor, patch]
|
||||
npm-minor-and-patch:
|
||||
update-types: [minor, patch]
|
||||
ignore:
|
||||
# nestjs-zod, which validates every request body, does not support
|
||||
# NestJS 12 yet. The framework moves by hand once it does.
|
||||
- dependency-name: '@nestjs/*'
|
||||
update-types: [version-update:semver-major]
|
||||
# TypeScript 7 is the native compiler and has no JavaScript API yet:
|
||||
# typescript-eslint, the coverage instrumenter and the Postgres probe all
|
||||
# call into it (readConfigFile, ScriptTarget). It moves by hand once the
|
||||
# tooling supports it.
|
||||
- dependency-name: typescript
|
||||
update-types: [version-update:semver-major]
|
||||
# mapbox-gl 3.33 and later read the worker registry key before handling
|
||||
# Set and Error, and maplibre-gl, bundled beside it, stamps that key on
|
||||
# both built-ins: every vector tile then fails with "reading 'omit'".
|
||||
# glWorkerRegistry.test.ts fails on a version with that order; it moves
|
||||
# by hand once mapbox-gl checks the built-ins first again.
|
||||
- dependency-name: mapbox-gl
|
||||
versions: ['>=3.33.0']
|
||||
# The packages below move by hand, each for its reason. A security
|
||||
# advisory for one of them still shows up in the Security tab, where it
|
||||
# is handled together with that reason.
|
||||
#
|
||||
# Pinned exactly by @nestjs/schedule; a newer cron of our own would be a
|
||||
# second copy whose CronJob the scheduler does not accept.
|
||||
- dependency-name: cron
|
||||
update-types: [version-update:semver-major, version-update:semver-minor, version-update:semver-patch]
|
||||
# Root pins that must name the rollup version the lockfile installs (the
|
||||
# Alpine image needs the musl binaries).
|
||||
- dependency-name: '@rollup/rollup-linux-*-musl'
|
||||
update-types: [version-update:semver-major, version-update:semver-minor, version-update:semver-patch]
|
||||
|
||||
# plugin-sdk is standalone with a lockfile of its own and ships to npm.
|
||||
- package-ecosystem: npm
|
||||
|
||||
@@ -105,9 +105,63 @@ jobs:
|
||||
track: ${{ inputs.track || 'internal' }}
|
||||
status: draft
|
||||
|
||||
# The same build for installs outside Google Play: the universal APK Google
|
||||
# Play makes of this bundle, signed with the Play app signing key, published
|
||||
# to liketrek/trek-android for Obtainium (wiki/Native-Apps.md). Only for a
|
||||
# release tag, and held back while the app needs a server version that is
|
||||
# not released yet.
|
||||
- name: Whether the latest server release serves this build
|
||||
id: released
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
run: |
|
||||
tag=$(gh api "repos/$GITHUB_REPOSITORY/releases/latest" --jq .tag_name)
|
||||
git fetch --depth=1 origin "refs/tags/$tag:refs/tags/$tag"
|
||||
git show "$tag:server/src/nest/health/features.controller.ts" > "$RUNNER_TEMP/released-features.ts"
|
||||
node scripts/ci/android-apk-release.mjs guard "$RUNNER_TEMP/released-features.ts" >> "$GITHUB_OUTPUT"
|
||||
|
||||
- name: Universal APK from Google Play
|
||||
if: steps.released.outputs.publish == 'true'
|
||||
env:
|
||||
PLAY_APK_SERVICE_ACCOUNT_JSON: ${{ secrets.PLAY_APK_SERVICE_ACCOUNT_JSON }}
|
||||
APK: trek-${{ steps.version.outputs.version }}.apk
|
||||
run: |
|
||||
printf '%s' "$PLAY_APK_SERVICE_ACCOUNT_JSON" > "$RUNNER_TEMP/play-apk.json"
|
||||
node scripts/ci/android-apk-release.mjs download "$RUNNER_TEMP/play-apk.json" com.liketrek.trek \
|
||||
"${{ steps.version.outputs.build }}" "$RUNNER_TEMP/$APK"
|
||||
rm -f "$RUNNER_TEMP/play-apk.json"
|
||||
cd "$RUNNER_TEMP" && sha256sum "$APK" > "$APK.sha256"
|
||||
|
||||
- uses: actions/create-github-app-token@v3
|
||||
if: steps.released.outputs.publish == 'true'
|
||||
id: apk-token
|
||||
with:
|
||||
app-id: ${{ secrets.RELEASE_APP_ID }}
|
||||
private-key: ${{ secrets.RELEASE_APP_PRIVATE_KEY }}
|
||||
owner: liketrek
|
||||
repositories: trek-android
|
||||
|
||||
# One release per app version: a newer build of the same version replaces
|
||||
# its APK, so the release always holds what Google Play holds for it.
|
||||
- name: Publish to liketrek/trek-android
|
||||
if: steps.released.outputs.publish == 'true'
|
||||
env:
|
||||
GH_TOKEN: ${{ steps.apk-token.outputs.token }}
|
||||
VERSION: ${{ steps.version.outputs.version }}
|
||||
BUILD: ${{ steps.version.outputs.build }}
|
||||
run: |
|
||||
apk="$RUNNER_TEMP/trek-$VERSION.apk"
|
||||
notes="TREK $VERSION for Android (build $BUILD): the build Google Play distributes, with the same signature. Connect it to your own TREK server; push and TREK Cloud need Google Play services. Changes: https://github.com/liketrek/TREK/releases"
|
||||
if gh release view "v$VERSION" -R liketrek/trek-android > /dev/null 2>&1; then
|
||||
gh release upload "v$VERSION" -R liketrek/trek-android --clobber "$apk" "$apk.sha256"
|
||||
gh release edit "v$VERSION" -R liketrek/trek-android --notes "$notes"
|
||||
else
|
||||
gh release create "v$VERSION" -R liketrek/trek-android --title "TREK $VERSION" --notes "$notes" "$apk" "$apk.sha256"
|
||||
fi
|
||||
|
||||
- name: Remove the upload key
|
||||
if: always()
|
||||
run: rm -f "$RUNNER_TEMP/upload.jks"
|
||||
run: rm -f "$RUNNER_TEMP/upload.jks" "$RUNNER_TEMP/play-apk.json"
|
||||
|
||||
ios:
|
||||
if: github.repository == 'liketrek/TREK'
|
||||
|
||||
@@ -1224,6 +1224,14 @@ jobs:
|
||||
--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"
|
||||
helm template trek charts/trek \
|
||||
--set-json 'extraObjects=[{"apiVersion":"batch/v1","kind":"CronJob","metadata":{"name":"{{ include \"trek.fullname\" . }}-backup-copy"},"spec":{"schedule":"0 3 * * *","jobTemplate":{"spec":{"template":{"spec":{"restartPolicy":"OnFailure","containers":[{"name":"copy","image":"busybox:1.36","command":["ls","/data/backups"],"volumeMounts":[{"name":"data","mountPath":"/data","readOnly":true}]}],"volumes":[{"name":"data","persistentVolumeClaim":{"claimName":"{{ include \"trek.fullname\" . }}-data","readOnly":true}}]}}}}}},"apiVersion: v1\nkind: ConfigMap\nmetadata:\n name: {{ .Release.Name }}-notes\ndata:\n release: {{ .Release.Name | quote }}\n"]' \
|
||||
> "$out/extra-objects.yaml"
|
||||
# kubeconform accepts a name that still reads {{ ... }}, so check that both forms went through tpl.
|
||||
if grep -n '{{' "$out/extra-objects.yaml"; then
|
||||
echo "::error::extraObjects left a template unrendered"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
- name: Check the manifests against the Kubernetes schemas
|
||||
# The pinned Gateway API schema adds HTTPRoute validation without skipping unknown resources.
|
||||
|
||||
@@ -101,6 +101,8 @@ COPY --from=gosu-build /out/gosu /usr/local/bin/gosu
|
||||
ENV XDG_CACHE_HOME=/tmp/kf6-cache
|
||||
# Prevent Qt from probing for a display in headless containers.
|
||||
ENV QT_QPA_PLATFORM=offscreen
|
||||
# A UTF-8 locale, so Qt does not warn about the C locale on every extractor run.
|
||||
ENV LANG=C.UTF-8
|
||||
# Fixed path for both amd64 (static binary) and arm64 (symlink to apt binary).
|
||||
# Override with KITINERARY_EXTRACTOR_PATH if you install it elsewhere.
|
||||
ENV KITINERARY_EXTRACTOR_PATH=/usr/local/bin/kitinerary-extractor
|
||||
|
||||
@@ -12,14 +12,14 @@ TREK has grown from a travel planner into a whole ecosystem for trips: plan toge
|
||||
|
||||
<br />
|
||||
|
||||
<a href="https://apps.apple.com/app/id6831237775"><picture><source media="(prefers-color-scheme: dark)" srcset="docs/app/app-store-dark.svg" /><source media="(prefers-color-scheme: light)" srcset="docs/app/app-store-light.svg" /><img src="docs/app/app-store-light.svg" alt="Download TREK on the App Store, with a QR code" width="320" /></picture></a>
|
||||
|
||||
<a href="https://play.google.com/store/apps/details?id=com.liketrek.trek"><picture><source media="(prefers-color-scheme: dark)" srcset="docs/app/google-play-dark.svg" /><source media="(prefers-color-scheme: light)" srcset="docs/app/google-play-light.svg" /><img src="docs/app/google-play-light.svg" alt="Get TREK on Google Play, with a QR code" width="320" /></picture></a>
|
||||
|
||||
<br />
|
||||
|
||||
<a href="https://demo.liketrek.com"><img alt="Demo" src="https://img.shields.io/badge/Demo-try-111827?style=for-the-badge" /></a>
|
||||
|
||||
<a href="https://hub.docker.com/r/mauriceboe/trek"><img alt="Docker" src="https://img.shields.io/badge/Docker-ready-2496ED?style=for-the-badge" /></a>
|
||||
|
||||
<a href="https://sonarcloud.io/project/overview?id=liketrek_TREK"><img alt="Sonar Quality Gate" src="https://img.shields.io/sonar/quality_gate/liketrek_TREK?server=https%3A%2F%2Fsonarcloud.io&style=for-the-badge" /></a>
|
||||
|
||||
<img alt="GitHub Actions Workflow Status" src="https://img.shields.io/github/actions/workflow/status/liketrek/TREK/test.yml?branch=main&style=for-the-badge">
|
||||
|
||||
<a href="https://discord.gg/NhZBDSd4qW"><img alt="Discord" src="https://img.shields.io/badge/Discord-join-5865F2?style=for-the-badge" /></a>
|
||||
|
||||
<a href="https://kanban.pakulat.org/shared/I4wxF6inOOMB0C6hH6kQm3efyNxFjwyI"><img alt="Roadmap" src="https://img.shields.io/badge/Roadmap-view-0EA5E9?style=for-the-badge" /></a>
|
||||
@@ -38,7 +38,6 @@ TREK has grown from a travel planner into a whole ecosystem for trips: plan toge
|
||||
|
||||
<a href="https://github.com/liketrek/TREK"><img alt="Stars" src="https://img.shields.io/github/stars/liketrek/trek?style=for-the-badge&label=Stars&color=6B7280" /></a>
|
||||
|
||||
<sub>PUBLIC SERVICES PROUDLY SPONSORED BY</sub><br /><a href="https://cloud.dataforest.net/en?mtm_campaign=trek"><picture><source media="(prefers-color-scheme: dark)" srcset="docs/sponsors/dataforest-light.svg" /><source media="(prefers-color-scheme: light)" srcset="docs/sponsors/dataforest-dark.svg" /><img src="docs/sponsors/dataforest-dark.svg" alt="dataforest cloud" height="30" /></picture></a>
|
||||
</div>
|
||||
|
||||
---
|
||||
@@ -53,14 +52,8 @@ TREK has grown from a travel planner into a whole ecosystem for trips: plan toge
|
||||
|
||||
## What you get
|
||||
|
||||
<picture>
|
||||
<source media="(max-width: 700px)" srcset="docs/tiles/grid-mobile.svg" />
|
||||
<source media="(prefers-color-scheme: dark)" srcset="docs/tiles/grid-desktop-dark.svg" />
|
||||
<img src="docs/tiles/grid-desktop.svg" alt="Plan, track, share" width="100%" />
|
||||
</picture>
|
||||
|
||||
<details>
|
||||
<summary><b>See all features</b></summary>
|
||||
<summary><h3>See all features</h3></summary>
|
||||
|
||||
<br />
|
||||
|
||||
@@ -220,34 +213,12 @@ Most of what follows is an addon an admin switches on or off. Lists, Costs, Docu
|
||||
|
||||
<br />
|
||||
|
||||
## Powered by [dataforest cloud](https://cloud.dataforest.net/en?mtm_campaign=trek)
|
||||
|
||||
<div align="center">
|
||||
|
||||
<br />
|
||||
<sub>POWERED BY</sub><br />
|
||||
<a href="https://cloud.dataforest.net/en?mtm_campaign=trek"><picture><source media="(prefers-color-scheme: dark)" srcset="docs/sponsors/dataforest-light.svg" /><source media="(prefers-color-scheme: light)" srcset="docs/sponsors/dataforest-dark.svg" /><img src="docs/sponsors/dataforest-dark.svg" alt="dataforest cloud" height="40" /></picture></a>
|
||||
|
||||
<a href="https://cloud.dataforest.net/en?mtm_campaign=trek">
|
||||
<picture>
|
||||
<source media="(prefers-color-scheme: dark)" srcset="docs/sponsors/dataforest-light.svg" />
|
||||
<source media="(prefers-color-scheme: light)" srcset="docs/sponsors/dataforest-dark.svg" />
|
||||
<img src="docs/sponsors/dataforest-dark.svg" alt="dataforest cloud" height="60" />
|
||||
</picture>
|
||||
</a>
|
||||
|
||||
<br />
|
||||
<br />
|
||||
|
||||
**Every TREK installation in the world searches through servers that [dataforest cloud](https://cloud.dataforest.net/en?mtm_campaign=trek) sponsors.**
|
||||
|
||||
The place index with over 88 million places, the address search in every TREK language and the planet-wide routing all run on [dataforest cloud](https://cloud.dataforest.net/en?mtm_campaign=trek) in Frankfurt, Germany, free of charge for everyone who self-hosts TREK. Without this sponsorship, these services would not exist in this form.
|
||||
|
||||
Thank you, [dataforest](https://cloud.dataforest.net/en?mtm_campaign=trek), for backing open source this generously. 💚
|
||||
|
||||
<br />
|
||||
|
||||
<a href="https://cloud.dataforest.net/en?mtm_campaign=trek"><img alt="Visit dataforest cloud" src="https://img.shields.io/badge/Visit-dataforest_cloud-02C382?style=for-the-badge" /></a>
|
||||
|
||||
Looking for a server for your own TREK? [dataforest cloud](https://cloud.dataforest.net/en?mtm_campaign=trek) is where TREK's own services live.
|
||||
The place index with 88 million places, the address search and the planet-wide routing run on <a href="https://cloud.dataforest.net/en?mtm_campaign=trek">dataforest cloud</a> in Frankfurt, free for every self-hosted TREK. Thank you! 💚
|
||||
|
||||
</div>
|
||||
|
||||
@@ -255,13 +226,7 @@ Looking for a server for your own TREK? [dataforest cloud](https://cloud.datafor
|
||||
|
||||
## AI usage
|
||||
|
||||
We use LLM-assisted coding tools across parts of this codebase. Nothing ships that a
|
||||
maintainer has not read and understood: every change goes through a pull request, is
|
||||
reviewed and tested, and has a human who can answer for it. "The AI wrote that" is not
|
||||
an answer any of us would accept from ourselves.
|
||||
|
||||
See [**How we use AI in TREK**](https://github.com/liketrek/TREK/discussions/1851) for
|
||||
the details.
|
||||
We use LLM-assisted coding tools, and nothing ships that a maintainer has not read, reviewed, tested and can answer for. More in [How we use AI in TREK](https://github.com/liketrek/TREK/discussions/1851).
|
||||
|
||||
<br />
|
||||
|
||||
@@ -285,7 +250,7 @@ Open `http://localhost:3000`, or `http://<server-ip>:3000` from another machine.
|
||||
|
||||
<div align="center">
|
||||
|
||||
<a href="#docker-compose-production">Docker Compose</a> · <a href="#helm-kubernetes">Helm / Kubernetes</a> · <a href="#install-as-app-pwa">Install as PWA</a> · <a href="#reverse-proxy">Reverse Proxy</a>
|
||||
<a href="#docker-compose-production">Docker Compose</a> · <a href="#helm-kubernetes">Helm / Kubernetes</a> · <a href="#reverse-proxy">Reverse Proxy</a>
|
||||
|
||||
</div>
|
||||
|
||||
@@ -342,18 +307,6 @@ See [`charts/README.md`](https://github.com/liketrek/TREK/blob/main/charts/READM
|
||||
|
||||
<br />
|
||||
|
||||
<h2 id="install-as-app-pwa">Install as App (PWA)</h2>
|
||||
|
||||
TREK works as a Progressive Web App, and the TREK Travel Planner app for iPhone, iPad and Android connects to the same server ([Native Apps](https://github.com/liketrek/TREK/wiki/Native-Apps)). To install the web app instead:
|
||||
|
||||
1. Open TREK in the browser (HTTPS required)
|
||||
2. **iOS**: Share ▸ *Add to Home Screen*
|
||||
3. **Android**: Menu ▸ *Install app* (or *Add to Home Screen*)
|
||||
|
||||
TREK then launches fullscreen with its own icon, just like a native app.
|
||||
|
||||
<br />
|
||||
|
||||
## Updating
|
||||
|
||||
See [Updating](https://github.com/liketrek/TREK/wiki/Updating) — Docker Compose,
|
||||
@@ -442,6 +395,8 @@ Caddy handles TLS and WebSockets automatically.
|
||||
Every variable, its default and what it does: see
|
||||
[Environment Variables](https://github.com/liketrek/TREK/wiki/Environment-Variables).
|
||||
|
||||
<br />
|
||||
|
||||
## Data sources
|
||||
|
||||
The Atlas map's country and sub-national (province/county) boundaries come from
|
||||
|
||||
@@ -60,3 +60,4 @@ See `values.yaml` for more options.
|
||||
- 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.
|
||||
- `podSecurityContext` defaults to `fsGroup: 1000` with `fsGroupChangePolicy: OnRootMismatch`, and `securityContext` (the container's) is empty. The container then starts as root, hands `/app/data` and `/app/uploads` to `node` (uid 1000) if the directory or anything directly inside it is not owned by `node` yet, and drops to `node`. Deeper files are not checked. Only the owning user is changed (plus a `root` group), so a different `fsGroup` stays in place. A volume that refuses `chown` (NFS with `root_squash`) logs a warning instead; set `runAsUser: 1000` then. To run as `node` from the start, for example under the `restricted` Pod Security Standard, set `podSecurityContext.runAsUser: 1000` and `runAsGroup: 1000`; the image then skips that step and the privilege drop. See the example in `values.yaml`.
|
||||
- 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`.
|
||||
- Use `extraObjects` to render further Kubernetes objects next to the chart's own, for example a backup `CronJob`. Each item is a map or a string of YAML, and `{{ }}` in it is evaluated, so `{{ .Release.Name }}` works. A backup job should copy TREK's own backups from `backups/` on the data volume and mount it read only, since that volume also holds the encryption key. The archives carry `.encryption_key` too unless `ENCRYPTION_KEY` is set, so protect the copy's destination like the data volume.
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
apiVersion: v2
|
||||
name: trek
|
||||
version: 5.1.4
|
||||
version: 5.2.1
|
||||
description: Minimal Helm chart for TREK app
|
||||
appVersion: "5.1.4"
|
||||
appVersion: "5.2.1"
|
||||
|
||||
@@ -0,0 +1,8 @@
|
||||
{{- range .Values.extraObjects }}
|
||||
---
|
||||
{{- if kindIs "string" . }}
|
||||
{{ tpl . $ }}
|
||||
{{- else }}
|
||||
{{ tpl (toYaml .) $ }}
|
||||
{{- end }}
|
||||
{{- end }}
|
||||
@@ -338,6 +338,29 @@ extraVolumes: []
|
||||
# readOnly: true
|
||||
extraVolumeMounts: []
|
||||
|
||||
# Further Kubernetes objects the chart renders next to its own, for example a Job, a
|
||||
# CronJob or a ConfigMap. Each item is rendered as written, either as a map or as a
|
||||
# string of YAML, and {{ }} in it is evaluated, so {{ include "trek.fullname" . }} or
|
||||
# {{ .Release.Name }} work, in both forms. Write literal braces as {{ "{{" }}.
|
||||
# A backup job must only read the data volume: it also holds the encryption key and the
|
||||
# server's secrets, and a second writer corrupts travel.db. Rather than copying the live
|
||||
# travel.db, copy TREK's own backups (Admin, Backup, automatic backups) from backups/ in
|
||||
# that volume. Those archives carry .encryption_key too (unless ENCRYPTION_KEY is set),
|
||||
# so protect the job's destination like the data volume itself.
|
||||
# extraObjects:
|
||||
# - apiVersion: v1
|
||||
# kind: ConfigMap
|
||||
# metadata:
|
||||
# name: '{{ include "trek.fullname" . }}-extra'
|
||||
# data:
|
||||
# note: hello
|
||||
# - |
|
||||
# apiVersion: v1
|
||||
# kind: ConfigMap
|
||||
# metadata:
|
||||
# name: {{ .Release.Name }}-notes
|
||||
extraObjects: []
|
||||
|
||||
resources:
|
||||
requests:
|
||||
cpu: 100m
|
||||
|
||||
@@ -1,6 +1,9 @@
|
||||
package com.liketrek.trek;
|
||||
|
||||
import android.content.Intent;
|
||||
import android.graphics.Color;
|
||||
import android.graphics.drawable.ColorDrawable;
|
||||
import android.graphics.drawable.Drawable;
|
||||
import android.graphics.drawable.GradientDrawable;
|
||||
import android.os.Bundle;
|
||||
import android.util.TypedValue;
|
||||
@@ -11,11 +14,13 @@ import android.view.Menu;
|
||||
import android.view.View;
|
||||
import android.view.ViewGroup;
|
||||
import android.webkit.CookieManager;
|
||||
import android.webkit.WebView;
|
||||
import android.widget.Button;
|
||||
import android.widget.FrameLayout;
|
||||
import android.widget.LinearLayout;
|
||||
import android.widget.TextView;
|
||||
import com.getcapacitor.BridgeActivity;
|
||||
import com.getcapacitor.WebViewListener;
|
||||
import com.liketrek.trek.screen.TrekKeyCommands;
|
||||
import com.liketrek.trek.tiles.TrekTileStore;
|
||||
import com.liketrek.trek.widget.TrekWidgetUpdater;
|
||||
@@ -26,6 +31,9 @@ public class MainActivity extends BridgeActivity {
|
||||
/** The share sheet (share/ShareActivity.kt) left an item for the import. */
|
||||
public static final String ACTION_SHARE_HANDOFF = "com.liketrek.trek.SHARE_HANDOFF";
|
||||
|
||||
/** The page colour of the address screen (native-shell/shell.css --page). */
|
||||
private static final int SHELL_PAGE = 0xFFFFFAF5;
|
||||
|
||||
@Override
|
||||
protected void onCreate(Bundle savedInstanceState) {
|
||||
registerPlugin(TrekShellPlugin.class);
|
||||
@@ -57,6 +65,33 @@ public class MainActivity extends BridgeActivity {
|
||||
// and Chrome honours that, but the WebView draws the stretch on its root
|
||||
// scroller natively. It scales the whole view, top bar and bottom dock included.
|
||||
bridge.getWebView().setOverScrollMode(View.OVER_SCROLL_NEVER);
|
||||
// The address screen, and the step from it to the server just picked:
|
||||
// the warm ground of the first screens behind everything, so the
|
||||
// restart and the page's first frames do not flash white. The window's
|
||||
// colour is also what an older WebView shows under the status bar,
|
||||
// where it lays the page out between the bars (native/appBoot.ts).
|
||||
if (!onServer || restarting) {
|
||||
Drawable windowBackground = getWindow().getDecorView().getBackground();
|
||||
// A new drawable: setBackgroundColor would recolour the theme's own one,
|
||||
// and the restore below would hand the window the warm ground back.
|
||||
getWindow().getDecorView().setBackground(new ColorDrawable(SHELL_PAGE));
|
||||
bridge.getWebView().setBackgroundColor(SHELL_PAGE);
|
||||
// Once the server's page is up, the window is the one a normal launch
|
||||
// has, so the status bar of an older WebView follows the system again.
|
||||
if (onServer) {
|
||||
bridge.addWebViewListener(new WebViewListener() {
|
||||
private boolean restored;
|
||||
|
||||
@Override
|
||||
public void onPageLoaded(WebView webView) {
|
||||
if (restored) return;
|
||||
restored = true;
|
||||
getWindow().getDecorView().setBackground(windowBackground);
|
||||
webView.setBackgroundColor(Color.WHITE);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
// Set before any WebView callback can run: they are posted to this thread.
|
||||
if (onServer) {
|
||||
bridge.setWebViewClient(
|
||||
|
||||
@@ -0,0 +1,234 @@
|
||||
import { devices, expect, test, type Locator, type Page } from '@playwright/test';
|
||||
import { encodePolyline6 } from '@trek/shared';
|
||||
|
||||
async function createTourTrip(page: Page): Promise<number> {
|
||||
const trip = await page.request.post('/api/trips', {
|
||||
data: { title: 'Tour type picker', start_date: '2099-06-01', end_date: '2099-06-05' },
|
||||
});
|
||||
await expect(trip).toBeOK();
|
||||
const {
|
||||
trip: { id },
|
||||
} = await trip.json();
|
||||
await expect(await page.request.put(`/api/trips/${id}/addons/tours`, { data: { enabled: true } })).toBeOK();
|
||||
return id;
|
||||
}
|
||||
|
||||
async function expectInside(element: Locator, boundary: Locator) {
|
||||
await expect
|
||||
.poll(async () => {
|
||||
const target = await element.boundingBox();
|
||||
const rail = await boundary.boundingBox();
|
||||
return (
|
||||
!!target &&
|
||||
!!rail &&
|
||||
target.x >= rail.x - 1 &&
|
||||
target.y >= rail.y - 1 &&
|
||||
target.x + target.width <= rail.x + rail.width + 1 &&
|
||||
target.y + target.height <= rail.y + rail.height + 1
|
||||
);
|
||||
})
|
||||
.toBe(true);
|
||||
}
|
||||
|
||||
function editorFields(page: Page) {
|
||||
const trigger = page.getByTestId('tour-type-select');
|
||||
const scrollArea = page.getByTestId('tour-planner-editor-scroll');
|
||||
return { trigger, scrollArea, menu: page.getByRole('group', { name: 'Tour type', exact: true }) };
|
||||
}
|
||||
|
||||
test('Tour type follows and fits inside the narrow editor rail', async ({ page }) => {
|
||||
await page.setViewportSize({ width: 1024, height: 480 });
|
||||
const tripId = await createTourTrip(page);
|
||||
await page.goto(`/trips/${tripId}?tab=tour-planner`);
|
||||
await page.getByRole('button', { name: 'Plan new tour' }).click();
|
||||
await expect(page.getByTestId('tour-planner-empty-state')).toBeAttached();
|
||||
|
||||
const grip = page.locator('[data-resize="left"]');
|
||||
for (let step = 0; step < 8; step++) await grip.press('ArrowLeft');
|
||||
const { trigger, scrollArea, menu } = editorFields(page);
|
||||
await trigger.scrollIntoViewIfNeeded();
|
||||
await expectInside(trigger, scrollArea);
|
||||
await trigger.click();
|
||||
await expectInside(menu, scrollArea);
|
||||
await expect.poll(() => menu.evaluate((el) => el.scrollHeight > el.clientHeight)).toBe(true);
|
||||
|
||||
async function anchorGap() {
|
||||
return menu.evaluate((el) => {
|
||||
const anchor = document.querySelector('[data-testid="tour-type-select"]')!.getBoundingClientRect();
|
||||
const panel = el.getBoundingClientRect();
|
||||
return Math.round(Math.max(panel.top - anchor.bottom, anchor.top - panel.bottom));
|
||||
});
|
||||
}
|
||||
await expect.poll(anchorGap).toBe(4);
|
||||
const start = await scrollArea.evaluate((el) => el.scrollTop);
|
||||
await scrollArea.evaluate((el) => el.scrollBy(0, 20));
|
||||
await expect.poll(() => scrollArea.evaluate((el) => el.scrollTop)).toBeGreaterThan(start);
|
||||
await expect.poll(anchorGap).toBe(4);
|
||||
await expectInside(menu, scrollArea);
|
||||
await scrollArea.evaluate((el, top) => {
|
||||
el.scrollTop = top;
|
||||
}, start);
|
||||
await expect.poll(anchorGap).toBe(4);
|
||||
|
||||
await page.keyboard.press('Escape');
|
||||
await expect(trigger).toBeFocused();
|
||||
await expect(menu).toHaveCount(0);
|
||||
|
||||
await trigger.click();
|
||||
await scrollArea.evaluate((el) => el.scrollBy(0, 180));
|
||||
await expect(trigger).toHaveAttribute('aria-expanded', 'false');
|
||||
await expect(menu).toHaveCount(0);
|
||||
await scrollArea.evaluate((el) => {
|
||||
el.scrollTop = 0;
|
||||
});
|
||||
await expect(menu).toHaveCount(0);
|
||||
|
||||
await trigger.click();
|
||||
const ski = menu.getByTestId('tour-type-option-ski');
|
||||
await page.keyboard.press('End');
|
||||
await expect(ski).toBeInViewport();
|
||||
await expect(ski).toBeFocused();
|
||||
await page.keyboard.press('Enter');
|
||||
await expect(trigger).toContainText('Ski & winter');
|
||||
await expect(menu).toHaveCount(0);
|
||||
await page.getByRole('button', { name: 'Alpine', exact: true }).click();
|
||||
const hardest = page.getByRole('button', { name: 'Hardest runs', exact: true });
|
||||
const hardestMenu = page.getByRole('group', { name: 'Hardest runs', exact: true });
|
||||
await hardest.click();
|
||||
await expectInside(hardestMenu, scrollArea);
|
||||
await hardestMenu.getByRole('button', { name: 'Easy', exact: true }).click();
|
||||
await expect(hardest).toContainText('Easy');
|
||||
await expect(hardestMenu).toHaveCount(0);
|
||||
});
|
||||
|
||||
test('the saved hike difficulty dropdown fits above the field and keeps alpine confirmation', async ({ page }) => {
|
||||
await page.setViewportSize({ width: 1024, height: 520 });
|
||||
const tripId = await createTourTrip(page);
|
||||
const saved = await page.request.post(`/api/trips/${tripId}/tours`, {
|
||||
data: {
|
||||
name: 'Saved ridge walk',
|
||||
tour_type: 'hike',
|
||||
max_hiking_difficulty: 2,
|
||||
route_geometry: [
|
||||
[48.1, 11.1, 500],
|
||||
[48.11, 11.11, 550],
|
||||
],
|
||||
waypoints: [
|
||||
{ lat: 48.1, lng: 11.1, role: 'start', sequence: 0 },
|
||||
{ lat: 48.11, lng: 11.11, role: 'end', sequence: 1 },
|
||||
],
|
||||
},
|
||||
});
|
||||
await expect(saved).toBeOK();
|
||||
const {
|
||||
tour: { place_id },
|
||||
} = await saved.json();
|
||||
const detailUrl = `**/api/trips/${tripId}/tours/${place_id}`;
|
||||
const detailGate = Promise.withResolvers<void>();
|
||||
await page.route(
|
||||
detailUrl,
|
||||
async (route) => {
|
||||
await detailGate.promise;
|
||||
await route.continue();
|
||||
},
|
||||
{ times: 1 }
|
||||
);
|
||||
const shape = encodePolyline6([
|
||||
{ lat: 48.1, lon: 11.1 },
|
||||
{ lat: 48.11, lon: 11.11 },
|
||||
]);
|
||||
await page.route('**/api/routing/valhalla/route', (route) =>
|
||||
route.fulfill({
|
||||
json: { trip: { legs: [{ shape, summary: { length: 1.4, time: 1200 } }] } },
|
||||
})
|
||||
);
|
||||
await page.goto(`/trips/${tripId}?tab=tour-planner`);
|
||||
const detailRequested = page.waitForRequest(detailUrl);
|
||||
await page.getByRole('option', { name: /Saved ridge walk/ }).click();
|
||||
await detailRequested;
|
||||
|
||||
const { trigger, menu, scrollArea } = editorFields(page);
|
||||
try {
|
||||
await expect(trigger).toHaveCount(0);
|
||||
await expect(menu).toHaveCount(0);
|
||||
} finally {
|
||||
detailGate.resolve();
|
||||
}
|
||||
await expect(page.getByLabel('Tour name')).toHaveValue('Saved ridge walk');
|
||||
await trigger.click();
|
||||
await expectInside(menu, scrollArea);
|
||||
await page.keyboard.press('Escape');
|
||||
|
||||
const difficulty = page.getByRole('button', { name: 'Maximum trail difficulty', exact: true });
|
||||
const difficultyMenu = page.getByRole('group', { name: 'Maximum trail difficulty', exact: true });
|
||||
await difficulty.scrollIntoViewIfNeeded();
|
||||
await difficulty.click();
|
||||
await expectInside(difficultyMenu, scrollArea);
|
||||
await expect(difficultyMenu).toHaveCSS('transform-origin', /px [1-9][0-9.]*px$/);
|
||||
await page.keyboard.press('Escape');
|
||||
await expect(difficulty).toBeFocused();
|
||||
await expect(difficultyMenu).toHaveCount(0);
|
||||
await difficulty.click();
|
||||
await scrollArea.evaluate((el) => {
|
||||
el.scrollTop = 0;
|
||||
});
|
||||
await expect(difficulty).toHaveAttribute('aria-expanded', 'false');
|
||||
await expect(difficultyMenu).toHaveCount(0);
|
||||
|
||||
await difficulty.click();
|
||||
await difficultyMenu.getByRole('button', { name: 'T3: Demanding mountain hiking' }).click();
|
||||
await expect(difficulty).toContainText('T3:');
|
||||
await difficulty.click();
|
||||
await difficultyMenu.getByRole('button', { name: 'T4: Alpine hiking' }).click();
|
||||
await expect(page.getByRole('heading', { name: 'Enable alpine routing?' })).toBeVisible();
|
||||
await page.getByRole('button', { name: 'Cancel' }).click();
|
||||
await expect(difficulty).toContainText('T3:');
|
||||
|
||||
const categories = page.getByTestId('tour-poi-categories');
|
||||
await categories.click();
|
||||
await expectInside(page.getByRole('group', { name: 'What to look for', exact: true }), scrollArea);
|
||||
});
|
||||
|
||||
test('the tour editor dropdowns fit in the native tablet layout', async ({ playwright, baseURL, storageState }) => {
|
||||
const browser = await playwright.webkit.launch();
|
||||
try {
|
||||
const page = await browser.newPage({
|
||||
...devices['iPad Pro 11'],
|
||||
viewport: { width: 680, height: 620 },
|
||||
baseURL,
|
||||
storageState,
|
||||
});
|
||||
page.setDefaultTimeout(10_000);
|
||||
// The browser supplies the WebKit viewport and touch input. This flag selects the app shell.
|
||||
await page.addInitScript(() => Object.assign(window, { CapacitorCustomPlatform: { name: 'ios' } }));
|
||||
const tripId = await createTourTrip(page);
|
||||
await page.goto(`/trips/${tripId}?tab=tour-planner`);
|
||||
await page.getByRole('tab', { name: 'Plan a tour', exact: true }).tap();
|
||||
await page.getByRole('button', { name: 'Plan new tour' }).tap();
|
||||
const { trigger, menu, scrollArea } = editorFields(page);
|
||||
await trigger.tap();
|
||||
await expectInside(menu, scrollArea);
|
||||
await scrollArea.evaluate((el) => el.scrollBy(0, 160));
|
||||
await expect(trigger).toHaveAttribute('aria-expanded', 'false');
|
||||
|
||||
const difficulty = page.getByRole('button', { name: 'Maximum trail difficulty', exact: true });
|
||||
const difficultyMenu = page.getByRole('group', { name: 'Maximum trail difficulty', exact: true });
|
||||
await difficulty.tap();
|
||||
await expectInside(difficultyMenu, scrollArea);
|
||||
await difficultyMenu.getByRole('button', { name: 'T1: Hiking' }).tap();
|
||||
await expect(difficulty).toContainText('T1:');
|
||||
await expect(difficultyMenu).toHaveCount(0);
|
||||
|
||||
await trigger.tap();
|
||||
await menu.getByTestId('tour-type-option-ski').tap();
|
||||
await page.getByRole('button', { name: 'Alpine', exact: true }).tap();
|
||||
const hardest = page.getByRole('button', { name: 'Hardest runs', exact: true });
|
||||
const hardestMenu = page.getByRole('group', { name: 'Hardest runs', exact: true });
|
||||
await hardest.tap();
|
||||
await expectInside(hardestMenu, scrollArea);
|
||||
await hardestMenu.getByRole('button', { name: 'Easy', exact: true }).tap();
|
||||
await expect(hardest).toContainText('Easy');
|
||||
} finally {
|
||||
await browser.close();
|
||||
}
|
||||
});
|
||||
@@ -5,6 +5,7 @@ import { SplashScreen } from '@capacitor/splash-screen';
|
||||
import { StatusBar, Style } from '@capacitor/status-bar';
|
||||
import { PASSWORD_MIN_LENGTH, passwordProblem, passwordRuleStates } from '../../shared/src/auth/password-policy';
|
||||
import logoWhite from '../public/logo-light.svg'; // #fff wordmark, for the landscape
|
||||
import { pageUnderStatusBar } from '../src/native/appBoot';
|
||||
import { AUTH_GATE_NAMES, canSignInInApp, type AuthGate } from '../src/native/authGate';
|
||||
import { opensSoon, refundedBeforeOpening } from '../src/native/cloudOrders';
|
||||
import { fakeIapClient, getIapClient, productIdFor, type Purchase } from '../src/native/iap';
|
||||
@@ -1705,7 +1706,9 @@ function showUnreachable(server: string, cert?: ClientCertDemand, failure?: stri
|
||||
*/
|
||||
async function paintStatusBar(): Promise<void> {
|
||||
try {
|
||||
await StatusBar.setStyle({ style: Style.Dark });
|
||||
// Below the bar on an older Android WebView the page stops, and the bar
|
||||
// stands on the window's light colour instead: dark icons there.
|
||||
await StatusBar.setStyle({ style: pageUnderStatusBar() ? Style.Dark : Style.Light });
|
||||
if (wideLayout.matches) await StatusBar.hide();
|
||||
else await StatusBar.show();
|
||||
} catch {
|
||||
|
||||
@@ -204,11 +204,32 @@
|
||||
--sea: #cfe3ef;
|
||||
--text-face: 'Plus Jakarta Sans', system-ui, -apple-system, 'Segoe UI', Roboto, sans-serif;
|
||||
--display-face: 'Poppins', system-ui, -apple-system, 'Segoe UI', Roboto, sans-serif;
|
||||
/* The insets of the device, from the web view or, on iOS, from the native side. */
|
||||
--safe-top: max(env(safe-area-inset-top, 0px), var(--trek-native-safe-top, 0px));
|
||||
--safe-bottom: max(env(safe-area-inset-bottom, 0px), var(--trek-native-safe-bottom, 0px));
|
||||
--safe-start: max(env(safe-area-inset-left, 0px), var(--trek-native-safe-left, 0px));
|
||||
--safe-end: max(env(safe-area-inset-right, 0px), var(--trek-native-safe-right, 0px));
|
||||
/* The insets of the device, from the web view or from the native side. On
|
||||
* Android a web view can report env() as 0 while the page reaches under the
|
||||
* status and navigation bars; Capacitor's SystemBars writes the real insets
|
||||
* to --safe-area-inset-* instead (0 where it lays the web view out between
|
||||
* the bars). iOS measures its own (TrekBridgeViewController publishSafeArea).
|
||||
* In a browser the variables are unset: env() alone. */
|
||||
--safe-top: max(
|
||||
env(safe-area-inset-top, 0px),
|
||||
var(--safe-area-inset-top, 0px),
|
||||
var(--trek-native-safe-top, 0px)
|
||||
);
|
||||
--safe-bottom: max(
|
||||
env(safe-area-inset-bottom, 0px),
|
||||
var(--safe-area-inset-bottom, 0px),
|
||||
var(--trek-native-safe-bottom, 0px)
|
||||
);
|
||||
--safe-start: max(
|
||||
env(safe-area-inset-left, 0px),
|
||||
var(--safe-area-inset-left, 0px),
|
||||
var(--trek-native-safe-left, 0px)
|
||||
);
|
||||
--safe-end: max(
|
||||
env(safe-area-inset-right, 0px),
|
||||
var(--safe-area-inset-right, 0px),
|
||||
var(--trek-native-safe-right, 0px)
|
||||
);
|
||||
color-scheme: light;
|
||||
-webkit-text-size-adjust: 100%;
|
||||
}
|
||||
|
||||
+7
-7
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@trek/client",
|
||||
"version": "5.1.4",
|
||||
"version": "5.2.1",
|
||||
"engines": {
|
||||
"node": "^22.22.2 || ^24.15.0 || >=26.0.0"
|
||||
},
|
||||
@@ -103,7 +103,7 @@
|
||||
"@fontsource/yellowtail": "^5.3.0",
|
||||
"@maplibre/maplibre-gl-leaflet": "0.1.4",
|
||||
"@noble/hashes": "^1.8.0",
|
||||
"@simplewebauthn/browser": "^13.3.0",
|
||||
"@simplewebauthn/browser": "^14.0.0",
|
||||
"@trek/shared": "*",
|
||||
"axios": "^1.21.0",
|
||||
"dexie": "^4.4.7",
|
||||
@@ -112,13 +112,13 @@
|
||||
"iso-3166-2": "^1.0.0",
|
||||
"leaflet": "^1.9.4",
|
||||
"lucide-react": "^0.577.0",
|
||||
"mapbox-gl": "^3.35.2",
|
||||
"mapbox-gl": "3.32.0",
|
||||
"maplibre-gl": "6.19.0",
|
||||
"modern-screenshot": "4.7.0",
|
||||
"plyr": "^3.8.5",
|
||||
"react": "^19.3.1",
|
||||
"react-dom": "^19.3.1",
|
||||
"react-dropzone": "^14.4.1",
|
||||
"react-dropzone": "^20.2.1",
|
||||
"react-leaflet": "^5.0.0",
|
||||
"react-leaflet-cluster": "^4.1.3",
|
||||
"react-markdown": "^10.1.0",
|
||||
@@ -141,7 +141,7 @@
|
||||
"@testing-library/user-event": "^14.6.13",
|
||||
"@trivago/prettier-plugin-sort-imports": "^6.0.2",
|
||||
"@types/leaflet": "^1.9.22",
|
||||
"@types/node": "^25.9.8",
|
||||
"@types/node": "^26.6.11",
|
||||
"@types/react": "^19.3.0",
|
||||
"@types/react-dom": "^19.3.0",
|
||||
"@vitejs/plugin-react": "^6.2.1",
|
||||
@@ -154,7 +154,7 @@
|
||||
"eslint-plugin-react-refresh": "^0.5.8",
|
||||
"fake-indexeddb": "^6.2.7",
|
||||
"jsdom": "^29.1.1",
|
||||
"msw": "^2.15.0",
|
||||
"msw": "^3.0.8",
|
||||
"postcss": "^8.5.33",
|
||||
"prettier": "^3.10.1",
|
||||
"prettier-plugin-organize-imports": "^4.3.0",
|
||||
@@ -163,7 +163,7 @@
|
||||
"sharp": "^0.35.5",
|
||||
"tailwindcss": "^3.4.19",
|
||||
"typescript": "^6.0.3",
|
||||
"typescript-eslint": "^8.72.1",
|
||||
"typescript-eslint": "^8.73.0",
|
||||
"vite": "8.3.8",
|
||||
"vite-plugin-pwa": "^2.0.0",
|
||||
"vitest": "^4.1.12"
|
||||
|
||||
@@ -12,6 +12,16 @@
|
||||
(function () {
|
||||
try {
|
||||
var raw = localStorage.getItem('trek_appearance');
|
||||
// Inside the iOS and Android app, before anyone signed in on this server
|
||||
// from here: the page carries on the address screen's colour until the
|
||||
// sign-in screen is up (native/appBoot.ts), instead of flashing white.
|
||||
// The app's bridge is in place before this script runs.
|
||||
var w = window;
|
||||
var inApp = !!(w.androidBridge || (w.webkit && w.webkit.messageHandlers && w.webkit.messageHandlers.bridge));
|
||||
if (inApp && !raw) {
|
||||
document.documentElement.setAttribute('data-app-boot', '');
|
||||
document.documentElement.style.backgroundColor = '#fffaf5';
|
||||
}
|
||||
if (!raw) return;
|
||||
var s = JSON.parse(raw);
|
||||
if (!s || s.v !== 1) return;
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"src": {
|
||||
"@typescript-eslint/no-non-null-assertion": 367,
|
||||
"@typescript-eslint/no-non-null-assertion": 354,
|
||||
"@typescript-eslint/no-misused-promises": 820,
|
||||
"no-console": 88,
|
||||
"complexity": 216,
|
||||
@@ -8,14 +8,14 @@
|
||||
"trek/no-swallowed-catch": 126,
|
||||
"max-params": 31,
|
||||
"trek/store-without-selector": 66,
|
||||
"react-hooks/refs": 534,
|
||||
"react-hooks/refs": 533,
|
||||
"react-hooks/set-state-in-effect": 189,
|
||||
"@typescript-eslint/no-floating-promises": 162,
|
||||
"react-hooks/exhaustive-deps": 113,
|
||||
"@typescript-eslint/no-unused-vars": 117,
|
||||
"react-hooks/immutability": 28,
|
||||
"max-lines-per-function": 127,
|
||||
"react-hooks/static-components": 50,
|
||||
"react-hooks/static-components": 38,
|
||||
"react-hooks/preserve-manual-memoization": 12,
|
||||
"no-useless-assignment": 7,
|
||||
"no-empty": 19,
|
||||
|
||||
@@ -2121,7 +2121,6 @@
|
||||
"tests/unit/sync/tripSyncManager.test.ts",
|
||||
"tests/unit/tripStore.test.ts",
|
||||
"tests/unit/utils/cleanAmount.test.ts",
|
||||
"tests/unit/utils/fileDownload.test.ts",
|
||||
"tests/unit/utils/formatters.test.ts",
|
||||
"tests/unit/utils/placeFiles.test.ts",
|
||||
"tests/unit/utils/shellGuard.test.ts",
|
||||
|
||||
@@ -8,18 +8,18 @@
|
||||
"src/components/Map/MapView.tsx": 1200,
|
||||
"src/components/Map/MapViewGL.test.tsx": 2919,
|
||||
"src/components/Map/MapViewGL.tsx": 2116,
|
||||
"src/components/Planner/DayDetailPanel.test.tsx": 2333,
|
||||
"src/components/Planner/DayDetailPanel.test.tsx": 2332,
|
||||
"src/components/Planner/DayPlanSidebar.test.tsx": 5349,
|
||||
"src/components/Planner/DayPlanSidebar.tsx": 2910,
|
||||
"src/components/Planner/DayPlanSidebar.tsx": 2908,
|
||||
"src/components/Planner/PlaceFormModal.test.tsx": 2836,
|
||||
"src/components/Planner/PlaceInspector.tsx": 1128,
|
||||
"src/components/Studio/TravelElements.tsx": 1559,
|
||||
"src/components/Studio/countryShapes.ts": 2595,
|
||||
"src/index.css": 1636,
|
||||
"src/mobile/screens/admin/MAdminPluginsPanel.tsx": 1503,
|
||||
"src/pages/JourneyDetailPage.test.tsx": 4028,
|
||||
"src/pages/LoginPage.tsx": 1294,
|
||||
"src/pages/TripPlannerPage.tsx": 1128,
|
||||
"src/pages/JourneyDetailPage.test.tsx": 3886,
|
||||
"src/pages/LoginPage.tsx": 1273,
|
||||
"src/pages/TripPlannerPage.tsx": 1127,
|
||||
"src/pages/atlas/useAtlas.ts": 1207,
|
||||
"src/pages/tripPlanner/useTripPlanner.roadtrip.test.tsx": 3518,
|
||||
"src/pages/tripPlanner/useTripPlanner.test.tsx": 3267,
|
||||
|
||||
@@ -45,7 +45,7 @@
|
||||
"components/Journey/JourneyMapGL.tsx": 5,
|
||||
"components/Journey/MobileEntryView.tsx": 94,
|
||||
"components/Journey/MobileMapTimeline.tsx": 8,
|
||||
"components/Journey/PhotoLightbox.tsx": 13,
|
||||
"components/Journey/PhotoLightbox.tsx": 11,
|
||||
"components/Journey/VideoPlayer.tsx": 2,
|
||||
"components/Journey/VideoPlayerLazy.tsx": 1,
|
||||
"components/Journey/journeyMapPopup.ts": 17,
|
||||
@@ -262,7 +262,7 @@
|
||||
"mobile/screens/trip/tabs/MCollabTab.tsx": 1,
|
||||
"mobile/screens/trip/tabs/MCostsTab.tsx": 70,
|
||||
"mobile/screens/trip/tabs/MDocSyncSheet.tsx": 43,
|
||||
"mobile/screens/trip/tabs/MFileLightbox.tsx": 12,
|
||||
"mobile/screens/trip/tabs/MFileLightbox.tsx": 11,
|
||||
"mobile/screens/trip/tabs/MFileLinkSheet.tsx": 2,
|
||||
"mobile/screens/trip/tabs/MFileMenuSheet.tsx": 1,
|
||||
"mobile/screens/trip/tabs/MFileTrashSheet.tsx": 4,
|
||||
|
||||
+28
-4
@@ -1,13 +1,14 @@
|
||||
import React from 'react'
|
||||
import { render, screen, waitFor, act } from '@testing-library/react'
|
||||
import { MemoryRouter, useLocation } from 'react-router'
|
||||
import { describe, it, expect, beforeEach, vi } from 'vitest'
|
||||
import { describe, it, expect, beforeEach, onTestFinished, vi } from 'vitest'
|
||||
import { http, HttpResponse } from 'msw'
|
||||
import { server } from '../tests/helpers/msw/server'
|
||||
import { useAuthStore } from './store/authStore'
|
||||
import { useSettingsStore } from './store/settingsStore'
|
||||
import { resetAllStores } from '../tests/helpers/store'
|
||||
import { buildUser, buildSettings, buildTrip } from '../tests/helpers/factories'
|
||||
import { locationAt } from '../tests/helpers/location'
|
||||
import { offlineDb } from './db/offlineDb'
|
||||
import { SETTINGS_WAIT_MS } from './utils/startDestination'
|
||||
import App from './App'
|
||||
@@ -185,9 +186,29 @@ describe('RootRedirect — startup destination', () => {
|
||||
seedAuth({ isAuthenticated: true, user: buildUser() })
|
||||
useSettingsStore.setState({ isLoaded: false })
|
||||
stubActiveTrip({ id: 42, title: 'Japan' })
|
||||
// App asks for the settings on its own as soon as the user is signed in.
|
||||
// Held until the redirect is decided, or whichever answer lands first wins
|
||||
// and the test proves nothing about the mirror; released here, so it cannot
|
||||
// land in the next test either.
|
||||
let releaseSettings = () => {}
|
||||
const settingsHeld = new Promise<void>((resolve) => { releaseSettings = resolve })
|
||||
onTestFinished(() => releaseSettings())
|
||||
server.use(
|
||||
http.get('/api/settings', async () => {
|
||||
await settingsHeld
|
||||
return HttpResponse.json({
|
||||
settings: buildSettings({ start_page: 'active_trip', start_trip_tab: 'finanzplan' }),
|
||||
})
|
||||
}),
|
||||
)
|
||||
|
||||
renderApp('/')
|
||||
await waitFor(() => expect(screen.getByText('TripPlanner')).toBeInTheDocument())
|
||||
expect(currentPath()).toBe('/trips/42?tab=finanzplan')
|
||||
expect(useSettingsStore.getState().isLoaded).toBe(false)
|
||||
|
||||
releaseSettings()
|
||||
await waitFor(() => expect(useSettingsStore.getState().isLoaded).toBe(true))
|
||||
})
|
||||
})
|
||||
|
||||
@@ -532,7 +553,7 @@ describe('Version cache-busting', () => {
|
||||
const reload = vi.fn()
|
||||
Object.defineProperty(window, 'location', {
|
||||
writable: true,
|
||||
value: { ...window.location, reload },
|
||||
value: locationAt('/', { reload }),
|
||||
})
|
||||
|
||||
server.use(
|
||||
@@ -587,7 +608,7 @@ describe('Version cache-busting', () => {
|
||||
// and try to update.
|
||||
localStorage.setItem('trek_app_version', '2.9.9')
|
||||
const reload = vi.fn()
|
||||
Object.defineProperty(window, 'location', { writable: true, value: { ...window.location, reload } })
|
||||
Object.defineProperty(window, 'location', { writable: true, value: locationAt('/', { reload }) })
|
||||
|
||||
server.use(
|
||||
http.get('/api/auth/app-config', () =>
|
||||
@@ -609,7 +630,7 @@ describe('Version cache-busting', () => {
|
||||
// failure neither deletes anything nor reloads into the old worker's shell.
|
||||
localStorage.setItem('trek_app_version', '2.9.9')
|
||||
const reload = vi.fn()
|
||||
Object.defineProperty(window, 'location', { writable: true, value: { ...window.location, reload } })
|
||||
Object.defineProperty(window, 'location', { writable: true, value: locationAt('/', { reload }) })
|
||||
const cachesDelete = vi.fn().mockResolvedValue(true)
|
||||
const unregister = vi.fn().mockResolvedValue(true)
|
||||
vi.stubGlobal('caches', { keys: vi.fn().mockResolvedValue(['workbox-precache-v2', 'map-tiles']), delete: cachesDelete })
|
||||
@@ -685,6 +706,9 @@ describe('RootRedirect — preference not mirrored on this device', () => {
|
||||
vi.useFakeTimers({ shouldAdvanceTime: true })
|
||||
seedAuth({ isAuthenticated: true, user: buildUser() })
|
||||
useSettingsStore.setState({ isLoaded: false })
|
||||
// No backend: the settings never arrive, so only the timeout can decide.
|
||||
// Answered, they would open the dashboard on their own and hide the wait.
|
||||
server.use(http.get('/api/settings', () => HttpResponse.error()))
|
||||
|
||||
renderApp('/')
|
||||
expect(screen.queryByText('Dashboard')).not.toBeInTheDocument()
|
||||
|
||||
+12
-1
@@ -1,4 +1,4 @@
|
||||
import React, { useEffect, useState, useRef, ReactNode, Suspense } from 'react'
|
||||
import React, { useEffect, useLayoutEffect, useState, useRef, ReactNode, Suspense } from 'react'
|
||||
import { Routes, Route, Navigate, useLocation, useNavigationType } from 'react-router'
|
||||
import { useAuthStore } from './store/authStore'
|
||||
import { useSettingsStore } from './store/settingsStore'
|
||||
@@ -17,6 +17,8 @@ import BackgroundTasksWidget from './components/BackgroundTasks/BackgroundTasksW
|
||||
import MobileShell from './mobile/MobileShell'
|
||||
import MRouteFallback from './mobile/components/MRouteFallback'
|
||||
import ErrorBoundary from './components/shared/ErrorBoundary'
|
||||
import AppBootScreen from './components/shared/AppBootScreen'
|
||||
import { endAppBoot, isAppBoot } from './native/appBoot'
|
||||
import { lazyWithRetry } from './utils/lazyWithRetry'
|
||||
import { reconcileAppVersion } from './utils/versionHandover'
|
||||
import { useServerVersionStore } from './store/serverVersionStore'
|
||||
@@ -113,6 +115,7 @@ function ProtectedRoute({ children, adminRequired = false, addonId }: ProtectedR
|
||||
const isPhone = useIsPhone()
|
||||
|
||||
if (isLoading) {
|
||||
if (isAppBoot()) return <AppBootScreen />
|
||||
return (
|
||||
<div className="min-h-screen flex items-center justify-center bg-slate-50">
|
||||
<div className="flex flex-col items-center gap-3">
|
||||
@@ -286,6 +289,7 @@ function RootRedirect() {
|
||||
}, [isLoading, isAuthenticated, settingsLoaded, settingsGaveUp, settings, target])
|
||||
|
||||
if (isLoading || (isAuthenticated && !target)) {
|
||||
if (isAppBoot()) return <AppBootScreen />
|
||||
return (
|
||||
<div className="min-h-screen flex items-center justify-center bg-slate-50">
|
||||
<div className="w-10 h-10 border-4 border-slate-200 border-t-slate-900 rounded-full animate-spin"></div>
|
||||
@@ -306,6 +310,7 @@ function RouteFallback() {
|
||||
// on a phone the desktop spinner on bg-surface would be a foreign white sheet
|
||||
// in front of the mobile screen.
|
||||
const isPhone = useIsPhone()
|
||||
if (isAppBoot()) return <AppBootScreen />
|
||||
if (isPhone) return <MRouteFallback />
|
||||
return (
|
||||
<div className="min-h-screen flex items-center justify-center bg-surface">
|
||||
@@ -398,6 +403,12 @@ export default function App() {
|
||||
const location = useLocation()
|
||||
const isSharedPage = location.pathname.startsWith('/shared/')
|
||||
|
||||
// Inside the app: the handover from its address screen ends once a signed-in
|
||||
// screen is up, before it paints, so it can rise in (native/appBoot.ts).
|
||||
useLayoutEffect(() => {
|
||||
if (isAuthenticated && location.pathname !== '/' && location.pathname !== '/login') endAppBoot()
|
||||
}, [isAuthenticated, location.pathname])
|
||||
|
||||
useEffect(() => {
|
||||
const run = () =>
|
||||
applyAppearance({
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
// FE-ADMIN-DUS-001 to FE-ADMIN-DUS-031
|
||||
import { render, screen, waitFor, within, fireEvent } from '../../../tests/helpers/render';
|
||||
import userEvent from '@testing-library/user-event';
|
||||
import { http, HttpResponse } from 'msw';
|
||||
import { delay, http, HttpResponse } from 'msw';
|
||||
import { server } from '../../../tests/helpers/msw/server';
|
||||
import { resetAllStores, seedStore } from '../../../tests/helpers/store';
|
||||
import { buildAdmin } from '../../../tests/helpers/factories';
|
||||
@@ -341,12 +341,43 @@ describe('DefaultUserSettingsTab', () => {
|
||||
expect(input).toHaveValue('pk.old');
|
||||
await user.clear(input);
|
||||
await user.type(input, 'pk.new');
|
||||
fireEvent.blur(input);
|
||||
// Leave the field for real: fireEvent.blur keeps the focus on it, so the reset click
|
||||
// would blur it a second time and race that save against the reset request
|
||||
await user.tab();
|
||||
expect(input).not.toHaveFocus();
|
||||
await waitFor(() => expect(puts).toEqual([{ mapbox_access_token: 'pk.new' }]));
|
||||
|
||||
// Clicking the reset link also blurs the field again, so only the last PUT is checked
|
||||
await user.click(resetLink('Shared Mapbox token'));
|
||||
await waitFor(() => expect(puts[puts.length - 1]).toEqual({ mapbox_access_token: null }));
|
||||
await waitFor(() => expect(puts).toEqual([{ mapbox_access_token: 'pk.new' }, { mapbox_access_token: null }]));
|
||||
await waitFor(() => expect(screen.getByPlaceholderText('pk.eyJ…')).toHaveValue(''));
|
||||
});
|
||||
|
||||
it('FE-ADMIN-DUS-032: a reset clicked while the save of the field is still out is the one that stays', async () => {
|
||||
const user = userEvent.setup();
|
||||
const { state } = stubDefaults({ map_provider: 'mapbox-gl', mapbox_access_token: 'pk.old' });
|
||||
// The save is the slower request: sent at once, the reset would overtake it.
|
||||
const done: string[] = [];
|
||||
server.use(
|
||||
http.put('/api/admin/default-user-settings', async ({ request }) => {
|
||||
const body = await request.json() as Record<string, unknown>;
|
||||
if (body.mapbox_access_token !== null) await delay(100);
|
||||
if (body.mapbox_access_token === null) delete state.mapbox_access_token;
|
||||
else state.mapbox_access_token = body.mapbox_access_token;
|
||||
done.push(body.mapbox_access_token === null ? 'reset' : 'save');
|
||||
return HttpResponse.json({ ...state });
|
||||
}),
|
||||
);
|
||||
render(<DefaultUserSettingsTab />);
|
||||
await screen.findByText('Shared Mapbox token');
|
||||
|
||||
const input = screen.getByPlaceholderText('pk.eyJ…');
|
||||
await user.clear(input);
|
||||
await user.type(input, 'pk.new');
|
||||
// The click leaves the field, which saves it, and resets it right after.
|
||||
await user.click(resetLink('Shared Mapbox token'));
|
||||
|
||||
await waitFor(() => expect(done).toEqual(['save', 'reset']));
|
||||
expect(state.mapbox_access_token).toBeUndefined();
|
||||
await waitFor(() => expect(screen.getByPlaceholderText('pk.eyJ…')).toHaveValue(''));
|
||||
});
|
||||
|
||||
@@ -449,12 +480,14 @@ describe('DefaultUserSettingsTab', () => {
|
||||
expect(input).toHaveValue('ck.old');
|
||||
await user.clear(input);
|
||||
await user.type(input, 'ck.new');
|
||||
fireEvent.blur(input);
|
||||
// Leave the field for real: fireEvent.blur keeps the focus on it, so the reset click
|
||||
// would blur it a second time and race that save against the reset request
|
||||
await user.tab();
|
||||
expect(input).not.toHaveFocus();
|
||||
await waitFor(() => expect(puts).toEqual([{ carto_api_key: 'ck.new' }]));
|
||||
|
||||
// Clicking the reset link also blurs the field again, so only the last PUT is checked
|
||||
await user.click(resetLink('Shared CARTO key'));
|
||||
await waitFor(() => expect(puts[puts.length - 1]).toEqual({ carto_api_key: null }));
|
||||
await waitFor(() => expect(puts).toEqual([{ carto_api_key: 'ck.new' }, { carto_api_key: null }]));
|
||||
await waitFor(() => expect(cartoInput()).toHaveValue(''));
|
||||
});
|
||||
|
||||
|
||||
@@ -11,6 +11,39 @@ import DevNotificationsPanel from './DevNotificationsPanel';
|
||||
|
||||
const ADMIN_USER = buildUser({ id: 1, username: 'testadmin', role: 'admin' });
|
||||
|
||||
/**
|
||||
* Renders the panel and waits until both lookups (trips and users) have landed, so a test
|
||||
* acts on the settled panel and no lookup answers after it has ended.
|
||||
*/
|
||||
async function renderSettled() {
|
||||
render(<><ToastContainer /><DevNotificationsPanel /></>);
|
||||
await screen.findByText('Trip-Scoped Events');
|
||||
await screen.findByText('User-Scoped Events');
|
||||
}
|
||||
|
||||
const LOOKUPS = ['/api/admin/users', '/api/trips'];
|
||||
|
||||
/**
|
||||
* Records the GET requests to `paths` that have been answered, for the tests whose lookups
|
||||
* come back empty or failed and so change nothing on screen to wait for. Call before render;
|
||||
* the returned function waits until exactly `paths` (a path once per expected request) ended.
|
||||
*/
|
||||
function trackRequests(paths: string[] = LOOKUPS) {
|
||||
const answered: string[] = [];
|
||||
const onEnd = ({ request }: { request: Request }) => {
|
||||
const { pathname } = new URL(request.url);
|
||||
if (request.method === 'GET' && paths.includes(pathname)) answered.push(pathname);
|
||||
};
|
||||
server.events.on('request:end', onEnd);
|
||||
return async () => {
|
||||
try {
|
||||
await waitFor(() => expect([...answered].sort()).toEqual([...paths].sort()));
|
||||
} finally {
|
||||
server.events.removeListener('request:end', onEnd);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
resetAllStores();
|
||||
seedStore(useAuthStore, { user: ADMIN_USER, isAuthenticated: true });
|
||||
@@ -21,9 +54,12 @@ afterEach(() => {
|
||||
});
|
||||
|
||||
describe('DevNotificationsPanel', () => {
|
||||
it('FE-ADMIN-DEVNOTIF-001: "DEV ONLY" badge is always visible', () => {
|
||||
it('FE-ADMIN-DEVNOTIF-001: "DEV ONLY" badge is always visible', async () => {
|
||||
render(<><ToastContainer /><DevNotificationsPanel /></>);
|
||||
expect(screen.getByText('DEV ONLY')).toBeInTheDocument();
|
||||
// Let the lookups the panel started land here, not in the next test
|
||||
await screen.findByText('Trip-Scoped Events');
|
||||
await screen.findByText('User-Scoped Events');
|
||||
});
|
||||
|
||||
it('FE-ADMIN-DEVNOTIF-002: four section titles render after data loads', async () => {
|
||||
@@ -36,8 +72,7 @@ describe('DevNotificationsPanel', () => {
|
||||
});
|
||||
|
||||
it('FE-ADMIN-DEVNOTIF-003: trip selector populated from API', async () => {
|
||||
render(<><ToastContainer /><DevNotificationsPanel /></>);
|
||||
await screen.findByText('Trip-Scoped Events');
|
||||
await renderSettled();
|
||||
const [tripSelect] = screen.getAllByRole('combobox');
|
||||
const options = Array.from(tripSelect.querySelectorAll('option'));
|
||||
const labels = options.map(o => o.textContent);
|
||||
@@ -46,8 +81,7 @@ describe('DevNotificationsPanel', () => {
|
||||
});
|
||||
|
||||
it('FE-ADMIN-DEVNOTIF-004: user selector populated from API', async () => {
|
||||
render(<><ToastContainer /><DevNotificationsPanel /></>);
|
||||
await screen.findByText('User-Scoped Events');
|
||||
await renderSettled();
|
||||
const selects = screen.getAllByRole('combobox');
|
||||
// Second combobox is the user selector (first is trip selector)
|
||||
const userSelect = selects[1];
|
||||
@@ -66,8 +100,7 @@ describe('DevNotificationsPanel', () => {
|
||||
}),
|
||||
);
|
||||
const user = userEvent.setup();
|
||||
render(<><ToastContainer /><DevNotificationsPanel /></>);
|
||||
await screen.findByText('Type Testing');
|
||||
await renderSettled();
|
||||
await user.click(screen.getByText('Simple → Me').closest('button')!);
|
||||
await waitFor(() => expect(capturedBody).toBeDefined());
|
||||
expect(capturedBody).toMatchObject({
|
||||
@@ -75,6 +108,8 @@ describe('DevNotificationsPanel', () => {
|
||||
scope: 'user',
|
||||
targetId: ADMIN_USER.id,
|
||||
});
|
||||
// The send settles inside this test, so its toast cannot land in the next one
|
||||
await screen.findByText('Sent: simple-me');
|
||||
});
|
||||
|
||||
it('FE-ADMIN-DEVNOTIF-006: success toast shown after fire', async () => {
|
||||
@@ -84,30 +119,34 @@ describe('DevNotificationsPanel', () => {
|
||||
),
|
||||
);
|
||||
const user = userEvent.setup();
|
||||
render(<><ToastContainer /><DevNotificationsPanel /></>);
|
||||
await screen.findByText('Type Testing');
|
||||
await renderSettled();
|
||||
await user.click(screen.getByText('Simple → Me').closest('button')!);
|
||||
expect(await screen.findByText('Sent: simple-me')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-ADMIN-DEVNOTIF-007: all buttons disabled while a send is in-flight', async () => {
|
||||
// The send is held open until the assertion ran, then released, so it settles in this test
|
||||
let release!: () => void;
|
||||
const gate = new Promise<void>(resolve => { release = resolve; });
|
||||
server.use(
|
||||
http.post('/api/admin/dev/test-notification', async () => {
|
||||
await new Promise(() => {}); // never resolves — simulates in-flight
|
||||
await gate;
|
||||
return HttpResponse.json({ ok: true });
|
||||
}),
|
||||
);
|
||||
const user = userEvent.setup();
|
||||
render(<><ToastContainer /><DevNotificationsPanel /></>);
|
||||
await screen.findByText('Type Testing');
|
||||
await renderSettled();
|
||||
|
||||
// The request handler never resolves, so sending stays true after the click settles
|
||||
// The request handler is held, so sending stays true after the click settles
|
||||
await user.click(screen.getByText('Simple → Me').closest('button')!);
|
||||
|
||||
await waitFor(() => {
|
||||
const buttons = screen.getAllByRole('button');
|
||||
buttons.forEach(btn => expect(btn).toBeDisabled());
|
||||
});
|
||||
|
||||
release();
|
||||
await screen.findByText('Sent: simple-me');
|
||||
});
|
||||
|
||||
it('FE-ADMIN-DEVNOTIF-008: the server error field is what the toast shows', async () => {
|
||||
@@ -117,8 +156,7 @@ describe('DevNotificationsPanel', () => {
|
||||
),
|
||||
);
|
||||
const user = userEvent.setup();
|
||||
render(<><ToastContainer /><DevNotificationsPanel /></>);
|
||||
await screen.findByText('Type Testing');
|
||||
await renderSettled();
|
||||
await user.click(screen.getByText('Simple → Me').closest('button')!);
|
||||
expect(await screen.findByText('No channel configured')).toBeInTheDocument();
|
||||
});
|
||||
@@ -130,8 +168,7 @@ describe('DevNotificationsPanel', () => {
|
||||
),
|
||||
);
|
||||
const user = userEvent.setup();
|
||||
render(<><ToastContainer /><DevNotificationsPanel /></>);
|
||||
await screen.findByText('Type Testing');
|
||||
await renderSettled();
|
||||
await user.click(screen.getByText('Simple → Me').closest('button')!);
|
||||
expect(await screen.findByText('Failed')).toBeInTheDocument();
|
||||
});
|
||||
@@ -145,8 +182,7 @@ describe('DevNotificationsPanel', () => {
|
||||
}),
|
||||
);
|
||||
const user = userEvent.setup();
|
||||
render(<><ToastContainer /><DevNotificationsPanel /></>);
|
||||
await screen.findByText('Trip-Scoped Events');
|
||||
await renderSettled();
|
||||
|
||||
const [tripSelect] = screen.getAllByRole('combobox');
|
||||
const tokyoOption = Array.from(tripSelect.querySelectorAll('option')).find(
|
||||
@@ -159,15 +195,19 @@ describe('DevNotificationsPanel', () => {
|
||||
|
||||
await waitFor(() => expect(capturedBody).toBeDefined());
|
||||
expect(capturedBody!.targetId).toBe(tokyoId);
|
||||
// The send settles inside this test, so its toast cannot land in the next one
|
||||
await screen.findByText('Sent: booking_change');
|
||||
});
|
||||
|
||||
it('FE-ADMIN-DEVNOTIF-010: Trip-Scoped section absent when no trips', async () => {
|
||||
server.use(
|
||||
http.get('/api/trips', () => HttpResponse.json({ trips: [] })),
|
||||
);
|
||||
const lookupsAnswered = trackRequests();
|
||||
render(<><ToastContainer /><DevNotificationsPanel /></>);
|
||||
// Wait for user data to confirm async effects have settled
|
||||
await screen.findByText('User-Scoped Events');
|
||||
await lookupsAnswered();
|
||||
expect(screen.queryByText('Trip-Scoped Events')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
@@ -180,8 +220,7 @@ describe('DevNotificationsPanel', () => {
|
||||
}),
|
||||
);
|
||||
const user = userEvent.setup();
|
||||
render(<><ToastContainer /><DevNotificationsPanel /></>);
|
||||
await screen.findByText('Type Testing');
|
||||
await renderSettled();
|
||||
|
||||
await user.click(screen.getByText('Boolean → Me').closest('button')!);
|
||||
await screen.findByText('Sent: boolean-me');
|
||||
@@ -216,8 +255,7 @@ describe('DevNotificationsPanel', () => {
|
||||
}),
|
||||
);
|
||||
const user = userEvent.setup();
|
||||
render(<><ToastContainer /><DevNotificationsPanel /></>);
|
||||
await screen.findByText('Trip-Scoped Events');
|
||||
await renderSettled();
|
||||
|
||||
const [tripSelect] = screen.getAllByRole('combobox');
|
||||
const tripId = Number((tripSelect as HTMLSelectElement).value);
|
||||
@@ -247,8 +285,7 @@ describe('DevNotificationsPanel', () => {
|
||||
}),
|
||||
);
|
||||
const user = userEvent.setup();
|
||||
render(<><ToastContainer /><DevNotificationsPanel /></>);
|
||||
await screen.findByText('User-Scoped Events');
|
||||
await renderSettled();
|
||||
|
||||
const userSelect = screen.getAllByRole('combobox')[1] as HTMLSelectElement;
|
||||
const aliceOption = Array.from(userSelect.querySelectorAll('option')).find(
|
||||
@@ -278,9 +315,11 @@ describe('DevNotificationsPanel', () => {
|
||||
|
||||
it('FE-ADMIN-DEVNOTIF-014: the User-Scoped section is hidden when no users come back', async () => {
|
||||
server.use(http.get('/api/admin/users', () => HttpResponse.json({ users: [] })));
|
||||
const lookupsAnswered = trackRequests();
|
||||
render(<><ToastContainer /><DevNotificationsPanel /></>);
|
||||
|
||||
await screen.findByText('Trip-Scoped Events');
|
||||
await lookupsAnswered();
|
||||
expect(screen.queryByText('User-Scoped Events')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
@@ -288,22 +327,38 @@ describe('DevNotificationsPanel', () => {
|
||||
server.use(
|
||||
http.get('/api/trips', () => HttpResponse.error()),
|
||||
http.get('/api/admin/users', () => HttpResponse.error()),
|
||||
// A network error makes the API client probe /api/health before it rejects; the server
|
||||
// is down here, so the probe fails too instead of going out to the real network
|
||||
http.get('/api/health', () => HttpResponse.error()),
|
||||
);
|
||||
const lookupsAnswered = trackRequests([...LOOKUPS, '/api/health', '/api/health']);
|
||||
render(<><ToastContainer /><DevNotificationsPanel /></>);
|
||||
|
||||
expect(await screen.findByText('Type Testing')).toBeInTheDocument();
|
||||
await lookupsAnswered();
|
||||
await waitFor(() => expect(screen.queryByText('Trip-Scoped Events')).not.toBeInTheDocument());
|
||||
expect(screen.queryByText('User-Scoped Events')).not.toBeInTheDocument();
|
||||
expect(screen.getByText('Admin-Scoped Events')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-ADMIN-DEVNOTIF-016: a trigger takes its hover background from CSS, not inline styles', async () => {
|
||||
render(<><ToastContainer /><DevNotificationsPanel /></>);
|
||||
await screen.findByText('Type Testing');
|
||||
await renderSettled();
|
||||
|
||||
const btn = screen.getByText('Simple → Me').closest('button')!;
|
||||
fireEvent.mouseEnter(btn);
|
||||
expect(btn.style.background).toBe('');
|
||||
expect(btn.className).toContain('hover:bg-surface-secondary');
|
||||
});
|
||||
|
||||
it('FE-ADMIN-DEVNOTIF-017: a send button stays the same element while the panel updates around it', async () => {
|
||||
render(<><ToastContainer /><DevNotificationsPanel /></>);
|
||||
const btn = screen.getByRole('button', { name: /Simple → Me/ });
|
||||
|
||||
// The lookups answer and re-render the panel.
|
||||
await screen.findByText('Trip-Scoped Events');
|
||||
await screen.findByText('User-Scoped Events');
|
||||
|
||||
expect(btn.isConnected).toBe(true);
|
||||
expect(screen.getByRole('button', { name: /Simple → Me/ })).toBe(btn);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -25,20 +25,17 @@ function ButtonGrid({ children }: { children: React.ReactNode }): React.ReactEle
|
||||
return <div className="grid grid-cols-1 gap-2 sm:grid-cols-2">{children}</div>
|
||||
}
|
||||
|
||||
export default function DevNotificationsPanel(): React.ReactElement {
|
||||
const ids = useId()
|
||||
const {
|
||||
sending, trips, selectedTripId, setSelectedTripId, users, selectedUserId, setSelectedUserId,
|
||||
tripInviteId, vacayInviteId, send,
|
||||
} = useDevNotifications()
|
||||
|
||||
// ── Helpers ──────────────────────────────────────────────────────────────
|
||||
|
||||
const Btn = ({
|
||||
id, label, sub, icon: Icon, onClick,
|
||||
}: {
|
||||
id: string; label: string; sub: string; icon: React.ElementType; onClick: () => void
|
||||
}) => (
|
||||
/**
|
||||
* One send button. Declared here, not inside the panel: a component made during
|
||||
* render is a new type on every render, so React would remount every button on
|
||||
* each state change and a click could land on one that is already gone.
|
||||
*/
|
||||
function Btn({
|
||||
id, label, sub, icon: Icon, onClick, sending,
|
||||
}: {
|
||||
id: string; label: string; sub: string; icon: React.ElementType; onClick: () => void; sending: string | null
|
||||
}): React.ReactElement {
|
||||
return (
|
||||
<button type="button"
|
||||
onClick={onClick}
|
||||
disabled={sending !== null}
|
||||
@@ -54,6 +51,14 @@ export default function DevNotificationsPanel(): React.ReactElement {
|
||||
{sending === id && <Loader2 size={15} className="flex-none animate-spin text-content-faint" />}
|
||||
</button>
|
||||
)
|
||||
}
|
||||
|
||||
export default function DevNotificationsPanel(): React.ReactElement {
|
||||
const ids = useId()
|
||||
const {
|
||||
sending, trips, selectedTripId, setSelectedTripId, users, selectedUserId, setSelectedUserId,
|
||||
tripInviteId, vacayInviteId, send,
|
||||
} = useDevNotifications()
|
||||
|
||||
return (
|
||||
<div>
|
||||
@@ -66,16 +71,16 @@ export default function DevNotificationsPanel(): React.ReactElement {
|
||||
badge={<StatusPill tone="warning">DEV ONLY</StatusPill>}
|
||||
>
|
||||
<ButtonGrid>
|
||||
<Btn id="simple-me" label="Simple → Me" sub="test_simple · user" icon={Bell}
|
||||
<Btn sending={sending} id="simple-me" label="Simple → Me" sub="test_simple · user" icon={Bell}
|
||||
onClick={send.simpleMe}
|
||||
/>
|
||||
<Btn id="boolean-me" label="Boolean → Me" sub="test_boolean · user" icon={CheckCircle}
|
||||
<Btn sending={sending} id="boolean-me" label="Boolean → Me" sub="test_boolean · user" icon={CheckCircle}
|
||||
onClick={send.booleanMe}
|
||||
/>
|
||||
<Btn id="navigate-me" label="Navigate → Me" sub="test_navigate · user" icon={Navigation}
|
||||
<Btn sending={sending} id="navigate-me" label="Navigate → Me" sub="test_navigate · user" icon={Navigation}
|
||||
onClick={send.navigateMe}
|
||||
/>
|
||||
<Btn id="simple-admins" label="Simple → All Admins" sub="test_simple · admin" icon={Zap}
|
||||
<Btn sending={sending} id="simple-admins" label="Simple → All Admins" sub="test_simple · admin" icon={Zap}
|
||||
onClick={send.simpleAdmins}
|
||||
/>
|
||||
</ButtonGrid>
|
||||
@@ -94,19 +99,19 @@ export default function DevNotificationsPanel(): React.ReactElement {
|
||||
</SelectBox>
|
||||
</EditorField>
|
||||
<ButtonGrid>
|
||||
<Btn id="booking_change" label="booking_change" sub="navigate · trip" icon={Calendar}
|
||||
<Btn sending={sending} id="booking_change" label="booking_change" sub="navigate · trip" icon={Calendar}
|
||||
onClick={send.bookingChange}
|
||||
/>
|
||||
<Btn id="trip_reminder" label="trip_reminder" sub="navigate · trip" icon={Clock}
|
||||
<Btn sending={sending} id="trip_reminder" label="trip_reminder" sub="navigate · trip" icon={Clock}
|
||||
onClick={send.tripReminder}
|
||||
/>
|
||||
<Btn id="photos_shared" label="photos_shared" sub="navigate · trip" icon={Image}
|
||||
<Btn sending={sending} id="photos_shared" label="photos_shared" sub="navigate · trip" icon={Image}
|
||||
onClick={send.photosShared}
|
||||
/>
|
||||
<Btn id="collab_message" label="collab_message" sub="navigate · trip" icon={MessageSquare}
|
||||
<Btn sending={sending} id="collab_message" label="collab_message" sub="navigate · trip" icon={MessageSquare}
|
||||
onClick={send.collabMessage}
|
||||
/>
|
||||
<Btn id="packing_tagged" label="packing_tagged" sub="navigate · trip" icon={Tag}
|
||||
<Btn sending={sending} id="packing_tagged" label="packing_tagged" sub="navigate · trip" icon={Tag}
|
||||
onClick={send.packingTagged}
|
||||
/>
|
||||
</ButtonGrid>
|
||||
@@ -127,6 +132,7 @@ export default function DevNotificationsPanel(): React.ReactElement {
|
||||
</EditorField>
|
||||
<ButtonGrid>
|
||||
<Btn
|
||||
sending={sending}
|
||||
id={tripInviteId}
|
||||
label="trip_invite"
|
||||
sub="navigate · user"
|
||||
@@ -134,6 +140,7 @@ export default function DevNotificationsPanel(): React.ReactElement {
|
||||
onClick={send.tripInvite}
|
||||
/>
|
||||
<Btn
|
||||
sending={sending}
|
||||
id={vacayInviteId}
|
||||
label="vacay_invite"
|
||||
sub="navigate · user"
|
||||
@@ -147,7 +154,7 @@ export default function DevNotificationsPanel(): React.ReactElement {
|
||||
{/* ── Admin-Scoped Events ──────────────────────────────────────────── */}
|
||||
<SettingsCard icon={ShieldCheck} title="Admin-Scoped Events" hint="Fires to all admin users.">
|
||||
<ButtonGrid>
|
||||
<Btn id="version_available" label="version_available" sub="navigate · admin" icon={Download}
|
||||
<Btn sending={sending} id="version_available" label="version_available" sub="navigate · admin" icon={Download}
|
||||
onClick={send.versionAvailable}
|
||||
/>
|
||||
</ButtonGrid>
|
||||
|
||||
@@ -137,19 +137,25 @@ describe('useDefaultUserSettings', () => {
|
||||
|
||||
act(() => result.current.pickTilePreset(''));
|
||||
act(() => result.current.pickStylePreset(''));
|
||||
// Writes go out in order, a microtask later: let any that was queued start first.
|
||||
await act(async () => {});
|
||||
expect(update).not.toHaveBeenCalled();
|
||||
|
||||
act(() => result.current.pickTilePreset('https://tile.openstreetmap.de/{z}/{x}/{y}.png'));
|
||||
expect(result.current.mapTileUrl).toBe('https://tile.openstreetmap.de/{z}/{x}/{y}.png');
|
||||
expect(update).toHaveBeenLastCalledWith({ map_tile_url: 'https://tile.openstreetmap.de/{z}/{x}/{y}.png' });
|
||||
await waitFor(() =>
|
||||
expect(update).toHaveBeenLastCalledWith({ map_tile_url: 'https://tile.openstreetmap.de/{z}/{x}/{y}.png' })
|
||||
);
|
||||
|
||||
act(() => result.current.pickStylePreset('https://tiles.openfreemap.org/styles/positron'));
|
||||
expect(update).toHaveBeenLastCalledWith({ maplibre_style: 'https://tiles.openfreemap.org/styles/positron' });
|
||||
await waitFor(() =>
|
||||
expect(update).toHaveBeenLastCalledWith({ maplibre_style: 'https://tiles.openfreemap.org/styles/positron' })
|
||||
);
|
||||
|
||||
act(() => result.current.setMapboxStyle('mapbox://styles/not-for-maplibre'));
|
||||
act(() => result.current.commitStyle());
|
||||
expect(result.current.mapboxStyle).toBe(OPENFREEMAP_DEFAULT_STYLE);
|
||||
expect(update).toHaveBeenLastCalledWith({ maplibre_style: OPENFREEMAP_DEFAULT_STYLE });
|
||||
await waitFor(() => expect(update).toHaveBeenLastCalledWith({ maplibre_style: OPENFREEMAP_DEFAULT_STYLE }));
|
||||
await waitFor(() => expect(toast.success).toHaveBeenCalledTimes(3));
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
|
||||
import { adminApi } from '../../api/client';
|
||||
import { useWritesInOrder } from '../../hooks/useWritesInOrder';
|
||||
import { useTranslation } from '../../i18n';
|
||||
import { useAuthStore } from '../../store/authStore';
|
||||
import { useSettingsStore } from '../../store/settingsStore';
|
||||
@@ -87,32 +88,38 @@ export function useDefaultUserSettings({ errorMessage, previewCreatedAt }: Defau
|
||||
.catch(() => setLoaded(true));
|
||||
}, []);
|
||||
|
||||
const save = async (patch: Partial<Defaults>) => {
|
||||
try {
|
||||
const updated = await adminApi.updateDefaultUserSettings(patch as Record<string, unknown>);
|
||||
setDefaults(updated);
|
||||
toast.success(t('admin.defaultSettings.saved'));
|
||||
} catch (err: unknown) {
|
||||
toast.error(errorMessage(err, t('common.error')));
|
||||
}
|
||||
};
|
||||
// A field's save on blur and the reset clicked right after it reach the server in
|
||||
// that order, or the save landing last would store the old value again.
|
||||
const inOrder = useWritesInOrder();
|
||||
|
||||
const reset = async (key: keyof Defaults) => {
|
||||
try {
|
||||
const updated = await adminApi.updateDefaultUserSettings({ [key]: null });
|
||||
setDefaults(updated);
|
||||
if (key === 'map_tile_url') setMapTileUrl('');
|
||||
if (key === 'mapbox_access_token') setMapboxToken('');
|
||||
if (key === 'carto_api_key') setCartoKey('');
|
||||
if (key === 'mapbox_style' || key === 'maplibre_style') {
|
||||
const provider = normalizeProvider(defaults.map_provider);
|
||||
setMapboxStyle(provider === 'leaflet' ? '' : defaultStyleForProvider(provider));
|
||||
const save = (patch: Partial<Defaults>) =>
|
||||
inOrder(async () => {
|
||||
try {
|
||||
const updated = await adminApi.updateDefaultUserSettings(patch as Record<string, unknown>);
|
||||
setDefaults(updated);
|
||||
toast.success(t('admin.defaultSettings.saved'));
|
||||
} catch (err: unknown) {
|
||||
toast.error(errorMessage(err, t('common.error')));
|
||||
}
|
||||
toast.success(t('admin.defaultSettings.reset'));
|
||||
} catch (err: unknown) {
|
||||
toast.error(errorMessage(err, t('common.error')));
|
||||
}
|
||||
};
|
||||
});
|
||||
|
||||
const reset = (key: keyof Defaults) =>
|
||||
inOrder(async () => {
|
||||
try {
|
||||
const updated = await adminApi.updateDefaultUserSettings({ [key]: null });
|
||||
setDefaults(updated);
|
||||
if (key === 'map_tile_url') setMapTileUrl('');
|
||||
if (key === 'mapbox_access_token') setMapboxToken('');
|
||||
if (key === 'carto_api_key') setCartoKey('');
|
||||
if (key === 'mapbox_style' || key === 'maplibre_style') {
|
||||
const provider = normalizeProvider(defaults.map_provider);
|
||||
setMapboxStyle(provider === 'leaflet' ? '' : defaultStyleForProvider(provider));
|
||||
}
|
||||
toast.success(t('admin.defaultSettings.reset'));
|
||||
} catch (err: unknown) {
|
||||
toast.error(errorMessage(err, t('common.error')));
|
||||
}
|
||||
});
|
||||
|
||||
const isSet = (key: keyof Defaults) => defaults[key] !== undefined;
|
||||
|
||||
|
||||
@@ -111,11 +111,23 @@ export const CHATGPT_USAGE_URL = 'https://chatgpt.com/settings/usage';
|
||||
* error page and the user pastes its address back; only the port may differ.
|
||||
*/
|
||||
export function isChatgptCallback(text: string): boolean {
|
||||
return chatgptCallbackUrl(text) !== null;
|
||||
}
|
||||
|
||||
/**
|
||||
* The pasted callback as the server reads it, or null when it is something
|
||||
* else. The address bar and the hint under the field show it without `http://`,
|
||||
* so an address pasted that way gets the scheme put back.
|
||||
*/
|
||||
export function chatgptCallbackUrl(text: string): string | null {
|
||||
const trimmed = text.trim();
|
||||
const address = /^[a-z][a-z\d+.-]*:\/\//i.test(trimmed) ? trimmed : `http://${trimmed}`;
|
||||
let url: URL;
|
||||
try {
|
||||
url = new URL(text.trim());
|
||||
url = new URL(address);
|
||||
} catch {
|
||||
return false;
|
||||
return null;
|
||||
}
|
||||
return url.protocol === 'http:' && url.hostname === '127.0.0.1' && url.pathname === '/auth/callback';
|
||||
const ok = url.protocol === 'http:' && url.hostname === '127.0.0.1' && url.pathname === '/auth/callback';
|
||||
return ok ? address : null;
|
||||
}
|
||||
|
||||
@@ -40,7 +40,7 @@ beforeEach(() => {
|
||||
|
||||
describe('BackgroundTasksWidget', () => {
|
||||
it('shows the warnings when a finished job produced no items', () => {
|
||||
const warning = 'voucher.pdf: AI parsing failed — LLM request failed (400): response_format unsupported'
|
||||
const warning = 'voucher.pdf: AI parsing failed: LLM request failed (400): response_format unsupported'
|
||||
useBackgroundTasksStore.setState({ tasks: [task({ warnings: [warning] })] })
|
||||
render(<BackgroundTasksWidget />)
|
||||
expect(screen.getByText('No reservations could be extracted from the uploaded files.')).toBeInTheDocument()
|
||||
@@ -141,7 +141,7 @@ describe('BackgroundTasksWidget', () => {
|
||||
* disappeared on save.
|
||||
*/
|
||||
it('shows the warnings on a job that did produce items', () => {
|
||||
const warning = 'voucher.pdf: could not locate "Curbside Pickup Counter 7" — set it manually before saving'
|
||||
const warning = 'voucher.pdf: could not locate "Curbside Pickup Counter 7", set it manually before saving'
|
||||
useBackgroundTasksStore.setState({
|
||||
tasks: [task({ items: [{ id: 1 } as never], warnings: [warning] })],
|
||||
})
|
||||
|
||||
@@ -339,6 +339,8 @@ describe('CollectionPlaceDetail', () => {
|
||||
address: 'Somewhere',
|
||||
lat: 52.5,
|
||||
lng: 13.4,
|
||||
// No notes on this place, and none written (#3168).
|
||||
notes: null,
|
||||
});
|
||||
// Back in read mode.
|
||||
expect(await screen.findByRole('button', { name: 'Edit' })).toBeInTheDocument();
|
||||
|
||||
@@ -32,7 +32,7 @@ interface CollectionPlaceDetailProps {
|
||||
anchorRect?: { left: number; width: number } | null
|
||||
onClose: () => void
|
||||
onSetStatus: (status: CollectionStatus) => void
|
||||
onSave: (patch: { name?: string; description?: string | null; links?: CollectionLink[]; category_id?: number | null; label_ids?: number[]; image_url?: string | null; lat?: number | null; lng?: number | null; address?: string | null }) => Promise<void>
|
||||
onSave: (patch: { name?: string; description?: string | null; notes?: string | null; links?: CollectionLink[]; category_id?: number | null; label_ids?: number[]; image_url?: string | null; lat?: number | null; lng?: number | null; address?: string | null }) => Promise<void>
|
||||
/** Upload a custom cover image (#1136); enables the cover change/remove controls. */
|
||||
onUploadImage?: (file: File) => Promise<void>
|
||||
onCopyToTrip: () => void
|
||||
@@ -74,7 +74,7 @@ export default function CollectionPlaceDetail({
|
||||
const navigationTargets = getNavigationTargets(place)
|
||||
const descRef = useRef<HTMLTextAreaElement>(null)
|
||||
const {
|
||||
editing, setEditing, name, setName, categoryId, setCategoryId, description, setDescription, links, setLinks, setLink,
|
||||
editing, setEditing, name, setName, categoryId, setCategoryId, description, setDescription, notes, setNotes, links, setLinks, setLink,
|
||||
labelIds, toggleLabel, address, setAddress, lat, setLat, lng, setLng, saving, imgBusy, cover: banner, assignedLabels,
|
||||
handleImagePick: handleCoverPick, handleImageRemove, cancelEdit: resetForm, save,
|
||||
} = useCollectionPlaceForm({ place, labels, onSave, onUploadImage, t, normalizeLinkUrl, withCoordinates: true })
|
||||
@@ -226,6 +226,11 @@ export default function CollectionPlaceDetail({
|
||||
<MarkdownToolbar textareaRef={descRef} onUpdate={setDescription} />
|
||||
<textarea ref={descRef} value={description} onChange={e => setDescription(e.target.value)} rows={4} placeholder={t('collections.descriptionPlaceholder')} className="col-detail-textarea" />
|
||||
</div>
|
||||
{/* Notes: the traveller's own, apart from the description (#3168) */}
|
||||
<div className="col-detail-field">
|
||||
<div className="col-detail-label">{t('collections.notes')}</div>
|
||||
<textarea value={notes} onChange={e => setNotes(e.target.value)} rows={3} placeholder={t('collections.notesPlaceholder')} className="col-detail-textarea" />
|
||||
</div>
|
||||
{/* Links */}
|
||||
<div className="col-detail-field">
|
||||
<div className="col-detail-label">{t('collections.links')}</div>
|
||||
@@ -248,6 +253,12 @@ export default function CollectionPlaceDetail({
|
||||
<Markdown remarkPlugins={[remarkGfm, remarkBreaks]} components={markdownLinkComponents}>{place.description}</Markdown>
|
||||
</div>
|
||||
)}
|
||||
{place.notes?.trim() && (
|
||||
<div className="col-detail-field">
|
||||
<div className="col-detail-label">{t('collections.notes')}</div>
|
||||
<p className="m-0 whitespace-pre-wrap text-body text-content-muted [overflow-wrap:anywhere]">{place.notes}</p>
|
||||
</div>
|
||||
)}
|
||||
{place.links && place.links.length > 0 && (
|
||||
<div className="col-detail-links">
|
||||
{place.links.map((l, i) => (
|
||||
|
||||
@@ -176,6 +176,7 @@ describe('useCollectionPlaceForm', () => {
|
||||
expect(detail.props.onSave).toHaveBeenCalledWith({
|
||||
name: 'Louvre',
|
||||
description: 'Museum',
|
||||
notes: null,
|
||||
links: [{ label: 'Map', url: 'https://maps.example' }],
|
||||
category_id: 3,
|
||||
label_ids: [11],
|
||||
@@ -192,6 +193,7 @@ describe('useCollectionPlaceForm', () => {
|
||||
expect(sheet.props.onSave).toHaveBeenCalledWith({
|
||||
name: 'Louvre',
|
||||
description: 'Museum',
|
||||
notes: null,
|
||||
links: [{ label: 'Site', url: 'https://louvre.example' }],
|
||||
category_id: 3,
|
||||
label_ids: [10],
|
||||
@@ -199,6 +201,25 @@ describe('useCollectionPlaceForm', () => {
|
||||
});
|
||||
});
|
||||
|
||||
it('FE-COMP-COLPLACEHOOK-014: seeds, edits and saves the own notes on a saved place (#3168)', async () => {
|
||||
const sheet = setup({ place: place({ notes: 'Book a week ahead' }) });
|
||||
expect(sheet.result.current.notes).toBe('Book a week ahead');
|
||||
act(() => {
|
||||
sheet.result.current.setEditing(true);
|
||||
sheet.result.current.setNotes(' Closed on Tuesdays ');
|
||||
});
|
||||
await act(async () => {
|
||||
await sheet.result.current.save();
|
||||
});
|
||||
expect(sheet.props.onSave).toHaveBeenCalledWith(expect.objectContaining({ notes: 'Closed on Tuesdays' }));
|
||||
|
||||
act(() => sheet.result.current.setNotes(' '));
|
||||
await act(async () => {
|
||||
await sheet.result.current.save();
|
||||
});
|
||||
expect(sheet.props.onSave).toHaveBeenLastCalledWith(expect.objectContaining({ notes: null }));
|
||||
});
|
||||
|
||||
it('FE-COMP-COLPLACEHOOK-010: a failed save stays in edit mode and toasts', async () => {
|
||||
const onSave = vi.fn().mockRejectedValue({ response: { data: { error: 'Locked' } } });
|
||||
const { result } = setup({ onSave });
|
||||
|
||||
@@ -12,6 +12,7 @@ import { cleanListLinks } from './useListEditor';
|
||||
export interface CollectionPlacePatch {
|
||||
name?: string;
|
||||
description?: string | null;
|
||||
notes?: string | null;
|
||||
links?: CollectionLink[];
|
||||
category_id?: number | null;
|
||||
label_ids?: number[];
|
||||
@@ -84,6 +85,8 @@ export function useCollectionPlaceForm({
|
||||
const [name, setName] = useState(shown?.name ?? '');
|
||||
const [categoryId, setCategoryId] = useState<number | null>(shown?.category_id ?? null);
|
||||
const [description, setDescription] = useState(shown?.description ?? '');
|
||||
// The traveller's own notes on the place (#3168), apart from its description.
|
||||
const [notes, setNotes] = useState(shown?.notes ?? '');
|
||||
const [links, setLinks] = useState<CollectionLink[]>(shown?.links ?? []);
|
||||
const [labelIds, setLabelIds] = useState<number[]>(shown?.label_ids ?? []);
|
||||
const [address, setAddress] = useState(shown?.address ?? '');
|
||||
@@ -101,6 +104,7 @@ export function useCollectionPlaceForm({
|
||||
setName(p.name);
|
||||
setCategoryId(p.category_id ?? null);
|
||||
setDescription(p.description ?? '');
|
||||
setNotes(p.notes ?? '');
|
||||
setLinks(p.links ?? []);
|
||||
setLabelIds(p.label_ids ?? []);
|
||||
setAddress(p.address ?? '');
|
||||
@@ -189,6 +193,7 @@ export function useCollectionPlaceForm({
|
||||
const base = {
|
||||
name: name.trim() || shown.name,
|
||||
description: description.trim() || null,
|
||||
notes: notes.trim() || null,
|
||||
links: cleanListLinks(links, normalizeLinkUrl),
|
||||
category_id: categoryId,
|
||||
label_ids: labelIds,
|
||||
@@ -215,6 +220,8 @@ export function useCollectionPlaceForm({
|
||||
setCategoryId,
|
||||
description,
|
||||
setDescription,
|
||||
notes,
|
||||
setNotes,
|
||||
links,
|
||||
setLinks,
|
||||
setLink,
|
||||
|
||||
@@ -526,6 +526,24 @@ describe('FileManager', () => {
|
||||
});
|
||||
});
|
||||
|
||||
it('FE-COMP-FILEMANAGER-039: a file pasted while the drop zone has focus is uploaded once', async () => {
|
||||
const onUpload = vi.fn().mockResolvedValue({ file: { id: 56 } });
|
||||
render(<FileManager {...defaultProps} onUpload={onUpload} />);
|
||||
|
||||
const zone = document.querySelector('[role="presentation"]') as HTMLElement;
|
||||
const file = new File(['data'], 'pasted.png', { type: 'image/png' });
|
||||
const pasteEvent = new Event('paste', { bubbles: true, cancelable: true });
|
||||
Object.defineProperty(pasteEvent, 'clipboardData', {
|
||||
value: { types: ['Files'], files: [file], items: [{ kind: 'file', type: 'image/png', getAsFile: () => file }] },
|
||||
});
|
||||
|
||||
await fireEvent(zone, pasteEvent);
|
||||
|
||||
await waitFor(() => expect(onUpload).toHaveBeenCalled());
|
||||
await new Promise((resolve) => setTimeout(resolve, 50));
|
||||
expect(onUpload).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('FE-COMP-FILEMANAGER-028: upload with places open assign modal after upload', async () => {
|
||||
const { buildPlace } = await import('../../../tests/helpers/factories');
|
||||
const place = buildPlace({ id: 10, name: 'Sagrada Familia' });
|
||||
|
||||
@@ -124,7 +124,9 @@ export function useFileManager({ files = [], onUpload, onDelete, onUpdate, place
|
||||
toast.error(t('files.uploadErrorSize', { max: maxUploadMb }))
|
||||
}
|
||||
},
|
||||
noClick: false,
|
||||
// Pasting is handled once for the whole panel (handlePaste), with the upload
|
||||
// permission check; the zone's own paste upload would send each file twice.
|
||||
noPaste: true,
|
||||
})
|
||||
|
||||
const handlePaste = useCallback((e: React.ClipboardEvent) => {
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
// FE-COMP-LIGHTBOX-001 to FE-COMP-LIGHTBOX-029
|
||||
// FE-COMP-LIGHTBOX-001 to FE-COMP-LIGHTBOX-030
|
||||
|
||||
// Plyr needs a real media pipeline, so the player is stubbed here.
|
||||
vi.mock('./VideoPlayer', () => ({
|
||||
@@ -87,9 +87,9 @@ describe('PhotoLightbox', () => {
|
||||
|
||||
it('FE-COMP-LIGHTBOX-007: does not render when photos array is empty', () => {
|
||||
const onClose = vi.fn();
|
||||
const { container } = render(<PhotoLightbox photos={[]} onClose={onClose} />);
|
||||
render(<PhotoLightbox photos={[]} onClose={onClose} />);
|
||||
// Component returns null when photo is undefined (empty array, index 0 is undefined)
|
||||
expect(container.querySelector('img')).not.toBeInTheDocument();
|
||||
expect(document.querySelector('img')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-COMP-LIGHTBOX-008: calls onClose when close button clicked', () => {
|
||||
@@ -100,10 +100,10 @@ describe('PhotoLightbox', () => {
|
||||
});
|
||||
|
||||
it('FE-COMP-LIGHTBOX-009: opens at the requested start index', () => {
|
||||
const { container } = render(<PhotoLightbox photos={samplePhotos} startIndex={2} onClose={vi.fn()} />);
|
||||
render(<PhotoLightbox photos={samplePhotos} startIndex={2} onClose={vi.fn()} />);
|
||||
expect(screen.getByText('3 / 3')).toBeInTheDocument();
|
||||
// The third photo has no caption, so its img is presentational.
|
||||
expect(container.querySelector('img')).toHaveAttribute('src', '/photos/3.jpg');
|
||||
expect(document.querySelector('img')).toHaveAttribute('src', '/photos/3.jpg');
|
||||
});
|
||||
|
||||
it('FE-COMP-LIGHTBOX-010: only offers the arrows that lead somewhere', () => {
|
||||
@@ -162,8 +162,8 @@ describe('PhotoLightbox', () => {
|
||||
});
|
||||
|
||||
it('FE-COMP-LIGHTBOX-015: swipes horizontally to move between photos', () => {
|
||||
const { container } = render(<PhotoLightbox photos={samplePhotos} startIndex={1} onClose={vi.fn()} />);
|
||||
const surface = container.firstElementChild as HTMLElement;
|
||||
render(<PhotoLightbox photos={samplePhotos} startIndex={1} onClose={vi.fn()} />);
|
||||
const surface = screen.getByRole('dialog');
|
||||
|
||||
fireEvent.touchStart(surface, { touches: [{ clientX: 200, clientY: 200 }] });
|
||||
fireEvent.touchEnd(surface, { changedTouches: [{ clientX: 100, clientY: 210 }] });
|
||||
@@ -176,8 +176,8 @@ describe('PhotoLightbox', () => {
|
||||
|
||||
it('FE-COMP-LIGHTBOX-016: swipes down to close', () => {
|
||||
const onClose = vi.fn();
|
||||
const { container } = render(<PhotoLightbox photos={samplePhotos} onClose={onClose} />);
|
||||
const surface = container.firstElementChild as HTMLElement;
|
||||
render(<PhotoLightbox photos={samplePhotos} onClose={onClose} />);
|
||||
const surface = screen.getByRole('dialog');
|
||||
|
||||
fireEvent.touchStart(surface, { touches: [{ clientX: 200, clientY: 100 }] });
|
||||
fireEvent.touchEnd(surface, { changedTouches: [{ clientX: 210, clientY: 300 }] });
|
||||
@@ -187,8 +187,8 @@ describe('PhotoLightbox', () => {
|
||||
|
||||
it('FE-COMP-LIGHTBOX-017: ignores a touch end without a matching touch start', () => {
|
||||
const onClose = vi.fn();
|
||||
const { container } = render(<PhotoLightbox photos={samplePhotos} onClose={onClose} />);
|
||||
const surface = container.firstElementChild as HTMLElement;
|
||||
render(<PhotoLightbox photos={samplePhotos} onClose={onClose} />);
|
||||
const surface = screen.getByRole('dialog');
|
||||
|
||||
fireEvent.touchEnd(surface, { changedTouches: [{ clientX: 210, clientY: 300 }] });
|
||||
|
||||
@@ -294,8 +294,8 @@ describe('PhotoLightbox', () => {
|
||||
});
|
||||
|
||||
it('FE-COMP-LIGHTBOX-026: a swipe to the right turns to the next photo', () => {
|
||||
const { container } = render(<PhotoLightbox photos={samplePhotos} startIndex={1} onClose={vi.fn()} />);
|
||||
const surface = container.firstElementChild as HTMLElement;
|
||||
render(<PhotoLightbox photos={samplePhotos} startIndex={1} onClose={vi.fn()} />);
|
||||
const surface = screen.getByRole('dialog');
|
||||
|
||||
fireEvent.touchStart(surface, { touches: [{ clientX: 100, clientY: 200 }] });
|
||||
fireEvent.touchEnd(surface, { changedTouches: [{ clientX: 200, clientY: 210 }] });
|
||||
@@ -305,6 +305,13 @@ describe('PhotoLightbox', () => {
|
||||
fireEvent.touchEnd(surface, { changedTouches: [{ clientX: 100, clientY: 210 }] });
|
||||
expect(screen.getByText('2 / 3')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-COMP-LIGHTBOX-030: the left inset of the screen stays on the left, where the close button now sits', () => {
|
||||
render(<PhotoLightbox photos={samplePhotos} onClose={vi.fn()} />);
|
||||
const style = screen.getByRole('dialog').style;
|
||||
expect(style.paddingInlineEnd).toContain('safe-area-inset-left');
|
||||
expect(style.paddingInlineStart).toContain('safe-area-inset-right');
|
||||
});
|
||||
});
|
||||
|
||||
it('FE-COMP-LIGHTBOX-027: a caption with a source page links to it in a new tab, one without stays text', () => {
|
||||
|
||||
@@ -1,9 +1,11 @@
|
||||
import { useState, useEffect, useCallback, useRef } from 'react'
|
||||
import { createPortal } from 'react-dom'
|
||||
import { ChevronLeft, ChevronRight, Loader2, X, ZoomIn, ZoomOut } from 'lucide-react'
|
||||
import VideoPlayer from './VideoPlayerLazy'
|
||||
import { usePhotoZoom } from './usePhotoZoom'
|
||||
import { Tooltip } from '../shared/Tooltip'
|
||||
import { isRtlLanguage, useTranslation } from '../../i18n'
|
||||
import { lockBodyScroll } from '../../utils/bodyScrollLock'
|
||||
|
||||
interface LightboxPhoto {
|
||||
id: string
|
||||
@@ -34,10 +36,22 @@ interface Props {
|
||||
/** The round glass buttons of the top bar. */
|
||||
const ROUND_BTN: React.CSSProperties = {
|
||||
background: 'rgba(255,255,255,0.1)', border: 'none', borderRadius: '50%',
|
||||
width: 36, height: 36, display: 'flex', alignItems: 'center', justifyContent: 'center',
|
||||
color: '#fff', cursor: 'pointer',
|
||||
width: 40, height: 40, display: 'flex', alignItems: 'center', justifyContent: 'center',
|
||||
color: '#fff', cursor: 'pointer', flex: 'none',
|
||||
}
|
||||
|
||||
/** Close is the one every visitor needs: a little stronger than the rest. */
|
||||
const CLOSE_BTN: React.CSSProperties = { ...ROUND_BTN, background: 'rgba(255,255,255,0.18)' }
|
||||
|
||||
/**
|
||||
* The device's insets, from whichever source reports them: env() in a browser,
|
||||
* the values Capacitor's SystemBars writes on Android, the ones the iOS app
|
||||
* measures itself. The viewer is portalled to <body>, outside the phone shell
|
||||
* that defines its own --m-safe-* tokens, so it reads the sources directly.
|
||||
*/
|
||||
const SAFE = (side: 'top' | 'bottom' | 'left' | 'right') =>
|
||||
`max(env(safe-area-inset-${side}, 0px), var(--safe-area-inset-${side}, 0px), var(--trek-native-safe-${side}, 0px))`
|
||||
|
||||
export default function PhotoLightbox({ photos, startIndex = 0, onClose, label }: Props) {
|
||||
const [idx, setIdx] = useState(startIndex)
|
||||
const touchStart = useRef<{ x: number; y: number } | null>(null)
|
||||
@@ -51,7 +65,11 @@ export default function PhotoLightbox({ photos, startIndex = 0, onClose, label }
|
||||
useEffect(() => {
|
||||
const opener = document.activeElement instanceof HTMLElement ? document.activeElement : null
|
||||
dialogRef.current?.focus()
|
||||
return () => opener?.focus()
|
||||
const unlock = lockBodyScroll()
|
||||
return () => {
|
||||
unlock()
|
||||
opener?.focus()
|
||||
}
|
||||
}, [])
|
||||
|
||||
const photo = photos[idx]
|
||||
@@ -111,7 +129,9 @@ export default function PhotoLightbox({ photos, startIndex = 0, onClose, label }
|
||||
|
||||
if (!photo) return null
|
||||
|
||||
return (
|
||||
// Portalled to <body>: inside a transformed sheet or pane, `fixed` would be
|
||||
// relative to that box and the viewer would open as a small window in it.
|
||||
return createPortal(
|
||||
<div
|
||||
ref={dialogRef}
|
||||
role="dialog"
|
||||
@@ -120,26 +140,28 @@ export default function PhotoLightbox({ photos, startIndex = 0, onClose, label }
|
||||
tabIndex={-1}
|
||||
style={{
|
||||
outline: 'none',
|
||||
position: 'fixed', inset: 0, zIndex: 10000,
|
||||
position: 'fixed', inset: 0, zIndex: 'var(--z-modal)',
|
||||
background: 'rgba(0,0,0,0.92)', backdropFilter: 'blur(20px)',
|
||||
display: 'flex', flexDirection: 'column',
|
||||
paddingBottom: 'var(--bottom-nav-h)',
|
||||
paddingBottom: SAFE('bottom'),
|
||||
// The insets belong to the screen's sides, which right to left swaps.
|
||||
paddingInlineStart: SAFE(rtl ? 'right' : 'left'),
|
||||
paddingInlineEnd: SAFE(rtl ? 'left' : 'right'),
|
||||
}}
|
||||
onTouchStart={onTouchStart}
|
||||
onTouchMove={onTouchMove}
|
||||
onTouchEnd={onTouchEnd}
|
||||
>
|
||||
{/* Photo area — centered with nav overlays */}
|
||||
<div
|
||||
className="group/lightbox"
|
||||
style={{ flex: 1, display: 'flex', alignItems: 'center', justifyContent: 'center', position: 'relative', overflow: 'hidden' }}
|
||||
>
|
||||
{/* Top bar */}
|
||||
<div style={{ position: 'absolute', top: 0, insetInline: 0, zIndex: 10, display: 'flex', justifyContent: 'space-between', alignItems: 'center', padding: '16px 20px' }}>
|
||||
<span style={{ color: 'rgba(255,255,255,0.5)', fontSize: 'calc(13px * var(--fs-scale-body, 1))', fontWeight: 500 }}>
|
||||
{idx + 1} / {photos.length}
|
||||
</span>
|
||||
<div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
|
||||
{/* Top bar: its own row below the status bar and a notch, so the close
|
||||
button is always there to tap and never sits over the photo. */}
|
||||
<div style={{
|
||||
flex: 'none', display: 'flex', justifyContent: 'space-between', alignItems: 'center', gap: 12,
|
||||
paddingBlock: `calc(${SAFE('top')} + 10px) 10px`, paddingInline: 16,
|
||||
}}>
|
||||
<span style={{ color: 'rgba(255,255,255,0.5)', fontSize: 'calc(13px * var(--fs-scale-body, 1))', fontWeight: 500, fontVariantNumeric: 'tabular-nums' }}>
|
||||
{idx + 1} / {photos.length}
|
||||
</span>
|
||||
<div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
|
||||
{isImage && (
|
||||
<>
|
||||
<Tooltip label={t('journey.lightbox.zoomOut')}>
|
||||
@@ -162,16 +184,17 @@ export default function PhotoLightbox({ photos, startIndex = 0, onClose, label }
|
||||
</Tooltip>
|
||||
</>
|
||||
)}
|
||||
<button type="button" onClick={onClose} aria-label={t('common.close')} style={{
|
||||
background: 'rgba(255,255,255,0.1)', border: 'none', borderRadius: '50%',
|
||||
width: 36, height: 36, display: 'flex', alignItems: 'center', justifyContent: 'center',
|
||||
color: '#fff', cursor: 'pointer',
|
||||
}}>
|
||||
<X size={18} />
|
||||
<button type="button" onClick={onClose} aria-label={t('common.close')} style={CLOSE_BTN}>
|
||||
<X size={20} />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Photo area: what is left below the bar, with the page arrows over it. */}
|
||||
<div
|
||||
className="group/lightbox"
|
||||
style={{ flex: 1, minHeight: 0, display: 'flex', alignItems: 'center', justifyContent: 'center', position: 'relative', overflow: 'hidden', padding: '0 8px 8px' }}
|
||||
>
|
||||
{/* Prev button — visible on hover (desktop), always visible (mobile) */}
|
||||
{hasPrev && (
|
||||
<button type="button" onClick={prev} aria-label={t('journey.lightbox.previous')} className="flex sm:opacity-0 sm:group-hover/lightbox:opacity-100 focus-visible:opacity-100 transition-opacity" style={{
|
||||
@@ -200,7 +223,7 @@ export default function PhotoLightbox({ photos, startIndex = 0, onClose, label }
|
||||
onError={() => setLoadedId(photo.id)}
|
||||
{...zoom.mouse}
|
||||
style={{
|
||||
maxWidth: '92vw', maxHeight: '92vh',
|
||||
maxWidth: '100%', maxHeight: '100%',
|
||||
objectFit: 'contain', borderRadius: 4,
|
||||
animation: 'fadeIn 0.15s ease',
|
||||
userSelect: 'none',
|
||||
@@ -212,7 +235,7 @@ export default function PhotoLightbox({ photos, startIndex = 0, onClose, label }
|
||||
{loading && (
|
||||
<div data-testid="lightbox-loading" aria-hidden="true" style={{ position: 'absolute', inset: 0, display: 'flex', alignItems: 'center', justifyContent: 'center', pointerEvents: 'none' }}>
|
||||
{photo.thumbSrc && (
|
||||
<img src={photo.thumbSrc} alt="" draggable={false} style={{ width: '92vw', height: '92vh', objectFit: 'contain', borderRadius: 4 }} />
|
||||
<img src={photo.thumbSrc} alt="" draggable={false} style={{ width: '100%', height: '100%', objectFit: 'contain', borderRadius: 4 }} />
|
||||
)}
|
||||
<span style={{ ...ROUND_BTN, position: 'absolute', cursor: 'default' }}>
|
||||
<Loader2 size={18} className="animate-spin" />
|
||||
@@ -252,6 +275,7 @@ export default function PhotoLightbox({ photos, startIndex = 0, onClose, label }
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>,
|
||||
document.body,
|
||||
)
|
||||
}
|
||||
|
||||
@@ -544,9 +544,9 @@ describe('Navbar styling and menu details', () => {
|
||||
|
||||
const discord = screen.getByTitle('Discord');
|
||||
fireEvent.mouseEnter(discord);
|
||||
expect(discord.style.background).toBe('rgba(88, 101, 242, 0.125)');
|
||||
expect(discord.style.background).toBe('rgba(88, 101, 242, 0.15)');
|
||||
fireEvent.mouseLeave(discord);
|
||||
expect(discord.style.background).toBe('var(--bg-tertiary)');
|
||||
expect(discord.style.background).toBe('');
|
||||
|
||||
expect(document.querySelector('img[src="/text-light.svg"]')).not.toBeNull();
|
||||
});
|
||||
|
||||
@@ -17,6 +17,7 @@ import { useCollapseOnOverflow } from '../../hooks/useCollapseOnOverflow'
|
||||
import { openMailInbox } from '../MailIngest/mailInboxOpener'
|
||||
import { useMailInboxShell } from '../MailIngest/useMailInboxShell'
|
||||
import MailInboxDialog from '../MailIngest/MailInboxDialog'
|
||||
import UserMenuFooter from './UserMenuFooter'
|
||||
|
||||
const ADDON_ICONS: Record<string, LucideIcon> = { CalendarDays, Briefcase, Globe, Compass, Bookmark }
|
||||
|
||||
@@ -311,7 +312,7 @@ export default function Navbar({ tripTitle, tripId, onBack, showBack, onSettings
|
||||
{userMenuOpen && createPortal(
|
||||
<>
|
||||
<div style={{ position: 'fixed', inset: 0, zIndex: 9998 }} role="presentation" onClick={() => setUserMenuOpen(false)} />
|
||||
<div className="trek-menu-enter w-52 rounded-xl shadow-xl border overflow-hidden bg-surface-card border-edge" style={{ position: 'fixed', top: 'var(--nav-h)', insetInlineEnd: 8, zIndex: 9999 }}>
|
||||
<div className="trek-menu-enter w-60 rounded-xl shadow-xl border overflow-hidden bg-surface-card border-edge" style={{ position: 'fixed', top: 'var(--nav-h)', insetInlineEnd: 8, zIndex: 9999 }}>
|
||||
<div className="px-4 py-3 border-b border-edge-secondary">
|
||||
<p className="text-sm font-medium text-content">{user.username}</p>
|
||||
<p className="text-xs truncate text-content-muted">{user.email}</p>
|
||||
@@ -368,23 +369,7 @@ export default function Navbar({ tripTitle, tripId, onBack, showBack, onSettings
|
||||
<LogOut className="w-4 h-4" />
|
||||
{t('nav.logout')}
|
||||
</button>
|
||||
{appVersion && (
|
||||
<div className="px-4 pt-2 pb-2.5 text-center border-t border-edge-secondary" style={{ marginTop: 4 }}>
|
||||
<div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 6 }}>
|
||||
<div style={{ display: 'inline-flex', alignItems: 'center', gap: 5, background: 'var(--bg-tertiary)', borderRadius: 99, padding: '4px 12px' }}>
|
||||
<img src={dark ? '/text-light.svg' : '/text-dark.svg'} alt="TREK" style={{ height: 10, opacity: 0.5 }} />
|
||||
<span style={{ fontSize: 'calc(10px * var(--fs-scale-caption, 1))', fontWeight: 600, color: 'var(--text-faint)' }}>v{appVersion}</span>
|
||||
</div>
|
||||
<a href="https://discord.gg/NhZBDSd4qW" target="_blank" rel="noopener noreferrer"
|
||||
style={{ display: 'inline-flex', alignItems: 'center', justifyContent: 'center', width: 24, height: 24, borderRadius: 99, background: 'var(--bg-tertiary)', transition: 'background 0.15s' }}
|
||||
onMouseEnter={e => e.currentTarget.style.background = '#5865F220'}
|
||||
onMouseLeave={e => e.currentTarget.style.background = 'var(--bg-tertiary)'}
|
||||
title="Discord">
|
||||
<svg width="12" height="12" viewBox="0 0 24 24" fill="var(--text-faint)"><path d="M20.317 4.37a19.791 19.791 0 0 0-4.885-1.515.074.074 0 0 0-.079.037c-.21.375-.444.864-.608 1.25a18.27 18.27 0 0 0-5.487 0 12.64 12.64 0 0 0-.617-1.25.077.077 0 0 0-.079-.037A19.736 19.736 0 0 0 3.677 4.37a.07.07 0 0 0-.032.027C.533 9.046-.32 13.58.099 18.057a.082.082 0 0 0 .031.057 19.9 19.9 0 0 0 5.993 3.03.078.078 0 0 0 .084-.028c.462-.63.874-1.295 1.226-1.994a.076.076 0 0 0-.041-.106 13.107 13.107 0 0 1-1.872-.892.077.077 0 0 1-.008-.128 10.2 10.2 0 0 0 .372-.292.074.074 0 0 1 .077-.01c3.928 1.793 8.18 1.793 12.062 0a.074.074 0 0 1 .078.01c.12.098.246.198.373.292a.077.077 0 0 1-.006.127 12.299 12.299 0 0 1-1.873.892.077.077 0 0 0-.041.107c.36.698.772 1.362 1.225 1.993a.076.076 0 0 0 .084.028 19.839 19.839 0 0 0 6.002-3.03.077.077 0 0 0 .032-.054c.5-5.177-.838-9.674-3.549-13.66a.061.061 0 0 0-.031-.03zM8.02 15.33c-1.183 0-2.157-1.085-2.157-2.419 0-1.333.956-2.419 2.157-2.419 1.21 0 2.176 1.095 2.157 2.42 0 1.333-.956 2.418-2.157 2.418zm7.975 0c-1.183 0-2.157-1.085-2.157-2.419 0-1.333.955-2.419 2.157-2.419 1.21 0 2.176 1.095 2.157 2.42 0 1.333-.946 2.418-2.157 2.418z"/></svg>
|
||||
</a>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
{appVersion && <UserMenuFooter appVersion={appVersion} dark={dark} managed={!!managed} />}
|
||||
</div>
|
||||
</div>
|
||||
</>,
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
// FE-MENUFOOT-001 to FE-MENUFOOT-004
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
import { fireEvent, render, screen } from '../../../tests/helpers/render';
|
||||
import { isNativeApp } from '../../native/platform';
|
||||
import UserMenuFooter from './UserMenuFooter';
|
||||
|
||||
vi.mock('../../native/platform', () => ({ isNativeApp: vi.fn(() => false) }));
|
||||
|
||||
function titles(): string[] {
|
||||
return [...document.querySelectorAll('a[title]')].map((a) => a.getAttribute('title') ?? '');
|
||||
}
|
||||
|
||||
describe('UserMenuFooter', () => {
|
||||
it('FE-MENUFOOT-001: shows the version and the three support links beside Discord', () => {
|
||||
render(<UserMenuFooter appVersion="5.2.1" dark={false} managed={false} />);
|
||||
expect(screen.getByText('v5.2.1')).toBeInTheDocument();
|
||||
expect(document.querySelector('img[src="/text-dark.svg"]')).not.toBeNull();
|
||||
expect(titles()).toEqual(['Patreon', 'Ko-fi', 'Buy Me a Coffee', 'Discord']);
|
||||
expect(screen.getByTitle('Ko-fi')).toHaveAttribute('href', 'https://ko-fi.com/mauriceboe');
|
||||
expect(screen.getByTitle('Buy Me a Coffee')).toHaveAttribute('href', 'https://buymeacoffee.com/mauriceboe');
|
||||
expect(screen.getByTitle('Patreon')).toHaveAttribute('href', 'https://www.patreon.com/cw/mauriceboe');
|
||||
});
|
||||
|
||||
it('FE-MENUFOOT-002: a managed install keeps only Discord', () => {
|
||||
render(<UserMenuFooter appVersion="5.2.1" dark managed />);
|
||||
expect(titles()).toEqual(['Discord']);
|
||||
expect(document.querySelector('img[src="/text-light.svg"]')).not.toBeNull();
|
||||
});
|
||||
|
||||
it('FE-MENUFOOT-003: the native app shows no donation link', () => {
|
||||
vi.mocked(isNativeApp).mockReturnValueOnce(true);
|
||||
render(<UserMenuFooter appVersion="5.2.1" dark={false} managed={false} />);
|
||||
expect(titles()).toEqual(['Discord']);
|
||||
});
|
||||
|
||||
it('FE-MENUFOOT-004: hovering a link washes it in its brand colour and leaving clears it', () => {
|
||||
render(<UserMenuFooter appVersion="5.2.1" dark={false} managed={false} />);
|
||||
const kofi = screen.getByTitle('Ko-fi');
|
||||
fireEvent.mouseEnter(kofi);
|
||||
expect(kofi.style.background).toBe('rgba(255, 94, 91, 0.15)');
|
||||
fireEvent.mouseLeave(kofi);
|
||||
expect(kofi.style.background).toBe('');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,100 @@
|
||||
import { Coffee, Heart } from 'lucide-react';
|
||||
import React from 'react';
|
||||
import { donationsShown } from '../../utils/donations';
|
||||
import { PATREON_PATH, PATREON_URL } from '../shared/PatreonIcon';
|
||||
|
||||
const DISCORD_PATH =
|
||||
'M20.317 4.37a19.791 19.791 0 0 0-4.885-1.515.074.074 0 0 0-.079.037c-.21.375-.444.864-.608 1.25a18.27 18.27 0 0 0-5.487 0 12.64 12.64 0 0 0-.617-1.25.077.077 0 0 0-.079-.037A19.736 19.736 0 0 0 3.677 4.37a.07.07 0 0 0-.032.027C.533 9.046-.32 13.58.099 18.057a.082.082 0 0 0 .031.057 19.9 19.9 0 0 0 5.993 3.03.078.078 0 0 0 .084-.028c.462-.63.874-1.295 1.226-1.994a.076.076 0 0 0-.041-.106 13.107 13.107 0 0 1-1.872-.892.077.077 0 0 1-.008-.128 10.2 10.2 0 0 0 .372-.292.074.074 0 0 1 .077-.01c3.928 1.793 8.18 1.793 12.062 0a.074.074 0 0 1 .078.01c.12.098.246.198.373.292a.077.077 0 0 1-.006.127 12.299 12.299 0 0 1-1.873.892.077.077 0 0 0-.041.107c.36.698.772 1.362 1.225 1.993a.076.076 0 0 0 .084.028 19.839 19.839 0 0 0 6.002-3.03.077.077 0 0 0 .032-.054c.5-5.177-.838-9.674-3.549-13.66a.061.061 0 0 0-.031-.03zM8.02 15.33c-1.183 0-2.157-1.085-2.157-2.419 0-1.333.956-2.419 2.157-2.419 1.21 0 2.176 1.095 2.157 2.42 0 1.333-.956 2.418-2.157 2.418zm7.975 0c-1.183 0-2.157-1.085-2.157-2.419 0-1.333.955-2.419 2.157-2.419 1.21 0 2.176 1.095 2.157 2.42 0 1.333-.946 2.418-2.157 2.418z';
|
||||
|
||||
interface FooterLink {
|
||||
title: string;
|
||||
href: string;
|
||||
/** The brand's colour, as a faint wash behind the icon on hover. */
|
||||
tint: string;
|
||||
icon: React.ReactNode;
|
||||
}
|
||||
|
||||
function brandSvg(path: string): React.ReactNode {
|
||||
return (
|
||||
<svg width="12" height="12" viewBox="0 0 24 24" fill="currentColor" aria-hidden="true">
|
||||
<path d={path} />
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
|
||||
const DISCORD: FooterLink = {
|
||||
title: 'Discord',
|
||||
href: 'https://discord.gg/NhZBDSd4qW',
|
||||
tint: '#5865F2', // Discord's brand colour
|
||||
icon: brandSvg(DISCORD_PATH),
|
||||
};
|
||||
|
||||
const SUPPORT: FooterLink[] = [
|
||||
{
|
||||
title: 'Patreon',
|
||||
href: PATREON_URL,
|
||||
tint: '#ff424d', // Patreon's brand colour
|
||||
icon: brandSvg(PATREON_PATH),
|
||||
},
|
||||
{
|
||||
title: 'Ko-fi',
|
||||
href: 'https://ko-fi.com/mauriceboe',
|
||||
tint: '#ff5e5b', // Ko-fi's brand colour
|
||||
icon: <Heart size={12} strokeWidth={2.4} aria-hidden="true" />,
|
||||
},
|
||||
{
|
||||
title: 'Buy Me a Coffee',
|
||||
href: 'https://buymeacoffee.com/mauriceboe',
|
||||
tint: '#ffdd00', // Buy Me a Coffee's brand colour
|
||||
icon: <Coffee size={12} strokeWidth={2.4} aria-hidden="true" />,
|
||||
},
|
||||
];
|
||||
|
||||
interface Props {
|
||||
appVersion: string;
|
||||
dark: boolean;
|
||||
/** A centrally administered install: its users are not the ones to ask for support. */
|
||||
managed: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* The foot of the user menu: the running version, then the round links to the
|
||||
* community and, where donations may be shown, the three ways to support TREK.
|
||||
*/
|
||||
export default function UserMenuFooter({ appVersion, dark, managed }: Props): React.ReactElement {
|
||||
const links = !managed && donationsShown() ? [...SUPPORT, DISCORD] : [DISCORD];
|
||||
return (
|
||||
<div className="mt-1 flex items-center justify-center gap-1.5 border-t border-edge-secondary px-3 pb-2.5 pt-2">
|
||||
<div className="inline-flex items-center gap-[5px] rounded-full bg-surface-tertiary px-2.5 py-1">
|
||||
<img src={dark ? '/text-light.svg' : '/text-dark.svg'} alt="TREK" className="h-2.5 opacity-50" />
|
||||
<span
|
||||
className="font-semibold text-content-faint"
|
||||
style={{ fontSize: 'calc(10px * var(--fs-scale-caption, 1))' }}
|
||||
>
|
||||
v{appVersion}
|
||||
</span>
|
||||
</div>
|
||||
{links.map((link) => (
|
||||
<a
|
||||
key={link.title}
|
||||
href={link.href}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
title={link.title}
|
||||
aria-label={link.title}
|
||||
className="grid h-6 w-6 flex-none place-items-center rounded-full bg-surface-tertiary text-content-faint transition-colors"
|
||||
onMouseEnter={(e) => {
|
||||
e.currentTarget.style.background = `${link.tint}26`;
|
||||
e.currentTarget.style.color = 'var(--text-primary)';
|
||||
}}
|
||||
onMouseLeave={(e) => {
|
||||
e.currentTarget.style.background = '';
|
||||
e.currentTarget.style.color = '';
|
||||
}}
|
||||
>
|
||||
{link.icon}
|
||||
</a>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -14,8 +14,9 @@ export type InboxAction = 'add' | 'choose' | 'file' | 'manual' | 'discard';
|
||||
const INFO_ONLY: ReadonlySet<MailIngestReason> = new Set(['forwarding_confirmation', 'newsletter', 'auto_reply']);
|
||||
|
||||
/**
|
||||
* A passing AI failure is read again by the server on its own; an allowance
|
||||
* used up leaves the form and the document, so there is no "read again" here.
|
||||
* The server reads a mail again after a passing AI failure and keeps it here
|
||||
* only once its last try failed too; an allowance used up leaves the form and
|
||||
* the document, so there is no "read again" here.
|
||||
*/
|
||||
export function actionsOf(entry: MailIngestInboxEntry): InboxAction[] {
|
||||
const reason = entry.reason ?? entry.message.reason;
|
||||
|
||||
@@ -3,7 +3,7 @@ import { pluginsApi } from '../../api/client'
|
||||
import type { RouteEngine, RouteResult, RouteSegment, RouteWithLegs, SnappedWaypoint, Waypoint, RouteAnchors } from '../../types'
|
||||
import { haversineKm } from '../../utils/geo'
|
||||
import { countRoute } from './routeUsageCounter'
|
||||
import { cacheRoute, rememberRoute, routeInMemory, storedRoute } from './routeStore'
|
||||
import { cacheRoute, keepStandIn, rememberRoute, routeInMemory, standIn, storedRoute } from './routeStore'
|
||||
import { formatDuration, formatRouteDistance, getDistanceUnit, legSegment } from './routeText'
|
||||
import type { RouteAlternative } from './routeTypes'
|
||||
import { valhallaAvailable, valhallaPlansDays, valhallaRoutesDays, type AvoidClass } from './valhallaRoute'
|
||||
@@ -289,6 +289,12 @@ function withEngine(route: RouteWithLegs, engine: RouteEngine): RouteWithLegs {
|
||||
* A day planned with Valhalla: its answer, kept under the Valhalla key, or where it gives
|
||||
* none OSRM's for the whole day, kept under the plain key. One engine per day, never one
|
||||
* leg from each. While the relay rests, a day that avoids nothing is not put to it at all.
|
||||
*
|
||||
* A day that avoids nothing and that Valhalla could not route is not put to it again for a
|
||||
* while: OSRM's answer, the same road an OSRM instance draws, stands in for it under a key
|
||||
* of its own, so every visit does not wait out the relay first (#3228). Never under the
|
||||
* Valhalla key, which holds only what Valhalla answered. A day that avoids something is
|
||||
* asked again, since the stand-in drives the very road it means to leave out.
|
||||
*/
|
||||
async function valhallaOrOsrmDay(
|
||||
waypoints: Waypoint[],
|
||||
@@ -299,6 +305,9 @@ async function valhallaOrOsrmDay(
|
||||
signal?: AbortSignal
|
||||
},
|
||||
): Promise<RouteWithLegs> {
|
||||
const standInKey = avoiding.length ? null : `${keys.valhalla}:standin`
|
||||
const stoodIn = standInKey ? await standIn(standInKey) : null
|
||||
if (stoodIn) return stoodIn
|
||||
const asking = avoiding.length > 0 || valhallaRoutesDays()
|
||||
const routed = asking ? await valhallaDayRoute(waypoints, profile, avoiding, signal) : null
|
||||
if (routed) {
|
||||
@@ -307,7 +316,10 @@ async function valhallaOrOsrmDay(
|
||||
}
|
||||
const plain = (await storedRoute(keys.plain)) ?? await osrmWithLegs(waypoints, keys.coords, profile, signal)
|
||||
cacheRoute(keys.plain, plain)
|
||||
return withFallbackNoted(plain, avoiding)
|
||||
const drawn = withFallbackNoted(plain, avoiding)
|
||||
// A day left before Valhalla answered, or never put to it, was not refused by it.
|
||||
if (standInKey && asking && !signal?.aborted) keepStandIn(standInKey, drawn)
|
||||
return drawn
|
||||
}
|
||||
|
||||
/** Fetches a full route via OSRM and returns coordinates, distance, and duration estimates for driving/walking. */
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import type { Ref } from 'react'
|
||||
import { AlertTriangle, Route } from 'lucide-react'
|
||||
import { useTranslation } from '../../i18n'
|
||||
import { MapTogglePill } from './MapTogglePill'
|
||||
@@ -6,6 +7,9 @@ import { routeDistanceLabel } from './tripRouteLabels'
|
||||
import type { TripRouteOverview as Overview } from './useTripRouteOverview'
|
||||
import type { DistanceUnit } from '../../types'
|
||||
|
||||
export const TRIP_OVERVIEW_MAX_WIDTH = 320
|
||||
export const TRIP_OVERVIEW_INSET = 14
|
||||
|
||||
/**
|
||||
* Toggle for the whole-trip route overview (#1736). Same frosted shell as the other
|
||||
* map controls, so it lines up with the compass and the layer switcher.
|
||||
@@ -29,13 +33,14 @@ export function TripRouteOverviewPill({ active, onToggle }: { active: boolean; o
|
||||
* One component for both shells: the phone and the desktop place it differently but the
|
||||
* rows are the same rows, and a second copy of them is a second thing to keep in step.
|
||||
*/
|
||||
export function TripRouteOverviewPanel({ overview, unit, selectedDayId, onSelectDay, maxWidth = 320 }: {
|
||||
export function TripRouteOverviewPanel({ overview, unit, selectedDayId, onSelectDay, maxWidth = TRIP_OVERVIEW_MAX_WIDTH, cardRef }: {
|
||||
overview: Overview
|
||||
unit: DistanceUnit
|
||||
selectedDayId?: number | null
|
||||
onSelectDay?: (dayId: number) => void
|
||||
/** How wide the card may grow before day names start to ellipsize. */
|
||||
maxWidth?: number
|
||||
cardRef?: Ref<HTMLDivElement>
|
||||
}) {
|
||||
const { t } = useTranslation()
|
||||
if (!overview.days.length) return null
|
||||
@@ -45,6 +50,7 @@ export function TripRouteOverviewPanel({ overview, unit, selectedDayId, onSelect
|
||||
|
||||
return (
|
||||
<div
|
||||
ref={cardRef}
|
||||
data-testid="trip-overview-panel"
|
||||
style={{
|
||||
pointerEvents: 'auto', borderRadius: 14, overflow: 'hidden',
|
||||
|
||||
@@ -35,4 +35,12 @@ describe('centredMapCard', () => {
|
||||
expect(resolve(box.width, 1920)).toBe(800);
|
||||
expect(resolve(box.centre, 1920)).toBe(960);
|
||||
});
|
||||
|
||||
it('keeps the whole-trip toggle reachable beside the day card', () => {
|
||||
const box = centredMapCard(350, 310, { clearPill: true, rightGap: 74 });
|
||||
const width = resolve(box.width, 1280);
|
||||
const centre = resolve(box.centre, 1280);
|
||||
expect(centre - width / 2).toBeGreaterThanOrEqual(350 + 62);
|
||||
expect(centre + width / 2).toBeLessThanOrEqual(1280 - 310 - 74);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -18,6 +18,7 @@ const PILL_CLEARANCE = MAP_LAYER_SWITCHER_INSET + MAP_ROUND_CONTROL_SIZE + 8;
|
||||
* it and gives up the few pixels it needs, a wide map keeps it exactly centred.
|
||||
* The phone shows these cards as sheets with no pill beside them, so it leaves
|
||||
* `clearPill` off.
|
||||
* `rightGap` reserves room for a map control on the other edge.
|
||||
*
|
||||
* `extent` is what the card is placed in: '100%' of the map, or '100vw' for the
|
||||
* fixed day panel.
|
||||
@@ -29,13 +30,21 @@ const PILL_CLEARANCE = MAP_LAYER_SWITCHER_INSET + MAP_ROUND_CONTROL_SIZE + 8;
|
||||
export function centredMapCard(
|
||||
leftWidth: number,
|
||||
rightWidth: number,
|
||||
{ extent = '100%', clearPill = false }: { extent?: string; clearPill?: boolean } = {}
|
||||
{
|
||||
extent = '100%',
|
||||
clearPill = false,
|
||||
rightGap = EDGE_GAP,
|
||||
}: { extent?: string; clearPill?: boolean; rightGap?: number } = {}
|
||||
): { centre: string; width: string } {
|
||||
const free = `(${extent} - ${leftWidth}px - ${rightWidth}px)`;
|
||||
const centre = `calc(${leftWidth}px + ${free} / 2)`;
|
||||
if (!clearPill) return { centre, width: `min(800px, calc(${free} - ${2 * EDGE_GAP}px))` };
|
||||
const width = `min(800px, calc(${free} - ${PILL_CLEARANCE + EDGE_GAP}px))`;
|
||||
return { width, centre: `max(${centre}, calc(${leftWidth}px + ${PILL_CLEARANCE}px + ${width} / 2))` };
|
||||
const leftGap = clearPill ? PILL_CLEARANCE : EDGE_GAP;
|
||||
const width = `min(800px, calc(${free} - ${leftGap + rightGap}px))`;
|
||||
const centreClearingLeft = `max(${centre}, calc(${leftWidth}px + ${leftGap}px + ${width} / 2))`;
|
||||
if (rightGap === EDGE_GAP) return { width, centre: clearPill ? centreClearingLeft : centre };
|
||||
|
||||
const maxCentre = `calc(${extent} - ${rightWidth + rightGap}px - ${width} / 2)`;
|
||||
return { width, centre: `min(${centreClearingLeft}, ${maxCentre})` };
|
||||
}
|
||||
|
||||
/** How a card that floats over the map is placed there, read by `centredMapCard`. */
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { createRequire } from 'node:module';
|
||||
import { dirname, join } from 'node:path';
|
||||
import { describe, expect, it } from 'vitest';
|
||||
|
||||
// mapbox-gl and maplibre-gl ship in the same bundle, and both pass messages to
|
||||
// their workers through a class registry that stamps `_classRegistryKey` on
|
||||
// constructors. maplibre stamps the built-ins Set and Error globally. mapbox-gl
|
||||
// 3.33 and later read that key before their own Set and Error handling, find no
|
||||
// entry for "Set" in their registry and throw "Cannot read properties of
|
||||
// undefined (reading 'omit')" for every vector tile, so the Mapbox basemap stays
|
||||
// blank while raster layers still load. These read the shipped files because the
|
||||
// clash only exists between the two real libraries.
|
||||
const requireFromClient = createRequire(import.meta.url);
|
||||
|
||||
function distFile(pkg: string, file: string): string {
|
||||
const root = dirname(requireFromClient.resolve(`${pkg}/package.json`));
|
||||
return readFileSync(join(root, 'dist', file), 'utf8');
|
||||
}
|
||||
|
||||
function functionBody(source: string, signature: string): string {
|
||||
const start = source.indexOf(signature);
|
||||
expect(start, `${signature} not found`).toBeGreaterThan(-1);
|
||||
return source.slice(start, source.indexOf('\n}\n', start));
|
||||
}
|
||||
|
||||
describe('GL worker class registry', () => {
|
||||
it('FE-COMP-GLWORKERREGISTRY-001: maplibre-gl stamps the global Set and Error', () => {
|
||||
const maplibre = distFile('maplibre-gl', 'maplibre-gl-dev.mjs');
|
||||
expect(maplibre).toMatch(/register\("Set", Set\)/);
|
||||
expect(maplibre).toMatch(/register\("Error", Error\)/);
|
||||
});
|
||||
|
||||
it('FE-COMP-GLWORKERREGISTRY-002: mapbox-gl handles Set and Error before it reads the registry key', () => {
|
||||
const serialize = functionBody(
|
||||
distFile('mapbox-gl', 'mapbox-gl-dev.js'),
|
||||
'function serialize(input, transferables)'
|
||||
);
|
||||
const registryRead = serialize.indexOf('._classRegistryKey');
|
||||
expect(registryRead).toBeGreaterThan(-1);
|
||||
expect(serialize.indexOf('instanceof Set')).toBeGreaterThan(-1);
|
||||
expect(serialize.indexOf('instanceof Set')).toBeLessThan(registryRead);
|
||||
expect(serialize.indexOf('instanceof Error')).toBeLessThan(registryRead);
|
||||
});
|
||||
});
|
||||
@@ -39,3 +39,21 @@ export async function storedRoute(key: string): Promise<RouteWithLegs | null> {
|
||||
if (kept) rememberRoute(key, kept);
|
||||
return kept;
|
||||
}
|
||||
|
||||
/**
|
||||
* How long OSRM's answer stands in for a day Valhalla could not route. Long enough that
|
||||
* reopening the trip draws that day at once instead of waiting out the relay again on
|
||||
* every visit (#3228), short enough that a Valhalla back from an outage gets the day again
|
||||
* the same day.
|
||||
*/
|
||||
const STAND_IN_MS = 60 * 60 * 1000;
|
||||
|
||||
/** Keeps OSRM's answer for a day Valhalla could not route, on the device only, for `STAND_IN_MS`. */
|
||||
export function keepStandIn(key: string, route: RouteWithLegs): void {
|
||||
void routeCacheRepo.put(key, route);
|
||||
}
|
||||
|
||||
/** The answer that stood in for a day Valhalla could not route, while it is recent enough. */
|
||||
export function standIn(key: string): Promise<RouteWithLegs | null> {
|
||||
return routeCacheRepo.get<RouteWithLegs>(key, STAND_IN_MS);
|
||||
}
|
||||
|
||||
@@ -17,6 +17,9 @@ export interface TripRouteOverview extends TripRouteSummary {
|
||||
loading: boolean
|
||||
}
|
||||
|
||||
/** The overview as the planner reads it: also whether the trip has any stop to route at all. */
|
||||
type PlannedTripRouteOverview = TripRouteOverview & { hasPlannedRoute: boolean }
|
||||
|
||||
const EMPTY: TripRouteOverview = { ...summariseTripRoute([]), loading: false }
|
||||
const EMPTY_PLACES: Place[] = []
|
||||
|
||||
@@ -49,7 +52,7 @@ export function useTripRouteOverview(
|
||||
vias?: TripRouteVias,
|
||||
/** MDT-02: where the stages of the trip's multi-day tours run, so a day holding one draws that stage. */
|
||||
tourStageStops?: TourStageStops,
|
||||
): TripRouteOverview {
|
||||
): PlannedTripRouteOverview {
|
||||
const optimizeFromAccommodation = useSettingsStore(s => s.settings.optimize_from_accommodation)
|
||||
const toursEnabled = useTripAddonEnabled(tripId, 'tours')
|
||||
// Leg text is formatted at compute time, so a km↔mi switch has to re-run (#1300).
|
||||
@@ -131,5 +134,6 @@ export function useTripRouteOverview(
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [planKey, tripId, distanceUnit])
|
||||
|
||||
return result
|
||||
const hasPlannedRoute = plan.length > 0
|
||||
return useMemo(() => ({ ...result, hasPlannedRoute }), [result, hasPlannedRoute])
|
||||
}
|
||||
|
||||
@@ -59,6 +59,8 @@ interface Traffic {
|
||||
osrm: string[];
|
||||
}
|
||||
|
||||
const HOUR = 60 * 60 * 1000;
|
||||
|
||||
const answered = (body: RouteBody) => HttpResponse.json({ trip: valhallaTrip(body.locations) });
|
||||
|
||||
/** Every routing host answering, the relay as `relay` says; what each was asked is recorded. */
|
||||
@@ -274,12 +276,59 @@ describe('the route cache keeps the engine apart', () => {
|
||||
|
||||
up = true;
|
||||
resetValhallaTurns();
|
||||
expect((await calculateRouteWithLegs(points, { profile: 'driving' })).distance).toBe(2000);
|
||||
expect(traffic.relay).toHaveLength(1);
|
||||
|
||||
const now = Date.now();
|
||||
vi.spyOn(Date, 'now').mockReturnValue(now + HOUR + 1);
|
||||
expect((await calculateRouteWithLegs(points, { profile: 'driving' })).distance).toBe(4000);
|
||||
expect([traffic.relay.length, traffic.osrm.length]).toEqual([2, 1]);
|
||||
});
|
||||
|
||||
it('VDAY-CACHE-005: a day the relay could not route opens drawn after a reload, without waiting for the relay again (#3228)', async () => {
|
||||
const points = freshDay(3);
|
||||
let slow = true;
|
||||
const traffic = listen((body) =>
|
||||
slow ? HttpResponse.json({ error: 'The TREK routing service took too long' }, { status: 504 }) : answered(body)
|
||||
);
|
||||
expect((await calculateRouteWithLegs(points, { profile: 'driving' })).engine).toBe('osrm');
|
||||
const { offlineDb } = await import('../../db/offlineDb');
|
||||
const stoodIn = (key: string) => key.includes(`${points[0].lng},${points[0].lat}`) && key.endsWith(':standin');
|
||||
await vi.waitFor(async () => expect(await offlineDb.routeCache.filter((row) => stoodIn(row.key)).count()).toBe(1));
|
||||
|
||||
// A reload: the modules, and with them the routes in memory and the relay's rest, start over.
|
||||
vi.resetModules();
|
||||
const reloaded = await import('./RouteCalculator');
|
||||
const again = await reloaded.calculateRouteWithLegs(points, { profile: 'driving' });
|
||||
expect([again.distance, again.engine]).toEqual([2000, 'osrm']);
|
||||
expect([traffic.relay.length, traffic.osrm.length]).toEqual([1, 1]);
|
||||
|
||||
// An hour on, the relay gets the day again and its answer is kept as the day's.
|
||||
slow = false;
|
||||
const now = Date.now();
|
||||
vi.spyOn(Date, 'now').mockReturnValue(now + HOUR + 1);
|
||||
const routed = await reloaded.calculateRouteWithLegs(points, { profile: 'driving' });
|
||||
expect([routed.distance, routed.engine]).toEqual([4000, 'valhalla']);
|
||||
expect([traffic.relay.length, traffic.osrm.length]).toEqual([2, 1]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('the route cache while the relay rests', () => {
|
||||
it('VDAY-CACHE-006: a day drawn by OSRM while the relay rested is asked again as soon as it is back', async () => {
|
||||
let up = false;
|
||||
const traffic = listen((body) => (up ? answered(body) : HttpResponse.json({ error: 'down' }, { status: 503 })));
|
||||
await calculateRouteWithLegs(freshDay(2), { profile: 'driving' });
|
||||
const points = freshDay(3);
|
||||
expect((await calculateRouteWithLegs(points, { profile: 'driving' })).engine).toBe('osrm');
|
||||
expect(traffic.relay).toHaveLength(1);
|
||||
|
||||
up = true;
|
||||
resetValhallaTurns();
|
||||
const routed = await calculateRouteWithLegs(points, { profile: 'driving' });
|
||||
expect([routed.distance, routed.engine]).toEqual([4000, 'valhalla']);
|
||||
expect(traffic.relay).toHaveLength(2);
|
||||
});
|
||||
|
||||
it('VDAY-CACHE-003: a day kept from Valhalla is still found while the relay rests, as it is offline', async () => {
|
||||
const points = freshDay(3);
|
||||
let up = true;
|
||||
|
||||
@@ -463,6 +463,36 @@ describe('downloadTripPDF', () => {
|
||||
expect(html).not.toContain('<script>alert(1)</script>')
|
||||
})
|
||||
|
||||
// #3236: day notes, transport notes and the day intro are markdown in the planner too.
|
||||
it('FE-COMP-TRIPPDF-016m: renders markdown in day notes, transport notes and the day intro, sanitized', async () => {
|
||||
const md = {
|
||||
...richArgs,
|
||||
days: [{ ...dayWithPlaces, notes: '**Intro** day\n\n- museum\n- lunch' }],
|
||||
dayNotes: [{ ...dayNote, time: '*Bring* water\n___\n<script>alert(1)</script>' }],
|
||||
reservations: [{ ...transportReservation, notes: 'Seat **14A**\n1. check in\n2. board' }],
|
||||
}
|
||||
await downloadTripPDF(md)
|
||||
const html = getIframe()?.srcdoc ?? ''
|
||||
const doc = new DOMParser().parseFromString(html, 'text/html')
|
||||
const card = (selector: string) => {
|
||||
const found = doc.querySelector(selector)
|
||||
if (!found) throw new Error(`${selector} is not in the export`)
|
||||
return found
|
||||
}
|
||||
const intro = card('.day-intro')
|
||||
expect(intro.querySelector('strong')?.textContent).toBe('Intro')
|
||||
expect([...intro.querySelectorAll('li')].map(li => li.textContent)).toEqual(['museum', 'lunch'])
|
||||
const noteLine = card('.tl-note .note-time')
|
||||
expect(noteLine.querySelector('em')?.textContent).toBe('Bring')
|
||||
expect(noteLine.querySelector('hr')).not.toBeNull()
|
||||
expect(noteLine.querySelector('script')).toBeNull()
|
||||
expect(noteLine.textContent).toContain('<script>alert(1)</script>')
|
||||
const transportNote = card('.transport-note')
|
||||
expect(transportNote.querySelector('strong')?.textContent).toBe('14A')
|
||||
expect([...transportNote.querySelectorAll('ol li')].map(li => li.textContent)).toEqual(['check in', 'board'])
|
||||
expect(html).not.toContain('**')
|
||||
})
|
||||
|
||||
it('FE-COMP-TRIPPDF-016b: formats price chip and totals in the trip currency, not EUR', async () => {
|
||||
const usdArgs = {
|
||||
...richArgs,
|
||||
@@ -1464,7 +1494,8 @@ describe('downloadTripPDF — transport notes', () => {
|
||||
await downloadTripPDF({ ...richArgs, reservations: [{ ...withNote, notes: 'Gate <b>B12</b>' }] })
|
||||
const html = getIframe()!.srcdoc
|
||||
|
||||
expect(html).toContain('<div class="note-time transport-note">Gate <b>B12</b></div>')
|
||||
// Markdown like the planner (#3236), raw HTML still printed as text.
|
||||
expect(html).toContain('<div class="note-time transport-note md"><p><bdi>Gate <b>B12</b></bdi></p></div>')
|
||||
expect(html).not.toContain('pdf-no-transport-notes"')
|
||||
expect(notesToggle()!.getAttribute('aria-checked')).toBe('true')
|
||||
})
|
||||
@@ -1472,7 +1503,7 @@ describe('downloadTripPDF — transport notes', () => {
|
||||
it('FE-PDF-TNOTES-002: without any transport note there is nothing to switch', async () => {
|
||||
await downloadTripPDF(richArgs)
|
||||
|
||||
expect(getIframe()!.srcdoc).not.toContain('class="note-time transport-note"')
|
||||
expect(getIframe()!.srcdoc).not.toContain('class="note-time transport-note')
|
||||
expect(notesToggle()).toBeNull()
|
||||
// The page break switch is still there on its own.
|
||||
expect(document.querySelector('#pdf-daybreak-toggle')).not.toBeNull()
|
||||
|
||||
@@ -245,6 +245,7 @@ export async function downloadTripPDF({ trip, days, places, assignments: allStor
|
||||
return url ? thumbs.get(url) ?? url : null
|
||||
},
|
||||
markdown: text => markdown.row(text),
|
||||
markdownHtml: text => markdown.html(text),
|
||||
}
|
||||
|
||||
/*
|
||||
@@ -303,7 +304,7 @@ export async function downloadTripPDF({ trip, days, places, assignments: allStor
|
||||
? `<div class="empty-day">${escHtml(tr('dayplan.emptyDay'))}</div>`
|
||||
: `<ol class="timeline">${merged.map(item => {
|
||||
if (item.type === 'transport') return bookingItem(item.data as PdfBooking, day, ctx, flags)
|
||||
if (item.type === 'note') return noteItem(item.data as DayNote)
|
||||
if (item.type === 'note') return noteItem(item.data as DayNote, ctx)
|
||||
const a = item.data as Assignment
|
||||
if (!a.place) return ''
|
||||
number++
|
||||
@@ -316,7 +317,7 @@ export async function downloadTripPDF({ trip, days, places, assignments: allStor
|
||||
cost: dayCost(day.id) || null,
|
||||
}, ctx)
|
||||
const strip = photoStrip((stripPhotos.get(day.id) || []).map(p => ({ ...p, url: stripCopies.get(p.url) ?? p.url })))
|
||||
const intro = day.notes && day.notes.trim() ? `<div class="day-intro">${escHtml(day.notes.trim())}</div>` : ''
|
||||
const intro = day.notes && day.notes.trim() ? `<div class="day-intro md">${markdown.html(day.notes.trim())}</div>` : ''
|
||||
const stays = staysBlock(staysForDay(day, days, accommodationList), day, ctx)
|
||||
|
||||
// A real <table> so the browser repeats the <thead> day header at the top of
|
||||
|
||||
@@ -1,15 +1,22 @@
|
||||
import { createMarkdownHtml } from '../shared/markdownHtml';
|
||||
|
||||
/**
|
||||
* A place's description and notes are markdown in the app, so the export
|
||||
* renders them the same way instead of printing the raw syntax (#2692): one
|
||||
* info row per text, the HTML from the app's own sanitized pipeline.
|
||||
* Place descriptions and notes, day notes, booking notes and the day intro are
|
||||
* markdown in the app, so the export renders them the same way instead of
|
||||
* printing the raw syntax (#2692, #3236), the HTML from the app's own sanitized
|
||||
* pipeline. `row` lays a place's text out as an info row, `html` is the bare
|
||||
* markup for a card that brings its own box.
|
||||
*/
|
||||
export function createPdfMarkdown(): { row: (text: string) => string; dispose: () => void } {
|
||||
export function createPdfMarkdown(): {
|
||||
row: (text: string) => string;
|
||||
html: (text: string) => string;
|
||||
dispose: () => void;
|
||||
} {
|
||||
const markdown = createMarkdownHtml();
|
||||
return {
|
||||
row: (text) =>
|
||||
`<div class="info-row"><span class="info-spacer"></span><div class="info-text muted md">${markdown.html(text)}</div></div>`,
|
||||
html: markdown.html,
|
||||
dispose: markdown.dispose,
|
||||
};
|
||||
}
|
||||
@@ -17,6 +24,7 @@ export function createPdfMarkdown(): { row: (text: string) => string; dispose: (
|
||||
/** The markdown's own spacing, lists, tables and links at the export's small size. */
|
||||
export const PDF_MARKDOWN_CSS = `
|
||||
.info-text.md { min-width: 0; overflow-wrap: anywhere; }
|
||||
.note-time.md, .day-intro.md { white-space: normal; }
|
||||
.md > :first-child { margin-top: 0; }
|
||||
.md > :last-child { margin-bottom: 0; }
|
||||
.md p, .md ul, .md ol, .md table, .md blockquote, .md pre { margin: 0 0 4px; }
|
||||
|
||||
@@ -50,6 +50,7 @@ function context(over: Partial<PdfDayContext> = {}): PdfDayContext {
|
||||
placesById: new Map([[fullPlace.id, fullPlace]]),
|
||||
photoOf: () => null,
|
||||
markdown: (text) => `<p>${text}</p>`,
|
||||
markdownHtml: (text) => `<p>${text}</p>`,
|
||||
...over,
|
||||
};
|
||||
}
|
||||
@@ -169,7 +170,7 @@ describe('noteItem', () => {
|
||||
icon: 'Ticket',
|
||||
color: '#2563eb',
|
||||
} as DayNote;
|
||||
const tinted = parse(noteItem(note));
|
||||
const tinted = parse(noteItem(note, context()));
|
||||
expect(tinted.querySelector('.note-card')?.className).toBe('note-card note-tinted');
|
||||
expect(tinted.querySelector('.note-card')?.getAttribute('style')).toBe('--note:#2563eb');
|
||||
expect(texts(tinted, '.note-text')).toEqual(['Buy <tickets>']);
|
||||
@@ -177,7 +178,7 @@ describe('noteItem', () => {
|
||||
expect(texts(tinted, '.note-time')).toEqual(['08:00']);
|
||||
expect(tinted.querySelector('.tl-start')).toBeNull();
|
||||
|
||||
const plain = parse(noteItem({ ...note, color: 'not-a-colour', time: null } as DayNote));
|
||||
const plain = parse(noteItem({ ...note, color: 'not-a-colour', time: null } as DayNote, context()));
|
||||
expect(plain.querySelector('.note-card')?.className).toBe('note-card');
|
||||
expect(plain.querySelector('.note-time')).toBeNull();
|
||||
});
|
||||
|
||||
@@ -30,8 +30,10 @@ export interface PdfDayContext {
|
||||
placesById: ReadonlyMap<number, Place>;
|
||||
/** The picture to print for a place, already shrunk where it could be; null for none. */
|
||||
photoOf: (place: Assignment['place']) => string | null;
|
||||
/** A place's description or notes as sanitized markdown. */
|
||||
/** A place's description or notes as sanitized markdown, laid out as an info row. */
|
||||
markdown: (text: string) => string;
|
||||
/** A note's markdown as sanitized HTML, for a card that brings its own box. */
|
||||
markdownHtml: (text: string) => string;
|
||||
}
|
||||
|
||||
const NEUTRAL = '#6b6b75';
|
||||
@@ -214,7 +216,7 @@ export function bookingItem(r: PdfBooking, day: Day, ctx: PdfDayContext, flags:
|
||||
${bookingLines(r, tr).map(bookingLineHtml).join('')}
|
||||
${location ? `<div class="note-time">${escHtml(location)}</div>` : ''}
|
||||
${extras.length ? `<div class="note-extra">${extras.join('')}</div>` : ''}
|
||||
${note ? `<div class="note-time transport-note">${escHtml(note)}</div>` : ''}
|
||||
${note ? `<div class="note-time transport-note md">${ctx.markdownHtml(note)}</div>` : ''}
|
||||
</div>
|
||||
</div>`;
|
||||
return item('booking', timeColumn(start, end), bookingIcon(r.type, 11), card, `--kind:${tint}`);
|
||||
@@ -226,15 +228,16 @@ export function bookingItem(r: PdfBooking, day: Day, ctx: PdfDayContext, flags:
|
||||
* A day note. A coloured note carries its colour as the rule along its edge and its
|
||||
* icon (#1629), not as a fill: a tint costs ink and reads as grey on a mono printer.
|
||||
*/
|
||||
export function noteItem(note: DayNote): string {
|
||||
export function noteItem(note: DayNote, ctx: PdfDayContext): string {
|
||||
const colour = note.color ? hexColour(note.color, '') : '';
|
||||
// A note's `time` is the free line the day plan prints under its text, not a clock,
|
||||
// so it stays in the card and the time column stays empty.
|
||||
// so it stays in the card and the time column stays empty. The planner renders it as
|
||||
// markdown, so the card does too (#3236).
|
||||
const subtitle = typeof note.time === 'string' ? note.time.trim() : '';
|
||||
const card = `<div class="note-card${colour ? ' note-tinted' : ''}"${colour ? ` style="--note:${colour}"` : ''}>
|
||||
<span class="note-icon">${noteIcon(note.icon)}</span>
|
||||
<div class="note-body"><div class="note-text">${escHtml(note.text)}</div>${
|
||||
subtitle ? `<div class="note-time">${escHtml(subtitle)}</div>` : ''
|
||||
subtitle ? `<div class="note-time md">${ctx.markdownHtml(subtitle)}</div>` : ''
|
||||
}</div>
|
||||
</div>`;
|
||||
return item('note', timeColumn('', ''), '', card);
|
||||
|
||||
@@ -204,6 +204,9 @@ describe('BookingCostsSection', () => {
|
||||
expect(screen.getByText('Transport')).toBeInTheDocument();
|
||||
expect(screen.getByText(money(99, 'CHF'))).toBeInTheDocument();
|
||||
expect(screen.queryByRole('button', { name: /Create expense/ })).not.toBeInTheDocument();
|
||||
// The save adds the cost itself and opens no editor, so the preview says that (#3237).
|
||||
expect(screen.getByText('Added to Costs when you save the booking.')).toBeInTheDocument();
|
||||
expect(screen.queryByText('Saves the booking, then opens the Costs editor.')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-PLANNER-COSTSEC-016: an amount without a currency is in the trip currency, whatever the display currency (#2525)', () => {
|
||||
|
||||
@@ -29,7 +29,7 @@ export function BookingCostsSection({ reservationId, placeId = null, hintKey = '
|
||||
reservationId: number | null
|
||||
/** Set instead of reservationId when the block sits in the place form (#1298). */
|
||||
placeId?: number | null
|
||||
/** What gets saved before the editor opens — "the booking" or "the place". */
|
||||
/** The create button's hint: what gets saved before the editor opens, "the booking" or "the place". */
|
||||
hintKey?: string
|
||||
/** A cost parsed from an import that will be linked on save — previewed before the booking exists. */
|
||||
pendingExpense?: { total_price: number; currency?: string | null; category: string } | null
|
||||
@@ -76,6 +76,8 @@ export function BookingCostsSection({ reservationId, placeId = null, hintKey = '
|
||||
}
|
||||
|
||||
// Import review (booking not saved yet): preview the parsed cost that will be linked on save.
|
||||
// The save adds it itself and opens no editor, so the line under it says so, not the
|
||||
// create button's hint (#3237).
|
||||
if (linked.length === 0 && pendingExpense && pendingExpense.total_price > 0) {
|
||||
const meta = catMeta(pendingExpense.category)
|
||||
const Icon = meta.Icon
|
||||
@@ -86,7 +88,7 @@ export function BookingCostsSection({ reservationId, placeId = null, hintKey = '
|
||||
<span style={{ width: 26, height: 26, borderRadius: 7, display: 'grid', placeItems: 'center', background: meta.color + '22', color: meta.color, flexShrink: 0 }}><Icon size={14} /></span>
|
||||
<div style={{ flex: 1, minWidth: 0 }}>
|
||||
<div className="text-content" style={{ ...fs(14, 'body'), fontWeight: 600 }}>{t(meta.labelKey)}</div>
|
||||
<div className="text-content-faint" style={fs(12, 'body')}>{t(hintKey)}</div>
|
||||
<div className="text-content-faint" style={fs(12, 'body')}>{t('reservations.importedExpenseHint')}</div>
|
||||
</div>
|
||||
<span className="text-content" style={{ ...fs(14, 'body'), fontWeight: 700, flexShrink: 0 }}>{formatMoney(pendingExpense.total_price, ownCurrency(pendingExpense.currency), locale)}</span>
|
||||
</div>
|
||||
|
||||
@@ -1,32 +1,12 @@
|
||||
// FE-PLANNER-DAYDETAIL-DF-001 to FE-PLANNER-DAYDETAIL-DF-002
|
||||
// The day panel's heading with "date first in day headings" on (#2921).
|
||||
import userEvent from '@testing-library/user-event';
|
||||
import { http, HttpResponse } from 'msw';
|
||||
import { buildAdmin, buildDay, buildTrip } from '../../../tests/helpers/factories';
|
||||
import { server } from '../../../tests/helpers/msw/server';
|
||||
import { dayDetailProps as props, resetDayDetailPanel } from '../../../tests/helpers/dayDetailPanel';
|
||||
import { render, screen } from '../../../tests/helpers/render';
|
||||
import { resetAllStores, seedStore } from '../../../tests/helpers/store';
|
||||
import { useAuthStore } from '../../store/authStore';
|
||||
import { seedStore } from '../../../tests/helpers/store';
|
||||
import { useSettingsStore } from '../../store/settingsStore';
|
||||
import { useTripStore } from '../../store/tripStore';
|
||||
import DayDetailPanel from './DayDetailPanel';
|
||||
|
||||
const day = buildDay({ id: 1, trip_id: 1, date: '2025-06-15', title: 'Day in Paris' });
|
||||
|
||||
const props = {
|
||||
day,
|
||||
days: [day],
|
||||
places: [],
|
||||
categories: [],
|
||||
tripId: 1,
|
||||
assignments: {},
|
||||
reservations: [],
|
||||
lat: null,
|
||||
lng: null,
|
||||
onClose: vi.fn(),
|
||||
onAccommodationChange: vi.fn(),
|
||||
};
|
||||
|
||||
function settings(dayDateFirst: boolean) {
|
||||
seedStore(useSettingsStore, {
|
||||
settings: { time_format: '24h', temperature_unit: 'celsius', day_date_first: dayDateFirst },
|
||||
@@ -34,14 +14,7 @@ function settings(dayDateFirst: boolean) {
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
resetAllStores();
|
||||
vi.clearAllMocks();
|
||||
server.use(
|
||||
http.get('/api/weather/detailed', () => HttpResponse.json({ error: true })),
|
||||
http.get('/api/trips/1/accommodations', () => HttpResponse.json({ accommodations: [] }))
|
||||
);
|
||||
seedStore(useAuthStore, { user: buildAdmin(), isAuthenticated: true });
|
||||
seedStore(useTripStore, { trip: buildTrip({ id: 1 }) });
|
||||
resetDayDetailPanel();
|
||||
});
|
||||
|
||||
describe('DayDetailPanel with the date first', () => {
|
||||
|
||||
@@ -5,43 +5,17 @@ import userEvent from '@testing-library/user-event';
|
||||
import { http, HttpResponse } from 'msw';
|
||||
import { server } from '../../../tests/helpers/msw/server';
|
||||
import { useAuthStore } from '../../store/authStore';
|
||||
import { useTripStore } from '../../store/tripStore';
|
||||
import { useSettingsStore } from '../../store/settingsStore';
|
||||
import { usePermissionsStore } from '../../store/permissionsStore';
|
||||
import { usePluginStore } from '../../store/pluginStore';
|
||||
import { resetAllStores, seedStore } from '../../../tests/helpers/store';
|
||||
import { buildUser, buildAdmin, buildTrip, buildDay, buildPlace, buildReservation } from '../../../tests/helpers/factories';
|
||||
import { seedStore } from '../../../tests/helpers/store';
|
||||
import { buildUser, buildAdmin, buildDay, buildPlace, buildReservation } from '../../../tests/helpers/factories';
|
||||
import { dayDetailDay as day, dayDetailProps as defaultProps, resetDayDetailPanel } from '../../../tests/helpers/dayDetailPanel';
|
||||
import DayDetailPanel from './DayDetailPanel';
|
||||
import { isBlurred } from '../../../tests/helpers/bookingCodeBlur';
|
||||
|
||||
const day = buildDay({ id: 1, trip_id: 1, date: '2025-06-15', title: 'Day in Paris' });
|
||||
|
||||
const defaultProps = {
|
||||
day,
|
||||
days: [day],
|
||||
places: [],
|
||||
categories: [],
|
||||
tripId: 1,
|
||||
assignments: {},
|
||||
reservations: [],
|
||||
lat: null,
|
||||
lng: null,
|
||||
onClose: vi.fn(),
|
||||
onAccommodationChange: vi.fn(),
|
||||
};
|
||||
|
||||
beforeEach(() => {
|
||||
resetAllStores();
|
||||
vi.clearAllMocks();
|
||||
server.use(
|
||||
http.get('/api/weather/detailed', () => HttpResponse.json({ error: true })),
|
||||
http.get('/api/trips/1/accommodations', () => HttpResponse.json({ accommodations: [] })),
|
||||
);
|
||||
seedStore(useAuthStore, { user: buildAdmin(), isAuthenticated: true });
|
||||
seedStore(useTripStore, { trip: buildTrip({ id: 1 }) });
|
||||
seedStore(useSettingsStore, {
|
||||
settings: { time_format: '24h', temperature_unit: 'celsius', blur_booking_codes: false },
|
||||
});
|
||||
resetDayDetailPanel({ time_format: '24h', temperature_unit: 'celsius', blur_booking_codes: false });
|
||||
});
|
||||
|
||||
/** The stay picker filters by category through a pill that opens its list; this picks one entry of it. */
|
||||
@@ -147,13 +121,23 @@ describe('DayDetailPanel', () => {
|
||||
});
|
||||
|
||||
it('FE-PLANNER-DAYDETAIL-009: weather loading state shown briefly', async () => {
|
||||
// The forecast is held until the spinner was seen, then released, so the request
|
||||
// does not stay open past this test.
|
||||
let release!: () => void;
|
||||
const gate = new Promise<void>((resolve) => { release = resolve; });
|
||||
server.use(
|
||||
http.get('/api/weather/detailed', () => new Promise(() => {})), // never resolves
|
||||
http.get('/api/weather/detailed', async () => {
|
||||
await gate;
|
||||
return HttpResponse.json({ error: true });
|
||||
}),
|
||||
);
|
||||
render(<DayDetailPanel {...defaultProps} lat={48.8566} lng={2.3522} />);
|
||||
// The spinner announces itself as a loading status
|
||||
const spinner = await screen.findByRole('status', { name: 'Loading...' });
|
||||
expect(spinner.querySelector('.animate-spin')).not.toBeNull();
|
||||
|
||||
release();
|
||||
expect(await screen.findByText(/No weather/i)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-PLANNER-DAYDETAIL-101: a late forecast for the previous day never replaces the one for the current day', async () => {
|
||||
@@ -1606,14 +1590,14 @@ describe('DayDetailPanel remaining branches', () => {
|
||||
const user = userEvent.setup();
|
||||
const onAccommodationChange = vi.fn();
|
||||
let updateBody: Record<string, unknown> | null = null;
|
||||
let listCalls = 0;
|
||||
// The reload after the save reads the new name; keyed on the save, not on a
|
||||
// count of reads, so a stray read before it cannot rename the stay early.
|
||||
server.use(
|
||||
http.get('/api/trips/1/accommodations', () => {
|
||||
listCalls += 1;
|
||||
return HttpResponse.json({
|
||||
accommodations: [hotel(listCalls > 1 ? { place_name: 'Reloaded Hotel' } : {})],
|
||||
});
|
||||
}),
|
||||
http.get('/api/trips/1/accommodations', () =>
|
||||
HttpResponse.json({
|
||||
accommodations: [hotel(updateBody ? { place_name: 'Reloaded Hotel' } : {})],
|
||||
}),
|
||||
),
|
||||
http.put('/api/trips/1/accommodations/1', async ({ request }) => {
|
||||
updateBody = (await request.json()) as Record<string, unknown>;
|
||||
return HttpResponse.json({ accommodation: hotel() });
|
||||
@@ -1874,25 +1858,40 @@ describe('DayDetailPanel remaining branches, part two', () => {
|
||||
expect(await screen.findByText('15h 20m')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-W5DDP-021: a collapsed untitled day falls back to its position, or to ? when it has none', () => {
|
||||
it('FE-W5DDP-021: a collapsed untitled day falls back to its position, or to ? when it has none', async () => {
|
||||
// Each mount reads the stays; wait for that read to be answered, so it cannot
|
||||
// reach the handler of the test that runs next.
|
||||
let staysRead = 0;
|
||||
server.use(
|
||||
http.get('/api/trips/1/accommodations', () => {
|
||||
staysRead += 1;
|
||||
return HttpResponse.json({ accommodations: [] });
|
||||
}),
|
||||
);
|
||||
const bare = buildDay({ id: 2, trip_id: 1, date: null, title: null });
|
||||
const { unmount } = render(<DayDetailPanel {...defaultProps} day={bare} days={[defaultProps.day, bare]} collapsed />);
|
||||
expect(screen.getByText('Day 2')).toBeInTheDocument();
|
||||
await waitFor(() => expect(staysRead).toBe(1));
|
||||
unmount();
|
||||
|
||||
render(<DayDetailPanel {...defaultProps} day={bare} days={[]} collapsed />);
|
||||
expect(screen.getByText('Day ?')).toBeInTheDocument();
|
||||
await waitFor(() => expect(staysRead).toBe(2));
|
||||
});
|
||||
|
||||
it('FE-W5DDP-020: an empty reload after the edit-save clears the accommodation', async () => {
|
||||
const user = userEvent.setup();
|
||||
let listCalls = 0;
|
||||
// The list empties once the edit is saved, not on a count of reads, so a stray
|
||||
// read before the save cannot empty it early.
|
||||
let saved = false;
|
||||
server.use(
|
||||
http.get('/api/trips/1/accommodations', () => {
|
||||
listCalls += 1;
|
||||
return listCalls === 1 ? HttpResponse.json({ accommodations: [hotel()] }) : HttpResponse.json({});
|
||||
http.get('/api/trips/1/accommodations', () =>
|
||||
saved ? HttpResponse.json({}) : HttpResponse.json({ accommodations: [hotel()] }),
|
||||
),
|
||||
http.put('/api/trips/1/accommodations/1', () => {
|
||||
saved = true;
|
||||
return HttpResponse.json({ accommodation: hotel() });
|
||||
}),
|
||||
http.put('/api/trips/1/accommodations/1', () => HttpResponse.json({ accommodation: hotel() })),
|
||||
);
|
||||
|
||||
render(<DayDetailPanel {...defaultProps} places={[buildPlace({ id: 5, name: 'Grand Hotel' })]} />);
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import React, { useEffect, useRef, useId, type ReactNode } from 'react'
|
||||
import React, { useEffect, useRef, useId, type ReactNode, type Ref } from 'react'
|
||||
import { X, CloudRain, Wind, Droplets, Sunrise, Sunset, Hotel, Calendar, MapPin, LogIn, LogOut, Pencil, ChevronsDown, ChevronsUp, ArrowRight, Check, Moon, type LucideIcon } from 'lucide-react'
|
||||
import type { WeatherResult } from '@trek/shared'
|
||||
import { usePluginViewContributions, PluginCardFooter } from '../Plugins/PluginContributions'
|
||||
@@ -53,6 +53,8 @@ interface DayDetailPanelProps {
|
||||
onAccommodationChange: () => void
|
||||
leftWidth?: number
|
||||
rightWidth?: number
|
||||
rightGap?: number
|
||||
panelRef?: Ref<HTMLDivElement>
|
||||
collapsed?: boolean
|
||||
onToggleCollapse?: () => void
|
||||
mobile?: boolean
|
||||
@@ -73,7 +75,7 @@ interface DayDetailPanelProps {
|
||||
* head band that folds the card away, then the weather, the bookings of the
|
||||
* day and where the night is spent, each under its own label.
|
||||
*/
|
||||
export default function DayDetailPanel({ day, days, places, categories = [], tripId, assignments, reservations = [], lat, lng, onClose, onAccommodationChange, leftWidth = 0, rightWidth = 0, collapsed: collapsedProp = false, onToggleCollapse, mobile = false, onUpdateDayTitle, weatherPlaceName = null, openStayPicker = false, onStayPickerOpened, onOpenBooking }: DayDetailPanelProps) {
|
||||
export default function DayDetailPanel({ day, days, places, categories = [], tripId, assignments, reservations = [], lat, lng, onClose, onAccommodationChange, leftWidth = 0, rightWidth = 0, rightGap, panelRef, collapsed: collapsedProp = false, onToggleCollapse, mobile = false, onUpdateDayTitle, weatherPlaceName = null, openStayPicker = false, onStayPickerOpened, onOpenBooking }: DayDetailPanelProps) {
|
||||
const { t, language } = useTranslation()
|
||||
const can = useCanDo()
|
||||
const toast = useToast()
|
||||
@@ -184,10 +186,10 @@ export default function DayDetailPanel({ day, days, places, categories = [], tri
|
||||
setShowHotelPicker('edit')
|
||||
}
|
||||
const removeAccommodation = (acc: Accommodation) => { handleRemoveAccommodation(acc).catch(showError) }
|
||||
const mapCard = centredMapCard(leftWidth, rightWidth, { extent: '100vw', clearPill: !mobile })
|
||||
const mapCard = centredMapCard(leftWidth, rightWidth, { extent: '100vw', clearPill: !mobile, rightGap })
|
||||
|
||||
return (
|
||||
<div className="fixed z-50" style={{ bottom: 'calc(var(--bottom-nav-h) + 20px)', left: mapCard.centre, transform: 'translateX(-50%)', width: mapCard.width, ...(mobile ? { zIndex: 10000 } : null), fontFamily: 'var(--font-system)' }}>
|
||||
<div ref={panelRef} className="fixed z-50" style={{ bottom: 'calc(var(--bottom-nav-h) + 20px)', left: mapCard.centre, transform: 'translateX(-50%)', width: mapCard.width, ...(mobile ? { zIndex: 10000 } : null), fontFamily: 'var(--font-system)' }}>
|
||||
<div ref={cardRef}
|
||||
className="flex flex-col overflow-hidden rounded-[20px] border border-edge-faint bg-surface-elevated shadow-popover backdrop-blur-[40px] backdrop-saturate-[1.8]"
|
||||
style={{ maxHeight: collapsed ? 'none' : '60vh' }}>
|
||||
|
||||
@@ -158,6 +158,18 @@ function dayHeader(title: string) {
|
||||
}
|
||||
|
||||
describe('DayPlanSidebar day header', () => {
|
||||
it('opens the selected day details while the whole-trip overview is active', async () => {
|
||||
const user = userEvent.setup();
|
||||
const day = buildDay({ id: 10, date: '2025-06-01', title: 'My Day' });
|
||||
const props = makeDefaultProps({ days: [day], selectedDayId: day.id });
|
||||
render(<DayPlanSidebar {...props} openSelectedDayDetail />);
|
||||
|
||||
await user.click(screen.getByText('My Day'));
|
||||
|
||||
expect(props.onSelectDay).toHaveBeenCalledWith(day.id);
|
||||
expect(props.onDayDetail).toHaveBeenCalledWith(day);
|
||||
});
|
||||
|
||||
it('FE-PLANNER-DAYPLAN-176: a transfer day lists the check-out hotel before the check-in one', async () => {
|
||||
const user = userEvent.setup();
|
||||
const days = [
|
||||
|
||||
@@ -585,3 +585,87 @@ describe('DayPlanSidebar, public transit between two city walks (CW-08)', () =>
|
||||
expect(screen.getByTestId('tour-day-overrun')).toHaveTextContent('Ends at 14:00, after Harbour starts at 13:00');
|
||||
});
|
||||
});
|
||||
|
||||
// The walk from a train's arrival to the night's hotel: no stop is at either end, so
|
||||
// there is no mode to change, and the desktop left it inert. The transit search is
|
||||
// what can be planned for it, as for every other leg.
|
||||
describe('DayPlanSidebar, public transit from a booking arrival to the hotel', () => {
|
||||
it('FE-PLANNER-DAYPLAN-171f: the walk from a train arrival to the hotel, which no stop owns, offers public transport', async () => {
|
||||
const user = userEvent.setup();
|
||||
const onPlanTransitLeg = vi.fn();
|
||||
const days = [
|
||||
buildDay({ id: 10, date: '2025-06-01', title: 'Day 1' }),
|
||||
buildDay({ id: 11, date: '2025-06-02', title: 'Day 2' }),
|
||||
buildDay({ id: 12, date: '2025-06-03', title: 'Day 3' }),
|
||||
];
|
||||
const accommodations = [
|
||||
{
|
||||
id: 1,
|
||||
trip_id: 1,
|
||||
start_day_id: 10,
|
||||
end_day_id: 12,
|
||||
place_lat: 47.5,
|
||||
place_lng: 19.05,
|
||||
place_name: 'Basilica apARTment',
|
||||
},
|
||||
];
|
||||
const train = buildReservation({
|
||||
id: 430,
|
||||
type: 'train',
|
||||
title: 'Wien => Budapest',
|
||||
day_id: 11,
|
||||
end_day_id: 11,
|
||||
day_plan_position: 5,
|
||||
reservation_time: '2025-06-02T16:42:00',
|
||||
reservation_end_time: '2025-06-02T19:29:00',
|
||||
endpoints: [
|
||||
{
|
||||
role: 'from',
|
||||
sequence: 0,
|
||||
name: 'Wien Hbf',
|
||||
code: null,
|
||||
lat: 48.18,
|
||||
lng: 16.37,
|
||||
timezone: null,
|
||||
local_date: null,
|
||||
local_time: null,
|
||||
},
|
||||
{
|
||||
role: 'to',
|
||||
sequence: 1,
|
||||
name: 'Budapest Keleti',
|
||||
code: null,
|
||||
lat: 47.5,
|
||||
lng: 19.08,
|
||||
timezone: null,
|
||||
local_date: null,
|
||||
local_time: null,
|
||||
},
|
||||
],
|
||||
});
|
||||
const albertina = buildPlace({ id: 1, name: 'Albertina', place_time: '12:00', lat: 48.2, lng: 16.37 });
|
||||
render(
|
||||
<DayPlanSidebar
|
||||
{...makeDefaultProps({
|
||||
days,
|
||||
assignments: { '11': [buildAssignment({ id: 11, day_id: 11, order_index: 0, place: albertina })] },
|
||||
accommodations,
|
||||
reservations: [train],
|
||||
selectedDayId: 11,
|
||||
routeShown: true,
|
||||
onPlanTransitLeg,
|
||||
})}
|
||||
/>
|
||||
);
|
||||
await user.click(await screen.findByLabelText('Public transit'));
|
||||
expect(contextMenu().queryByRole('button', { name: 'Driving' })).not.toBeInTheDocument();
|
||||
await user.click(contextMenu().getByRole('button', { name: 'Public transit' }));
|
||||
expect(onPlanTransitLeg).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
dayId: 11,
|
||||
from: expect.objectContaining({ lat: 47.5, lng: 19.08 }),
|
||||
to: { name: 'Basilica apARTment', lat: 47.5, lng: 19.05 },
|
||||
})
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -69,7 +69,7 @@ import { findTodayDayId } from './today'
|
||||
import { markdownLinkComponents } from '../shared/markdownLink'
|
||||
import { RouteConnector, HotelRouteConnector } from './DayPlanSidebarRouteConnector'
|
||||
import { resolveLegMode } from './legMode'
|
||||
import { useLegModeActions } from './useLegModeActions'
|
||||
import { transitOnlyMenuItems, useLegModeActions } from './useLegModeActions'
|
||||
import { dayExportStops, fillAroundLocked } from './dayRoute'
|
||||
import { projectDayItinerary, projectedById, type TourStageStops } from '../Map/dayTourProjection'
|
||||
import type { DayRoutePoint } from '../Map/dayRoutePlan'
|
||||
@@ -104,6 +104,7 @@ export interface DayPlanSidebarProps {
|
||||
categories: Category[]
|
||||
assignments: AssignmentsMap
|
||||
selectedDayId: number | null
|
||||
openSelectedDayDetail?: boolean
|
||||
selectedPlaceId: number | null
|
||||
selectedAssignmentId: number | null
|
||||
onSelectDay: (dayId: number | null, skipFit?: boolean) => void
|
||||
@@ -1413,6 +1414,27 @@ const DayPlanSidebar = React.memo(function DayPlanSidebar(props: DayPlanSidebarP
|
||||
} as unknown as React.MouseEvent)
|
||||
}
|
||||
|
||||
// A hotel bookend leg opens the mode menu of the stop that owns it, the first stop's
|
||||
// incoming mode at the top and the last stop's outgoing mode at the bottom. One no
|
||||
// stop owns, a booking's arrival to the hotel, can only have transit planned.
|
||||
const hotelLegRow = (dayId: number, leg: { seg: RouteSegment; name: string; targetId?: number }, placement: 'top' | 'bottom') => {
|
||||
const connector = <HotelRouteConnector seg={leg.seg} name={leg.name} profile={routeProfile} placement={placement} />
|
||||
const targetId = leg.targetId
|
||||
const planTransit = targetId == null ? transitLegPlanner(dayId, leg.seg) : undefined
|
||||
const open = targetId != null
|
||||
? (e: React.MouseEvent) => (placement === 'top' ? openIncomingLegModeMenu : openLegModeMenu)(e, targetId, dayId, leg.seg)
|
||||
: planTransit && ((e: React.MouseEvent) => ctxMenu.open(e, transitOnlyMenuItems(planTransit, t)))
|
||||
if (!canEditDays || !open) return connector
|
||||
const label = targetId != null ? t('dayplan.transportMode.change') : t('transit.title')
|
||||
return (
|
||||
<Tooltip label={label} placement="top">
|
||||
<div role="button" tabIndex={0} onClick={open} onKeyDown={e => openLegMenuByKey(e, open)} style={{ cursor: 'pointer' }} aria-label={label}>
|
||||
{connector}
|
||||
</div>
|
||||
</Tooltip>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
// Sized as a flex child as well as by height: the desktop panel puts the Days / Road
|
||||
// trip switch above this, and at height 100% alone the list ran the switch's height
|
||||
@@ -1459,12 +1481,11 @@ const DayPlanSidebar = React.memo(function DayPlanSidebar(props: DayPlanSidebarP
|
||||
<div className={`scroll-container flex flex-col gap-2 p-2${hasDragged ? '' : ' trek-stagger'}`} style={{ flex: 1, overflowY: 'auto', minHeight: 0 }} ref={scrollContainerRef} onScroll={(e) => onScrollTopChange?.((e.currentTarget as HTMLElement).scrollTop)}>
|
||||
{days.map((day, index) => {
|
||||
const isSelected = selectedDayId === day.id
|
||||
// Shared by the click and the key handler so the two can never drift
|
||||
// apart — pressing Enter on the row has to toggle, not just select.
|
||||
// Named for the selection, not the expand/collapse `toggleDay` above.
|
||||
// An already-selected day can reopen its details from the overview.
|
||||
const toggleDaySelection = () => {
|
||||
if (isSelected) { onSelectDay(null); if (onDayDetail) onDayDetail(null) }
|
||||
else { onSelectDay(day.id); if (onDayDetail) onDayDetail(day) }
|
||||
const dayToOpen = isSelected && !props.openSelectedDayDetail ? null : day
|
||||
onSelectDay(dayToOpen?.id ?? null)
|
||||
onDayDetail?.(dayToOpen)
|
||||
}
|
||||
const isExpanded = expandedDays.has(day.id)
|
||||
const da = getDayAssignments(day.id)
|
||||
@@ -1734,17 +1755,7 @@ const DayPlanSidebar = React.memo(function DayPlanSidebar(props: DayPlanSidebarP
|
||||
dropAfterLastItem(day.id, { assignmentId, noteId })
|
||||
}}
|
||||
>
|
||||
{hotelLegs[day.id]?.top && (() => {
|
||||
const targetId = hotelLegs[day.id]?.top?.targetId
|
||||
const connector = <HotelRouteConnector seg={hotelLegs[day.id]!.top!.seg} name={hotelLegs[day.id]!.top!.name} profile={routeProfile} placement="top" />
|
||||
return canEditDays && targetId != null ? (
|
||||
<Tooltip label={t('dayplan.transportMode.change')} placement="top">
|
||||
<div role="button" tabIndex={0} onClick={e => openIncomingLegModeMenu(e, targetId, day.id, hotelLegs[day.id]!.top!.seg)} onKeyDown={e => openLegMenuByKey(e, m => openIncomingLegModeMenu(m, targetId, day.id, hotelLegs[day.id]!.top!.seg))} style={{ cursor: 'pointer' }} aria-label={t('dayplan.transportMode.change')}>
|
||||
{connector}
|
||||
</div>
|
||||
</Tooltip>
|
||||
) : connector
|
||||
})()}
|
||||
{hotelLegs[day.id]?.top && hotelLegRow(day.id, hotelLegs[day.id]!.top!, 'top')}
|
||||
{daySchedule.byPosition[day.id]?.start.map(si => <PluginDayScheduleRow key={`${si.pluginId}:${si.id}`} item={si} />)}
|
||||
{visibleCount === 0 && !dayNoteUi ? (
|
||||
<div
|
||||
@@ -2477,17 +2488,7 @@ const DayPlanSidebar = React.memo(function DayPlanSidebar(props: DayPlanSidebarP
|
||||
})
|
||||
)}
|
||||
{daySchedule.byPosition[day.id]?.end.map(si => <PluginDayScheduleRow key={`${si.pluginId}:${si.id}`} item={si} />)}
|
||||
{hotelLegs[day.id]?.bottom && (() => {
|
||||
const targetId = hotelLegs[day.id]?.bottom?.targetId
|
||||
const connector = <HotelRouteConnector seg={hotelLegs[day.id]!.bottom!.seg} name={hotelLegs[day.id]!.bottom!.name} profile={routeProfile} placement="bottom" />
|
||||
return canEditDays && targetId != null ? (
|
||||
<Tooltip label={t('dayplan.transportMode.change')} placement="top">
|
||||
<div role="button" tabIndex={0} onClick={e => openLegModeMenu(e, targetId, day.id, hotelLegs[day.id]!.bottom!.seg)} onKeyDown={e => openLegMenuByKey(e, m => openLegModeMenu(m, targetId, day.id, hotelLegs[day.id]!.bottom!.seg))} style={{ cursor: 'pointer' }} aria-label={t('dayplan.transportMode.change')}>
|
||||
{connector}
|
||||
</div>
|
||||
</Tooltip>
|
||||
) : connector
|
||||
})()}
|
||||
{hotelLegs[day.id]?.bottom && hotelLegRow(day.id, hotelLegs[day.id]!.bottom!, 'bottom')}
|
||||
<AssistantDayPreview tripId={tripId} dayId={day.id} />{/* The assistant's waiting changes, then the drop zone at the list end */}
|
||||
<div
|
||||
style={{ minHeight: 12, padding: '2px 8px' }}
|
||||
|
||||
@@ -15,6 +15,7 @@ import {
|
||||
displayTitle,
|
||||
groupReservations,
|
||||
groupTransports,
|
||||
hasPassed,
|
||||
onTravelers,
|
||||
parseMeta,
|
||||
phaseOf,
|
||||
@@ -394,4 +395,48 @@ describe('onTravelers and the shared type colours', () => {
|
||||
expect(groups.transit.map(r => r.id)).toEqual([1]);
|
||||
expect(sortReservations([later, transit, open, sooner], days, 'date', 'asc', label).map(r => r.id)).toEqual([1, 3, 2, 4]);
|
||||
});
|
||||
|
||||
it('FE-PLANNER-BKMODEL-044: hasPassed reads the end, else the start, in local wall-clock time', () => {
|
||||
const now = new Date(2025, 5, 2, 12, 0);
|
||||
expect(hasPassed(buildReservation({ reservation_time: '2025-06-02T11:00' }), now)).toBe(true);
|
||||
expect(hasPassed(buildReservation({ reservation_time: '2025-06-02T13:00' }), now)).toBe(false);
|
||||
// The end counts: a flight that left in the morning and lands this afternoon is not over.
|
||||
expect(hasPassed(buildReservation({ reservation_time: '2025-06-02T08:00', reservation_end_time: '2025-06-02T15:00' }), now)).toBe(false);
|
||||
// An end time without a date is on the start's day.
|
||||
expect(hasPassed(buildReservation({ reservation_time: '2025-06-02T08:00', reservation_end_time: '11:30' }), now)).toBe(true);
|
||||
// A date without a time lasts until the day is over.
|
||||
expect(hasPassed(buildReservation({ reservation_time: '2025-06-02' }), now)).toBe(false);
|
||||
expect(hasPassed(buildReservation({ reservation_time: '2025-06-01' }), now)).toBe(true);
|
||||
// Without any date nothing says it is over.
|
||||
expect(hasPassed(buildReservation({ reservation_time: null, day_id: null }), now)).toBe(false);
|
||||
});
|
||||
|
||||
it('FE-PLANNER-BKMODEL-045: groupTransports moves what is over into past, latest first, only when given the time', () => {
|
||||
const early = buildReservation({ id: 1, type: 'train', status: 'confirmed', reservation_time: '2025-06-01T09:00' });
|
||||
const lastNight = buildReservation({ id: 2, type: 'transit', status: 'pending', reservation_time: '2025-06-01T21:00' });
|
||||
const ahead = buildReservation({ id: 3, type: 'bus', status: 'confirmed', reservation_time: '2025-06-03T09:00' });
|
||||
const now = new Date(2025, 5, 2, 12, 0);
|
||||
const groups = groupTransports([ahead, early, lastNight], days, now);
|
||||
expect(groups.confirmed.map(r => r.id)).toEqual([3]);
|
||||
expect(groups.transit).toEqual([]);
|
||||
expect(groups.past.map(r => r.id)).toEqual([2, 1]);
|
||||
expect(groupTransports([ahead, early, lastNight], days).past).toEqual([]);
|
||||
});
|
||||
|
||||
it('FE-PLANNER-BKMODEL-046: hasPassed takes the linked days when a booking carries no date of its own', () => {
|
||||
const now = new Date(2025, 5, 3, 12, 0);
|
||||
const hotel = buildReservation({ id: 1, type: 'hotel', status: 'confirmed', reservation_time: null, reservation_end_time: null, accommodation_start_day_id: 501, accommodation_end_day_id: 502 });
|
||||
const stillThere = buildReservation({ id: 2, type: 'hotel', status: 'confirmed', reservation_time: null, reservation_end_time: null, accommodation_start_day_id: 502, accommodation_end_day_id: 503 });
|
||||
const train = buildReservation({ id: 3, type: 'train', status: 'confirmed', reservation_time: '09:00', reservation_end_time: '11:00', day_id: 503 });
|
||||
const lateTrain = buildReservation({ id: 4, type: 'train', status: 'confirmed', reservation_time: '13:00', day_id: 503 });
|
||||
const overnight = buildReservation({ id: 5, type: 'bus', status: 'confirmed', reservation_time: '22:00', reservation_end_time: '06:00', day_id: 502, end_day_id: 503 });
|
||||
expect(hasPassed(hotel, now, days)).toBe(true);
|
||||
expect(hasPassed(stillThere, now, days)).toBe(false);
|
||||
expect(hasPassed(train, now, days)).toBe(true);
|
||||
expect(hasPassed(lateTrain, now, days)).toBe(false);
|
||||
expect(hasPassed(overnight, now, days)).toBe(true);
|
||||
const groups = groupTransports([hotel, stillThere, train, lateTrain, overnight], days, now);
|
||||
expect(groups.past.map(r => r.id)).toEqual([3, 5, 1]);
|
||||
expect(groups.confirmed.map(r => r.id)).toEqual([2, 4]);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -252,21 +252,49 @@ export interface StatusGroups {
|
||||
confirmed: Reservation[]
|
||||
pending: Reservation[]
|
||||
transit: Reservation[]
|
||||
/** What is over already (#3156), latest first; empty unless the caller passes the time. */
|
||||
past: Reservation[]
|
||||
}
|
||||
|
||||
/**
|
||||
* The phone tabs' three sections, each in date order: confirmed and pending, and
|
||||
* Whether a booking is over: its end, or its start where it has none, lies
|
||||
* before `now`. The times are local wall-clock values, as everywhere a booking
|
||||
* is read. An end time without a date is on the start's day, and a date
|
||||
* without a time counts until that day is over. A booking that carries no date
|
||||
* of its own takes them from bookingDates, so a hotel ends on its stay's last
|
||||
* day and a day-linked transport on its day. Without any date it is never over.
|
||||
*/
|
||||
export function hasPassed(r: Reservation, now: Date, days: Day[] = []): boolean {
|
||||
const start = splitReservationDateTime(r.reservation_time)
|
||||
const end = r.reservation_end_time ? splitReservationDateTime(r.reservation_end_time) : null
|
||||
const own = end?.date || start.date
|
||||
const linked = own ? null : bookingDates(r, days)
|
||||
const endDate = own ? end?.date : linked?.end
|
||||
const date = endDate || (own ? start.date : linked?.start)
|
||||
if (!date) return false
|
||||
const time = endDate || end?.time ? (end?.time ?? null) : start.time
|
||||
const [y, m, d] = date.split('-').map(Number)
|
||||
const [hh, mm] = time ? time.split(':').map(Number) : [23, 59]
|
||||
return new Date(y, m - 1, d, hh, mm) < now
|
||||
}
|
||||
|
||||
/**
|
||||
* The phone tabs' sections, each in date order: confirmed and pending, and
|
||||
* transit (automated public transport, #1065) on its own whatever its status.
|
||||
* A booking type never matches `transit`, so the split fits the bookings tab too.
|
||||
* Given the time, what is over leaves those and stands in `past` (#3156).
|
||||
*/
|
||||
export function groupTransports(list: Reservation[], days: Day[]): StatusGroups {
|
||||
export function groupTransports(list: Reservation[], days: Day[], now?: Date): StatusGroups {
|
||||
const sorted = sortReservations(list, days, 'date', 'asc', () => '')
|
||||
const transit = sorted.filter(r => r.type === 'transit')
|
||||
const nonTransit = sorted.filter(r => r.type !== 'transit')
|
||||
const isPast = (r: Reservation) => !!now && hasPassed(r, now, days)
|
||||
const current = sorted.filter(r => !isPast(r))
|
||||
const transit = current.filter(r => r.type === 'transit')
|
||||
const nonTransit = current.filter(r => r.type !== 'transit')
|
||||
return {
|
||||
confirmed: nonTransit.filter(r => r.status === 'confirmed'),
|
||||
pending: nonTransit.filter(r => r.status !== 'confirmed'),
|
||||
transit,
|
||||
past: sorted.filter(isPast).reverse(),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
// FE-PLANNER-RESLISTFILTER-001 to -004: the traveller filter and folded sections
|
||||
// FE-PLANNER-RESLISTFILTER-001 to -005: the traveller filter and folded sections
|
||||
// of the phone's bookings and transports tabs.
|
||||
import { act, renderHook } from '@testing-library/react';
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
|
||||
import { buildDay, buildReservation } from '../../../../tests/helpers/factories';
|
||||
import type { Reservation } from '../../../types';
|
||||
@@ -24,6 +24,14 @@ const bob = buildReservation({
|
||||
const ride = buildReservation({ id: 12, type: 'transit', status: 'confirmed', reservation_time: '2026-03-01T07:00' });
|
||||
const ALL = [ann, bob, ride];
|
||||
|
||||
// The day before the trip: every booking above is still ahead.
|
||||
beforeEach(() => {
|
||||
vi.useFakeTimers({ toFake: ['Date'], now: new Date(2026, 1, 28, 12, 0) });
|
||||
});
|
||||
afterEach(() => {
|
||||
vi.useRealTimers();
|
||||
});
|
||||
|
||||
describe('useReservationListFilter', () => {
|
||||
it('FE-PLANNER-RESLISTFILTER-001: without a filter every booking lands in its status section', () => {
|
||||
const { result } = renderHook(() => useReservationListFilter(ALL, days, 2));
|
||||
@@ -37,7 +45,7 @@ describe('useReservationListFilter', () => {
|
||||
const { result } = renderHook(() => useReservationListFilter(ALL, days, 2));
|
||||
act(() => result.current.toggleTravelerFilter(2));
|
||||
expect([...result.current.travelerFilter]).toEqual([2]);
|
||||
expect(result.current.groups).toEqual({ confirmed: [], pending: [bob], transit: [] });
|
||||
expect(result.current.groups).toEqual({ confirmed: [], pending: [bob], transit: [], past: [] });
|
||||
|
||||
act(() => result.current.toggleTravelerFilter(1));
|
||||
expect(result.current.groups.confirmed.map((r) => r.id)).toEqual([10]);
|
||||
@@ -58,9 +66,24 @@ describe('useReservationListFilter', () => {
|
||||
it('FE-PLANNER-RESLISTFILTER-004: a section folds and unfolds on its own', () => {
|
||||
const { result } = renderHook(() => useReservationListFilter(ALL, days, 2));
|
||||
act(() => result.current.toggleSection('pending'));
|
||||
expect(result.current.collapsed).toEqual({ pending: true });
|
||||
expect(result.current.collapsed).toEqual({ pending: true, past: true });
|
||||
act(() => result.current.toggleSection('confirmed'));
|
||||
act(() => result.current.toggleSection('pending'));
|
||||
expect(result.current.collapsed).toEqual({ pending: false, confirmed: true });
|
||||
expect(result.current.collapsed).toEqual({ pending: false, confirmed: true, past: true });
|
||||
});
|
||||
|
||||
it('FE-PLANNER-RESLISTFILTER-005: what is over goes to Past, folded while something is ahead and open once all is over', () => {
|
||||
vi.setSystemTime(new Date(2026, 2, 1, 12, 0));
|
||||
const midTrip = renderHook(() => useReservationListFilter(ALL, days, 2)).result;
|
||||
expect(midTrip.current.groups.past.map((r) => r.id)).toEqual([11, 12]);
|
||||
expect(midTrip.current.groups.confirmed.map((r) => r.id)).toEqual([10]);
|
||||
expect(midTrip.current.collapsed.past).toBe(true);
|
||||
act(() => midTrip.current.toggleSection('past'));
|
||||
expect(midTrip.current.collapsed.past).toBe(false);
|
||||
|
||||
vi.setSystemTime(new Date(2026, 2, 3, 12, 0));
|
||||
const afterTrip = renderHook(() => useReservationListFilter(ALL, days, 2)).result;
|
||||
expect(afterTrip.current.groups.past.map((r) => r.id)).toEqual([10, 11, 12]);
|
||||
expect(afterTrip.current.collapsed.past).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,7 +1,20 @@
|
||||
import { useState } from 'react';
|
||||
|
||||
import type { Day, Reservation } from '../../../types';
|
||||
import { groupTransports, onTravelers } from './bookingsModel';
|
||||
import { groupTransports, onTravelers, type StatusGroups } from './bookingsModel';
|
||||
|
||||
/**
|
||||
* The status sections both tabs list, in their order, leaving out the empty ones.
|
||||
* Bookings never fill `transit`, so that section only ever shows among transports.
|
||||
*/
|
||||
export function listSections(groups: StatusGroups, t: (key: string) => string) {
|
||||
return [
|
||||
{ id: 'confirmed', label: t('reservations.confirmed'), rows: groups.confirmed },
|
||||
{ id: 'pending', label: t('reservations.pending'), rows: groups.pending },
|
||||
{ id: 'transit', label: t('reservations.type.transit'), rows: groups.transit },
|
||||
{ id: 'past', label: t('reservations.past'), rows: groups.past },
|
||||
].filter((s) => s.rows.length > 0);
|
||||
}
|
||||
|
||||
/**
|
||||
* The traveller filter and the folded sections of the phone's bookings and
|
||||
@@ -15,9 +28,13 @@ import { groupTransports, onTravelers } from './bookingsModel';
|
||||
*/
|
||||
export function useReservationListFilter(all: Reservation[], days: Day[], memberCount: number) {
|
||||
const [travelerFilter, setTravelerFilter] = useState<Set<number>>(new Set());
|
||||
// The moment the tab opened: what was over by then moves into the folded Past
|
||||
// section (#3156). Taken once, so a list does not reshuffle while it is read.
|
||||
const [now] = useState(() => new Date());
|
||||
const groups = groupTransports(
|
||||
all.filter((r) => onTravelers(r, travelerFilter)),
|
||||
days
|
||||
days,
|
||||
now
|
||||
);
|
||||
const showTravelerFilter = memberCount > 1 && all.some((r) => (r.travelers || []).length > 0);
|
||||
const toggleTravelerFilter = (id: number) =>
|
||||
@@ -29,8 +46,12 @@ export function useReservationListFilter(all: Reservation[], days: Day[], member
|
||||
});
|
||||
const clearTravelerFilter = () => setTravelerFilter(new Set());
|
||||
|
||||
const [collapsed, setCollapsed] = useState<Record<string, boolean>>({});
|
||||
const toggleSection = (id: string) => setCollapsed((c) => ({ ...c, [id]: !c[id] }));
|
||||
const [folded, setFolded] = useState<Record<string, boolean>>({});
|
||||
// Past starts folded while something is still ahead, since mid-trip that is
|
||||
// what counts; once the whole trip is over it opens, to look back on.
|
||||
const ahead = groups.confirmed.length + groups.pending.length + groups.transit.length > 0;
|
||||
const collapsed: Record<string, boolean> = { ...folded, past: folded.past ?? ahead };
|
||||
const toggleSection = (id: string) => setFolded((c) => ({ ...c, [id]: !collapsed[id] }));
|
||||
|
||||
return {
|
||||
travelerFilter,
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
import type { BookingImportPreviewItem } from '@trek/shared';
|
||||
import { describe, expect, it } from 'vitest';
|
||||
|
||||
import { parsedItemToDraft } from './parsedItemToDraft';
|
||||
|
||||
const item = (metadata?: Record<string, unknown>): BookingImportPreviewItem => ({
|
||||
type: 'flight',
|
||||
title: 'Kuala Lumpur to Bangkok',
|
||||
metadata,
|
||||
source: { fileName: 'airasia.eml', index: 0 },
|
||||
});
|
||||
|
||||
describe('parsedItemToDraft', () => {
|
||||
// #3238: the review form opens with the status the document states.
|
||||
it('FE-PARSED-DRAFT-001: a booking the document calls confirmed opens confirmed, anything else pending', () => {
|
||||
expect(parsedItemToDraft(item({ reservationStatus: 'confirmed' })).status).toBe('confirmed');
|
||||
expect(parsedItemToDraft(item({ reservationStatus: 'cancelled' })).status).toBe('pending');
|
||||
expect(parsedItemToDraft(item({ reservationStatus: 'pending' })).status).toBe('pending');
|
||||
expect(parsedItemToDraft(item()).status).toBe('pending');
|
||||
});
|
||||
});
|
||||
@@ -1,4 +1,4 @@
|
||||
import type { BookingImportPreviewItem, Reservation, ReservationEndpoint } from '@trek/shared'
|
||||
import { importedReservationStatus, type BookingImportPreviewItem, type Reservation, type ReservationEndpoint } from '@trek/shared'
|
||||
|
||||
/**
|
||||
* A pre-fill draft for the reservation/transport edit modals built from a parsed
|
||||
@@ -29,7 +29,8 @@ export function parsedItemToDraft(item: BookingImportPreviewItem): BookingReview
|
||||
return {
|
||||
type: item.type,
|
||||
title: item.title,
|
||||
status: 'pending',
|
||||
// Confirmed when the document said so, pending otherwise (#3238).
|
||||
status: importedReservationStatus(item.metadata),
|
||||
reservation_time: item.reservation_time ?? null,
|
||||
reservation_end_time: item.reservation_end_time ?? null,
|
||||
location: item.location ?? item._venue?.address ?? item._venue?.name ?? null,
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
// FE-PLANNER-STOPNUM-001 to -002: the one stop count the map's pins and the plan's rows read (#2584).
|
||||
import { describe, expect, it } from 'vitest';
|
||||
|
||||
import type { Assignment } from '../../types';
|
||||
import { stopNumbersOfDay } from './stopNumbers';
|
||||
|
||||
const stop = (id: number, order_index: number, place: Partial<NonNullable<Assignment['place']>> | null = {}) =>
|
||||
({ id, order_index, place: place && { id: id * 10, ...place } }) as unknown as Assignment;
|
||||
|
||||
describe('stopNumbersOfDay', () => {
|
||||
it('FE-PLANNER-STOPNUM-001: numbers the stops from 1 in their stored order', () => {
|
||||
const numbers = stopNumbersOfDay([stop(3, 2), stop(1, 0), stop(2, 1)]);
|
||||
expect([...numbers.entries()]).toEqual([
|
||||
[1, 1],
|
||||
[2, 2],
|
||||
[3, 3],
|
||||
]);
|
||||
});
|
||||
|
||||
it('FE-PLANNER-STOPNUM-002: passes over service stops and rows without a place', () => {
|
||||
const numbers = stopNumbersOfDay([stop(1, 0), stop(2, 1, { stop_type: 'fuel' }), stop(3, 2, null), stop(4, 3)]);
|
||||
expect(numbers.get(1)).toBe(1);
|
||||
expect(numbers.has(2)).toBe(false);
|
||||
expect(numbers.has(3)).toBe(false);
|
||||
expect(numbers.get(4)).toBe(2);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,22 @@
|
||||
import type { Assignment } from '../../types';
|
||||
import { isServiceStopType } from '../Roadtrip/roadtripModel';
|
||||
|
||||
/**
|
||||
* The number each stop of a day carries, by assignment id: counted from 1 in the
|
||||
* day's stored order. A service stop is passed over rather than counted: the map
|
||||
* draws it without a badge and the rail gives it no number, so a number spent on
|
||||
* it left the pin after a fuel stop wearing "3" where the rail said "2".
|
||||
*
|
||||
* The one count the map's pins and the plan's rows both read (#2584), so the
|
||||
* number beside a stop in the list is the one on its pin.
|
||||
*/
|
||||
export function stopNumbersOfDay(dayAssignments: readonly Assignment[]): Map<number, number> {
|
||||
const numbers = new Map<number, number>();
|
||||
let counted = 0;
|
||||
for (const a of [...dayAssignments].sort((x, y) => x.order_index - y.order_index)) {
|
||||
if (!a.place?.id || isServiceStopType(a.place.stop_type)) continue;
|
||||
counted += 1;
|
||||
numbers.set(a.id, counted);
|
||||
}
|
||||
return numbers;
|
||||
}
|
||||
@@ -34,6 +34,15 @@ export function legModeMenuItems(
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* The menu of a leg no stop owns, a booking's arrival to the night's hotel: nothing
|
||||
* keeps a mode for it, so it follows the day default and only public transit can be
|
||||
* planned for it.
|
||||
*/
|
||||
export function transitOnlyMenuItems(planTransit: () => void, t: Translate): LegModeMenuItem[] {
|
||||
return [{ label: t('transit.title'), icon: TramFront, onClick: planTransit }];
|
||||
}
|
||||
|
||||
export interface LegModeDeps {
|
||||
tripId: number;
|
||||
toast: { error: (message: string) => void };
|
||||
|
||||
@@ -60,6 +60,8 @@ export interface PlaceSearchOptions {
|
||||
* search ends the billing session, and a pick clears the typed-ahead list too.
|
||||
*/
|
||||
variant: 'dialog' | 'sheet';
|
||||
/** What the field starts with, such as a map link shared to the app (#2582). */
|
||||
initialQuery?: string;
|
||||
/** Where the trip is happening: autocomplete is biased to the box, the full search to its centre. */
|
||||
locationBias: LocationBiasBox | undefined;
|
||||
t: ReturnType<typeof useTranslation>['t'];
|
||||
@@ -101,6 +103,7 @@ export function usePlaceSearch({
|
||||
onMapLink,
|
||||
onCoordinates,
|
||||
onResolvingChange,
|
||||
initialQuery,
|
||||
}: PlaceSearchOptions) {
|
||||
const sheet = variant === 'sheet';
|
||||
// Place names in the language the user picked for them, the app's otherwise (#1799).
|
||||
@@ -110,7 +113,7 @@ export function usePlaceSearch({
|
||||
// The same hint autocomplete gets, as a point instead of a box.
|
||||
const biasPoint = pointFromBox(locationBias);
|
||||
|
||||
const [query, setQuery] = useState('');
|
||||
const [query, setQuery] = useState(initialQuery ?? '');
|
||||
const [results, setResults] = useState<MapsSearchRow[]>([]);
|
||||
/** What answered the last full search. Only a fallback: a merged list carries the source per place. */
|
||||
const [searchSource, setSearchSource] = useState('');
|
||||
@@ -265,11 +268,12 @@ export function usePlaceSearch({
|
||||
const pickPlace = (place: MapsPlace, pick?: PlaceSearchPick) =>
|
||||
take(place, pick, sourceLabel(place, pick?.mode === 'search' ? searchSource : ''));
|
||||
|
||||
const runSearch = async (provider?: 'google') => {
|
||||
const runSearch = async (provider?: 'google', text?: string) => {
|
||||
// The retry sends the query the list came from, not the field: the list
|
||||
// stays on screen while the field is edited or cleared, and the line under
|
||||
// it promises the same query.
|
||||
const trimmed = provider ? (searchMetaRef.current?.query ?? '') : query.trim();
|
||||
// it promises the same query. A link shared into an open sheet is searched
|
||||
// as given, before the field shows it.
|
||||
const trimmed = provider ? (searchMetaRef.current?.query ?? '') : (text ?? query).trim();
|
||||
if (!trimmed) return;
|
||||
if (sheet) {
|
||||
setSuggestions([]);
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
// FE-COMP-PLUGIN-USERSET-001 to -012: the per plugin user settings logic both settings shells share.
|
||||
import { act, renderHook, waitFor } from '@testing-library/react';
|
||||
import { locationAt } from '../../../tests/helpers/location';
|
||||
import { pluginsApi, type PluginAction, type PluginUserSettingField } from '../../api/client';
|
||||
import { SECRET_MASK } from './settingsForm';
|
||||
import { usePluginOAuth, usePluginUserSettings } from './usePluginUserSettings';
|
||||
@@ -150,7 +151,7 @@ describe('usePluginOAuth', () => {
|
||||
|
||||
it('FE-COMP-PLUGIN-USERSET-012: a connect hands off to the provider and keeps the button busy', async () => {
|
||||
const realLocation = window.location;
|
||||
const loc = { href: 'http://localhost/settings' };
|
||||
const loc = locationAt('/settings');
|
||||
Object.defineProperty(window, 'location', { writable: true, configurable: true, value: loc });
|
||||
try {
|
||||
vi.spyOn(pluginsApi, 'oauthConnect').mockResolvedValue({
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
// FE-COMP-ACCOUNT-APPS-001 to FE-COMP-ACCOUNT-APPS-002
|
||||
import { http, HttpResponse } from 'msw';
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
import { buildSettings, buildUser } from '../../../tests/helpers/factories';
|
||||
import { server } from '../../../tests/helpers/msw/server';
|
||||
import { render, screen } from '../../../tests/helpers/render';
|
||||
import { resetAllStores, seedStore } from '../../../tests/helpers/store';
|
||||
import { isNativeApp } from '../../native/platform';
|
||||
import { useAuthStore } from '../../store/authStore';
|
||||
import { useSettingsStore } from '../../store/settingsStore';
|
||||
import AccountTab from './AccountTab';
|
||||
|
||||
vi.mock('../../sync/syncTriggers', () => ({ registerSyncTriggers: vi.fn(), unregisterSyncTriggers: vi.fn() }));
|
||||
vi.mock('../../native/platform', async (importOriginal) => ({
|
||||
...(await importOriginal<typeof import('../../native/platform')>()),
|
||||
isNativeApp: vi.fn(() => false),
|
||||
}));
|
||||
|
||||
beforeEach(() => {
|
||||
resetAllStores();
|
||||
server.use(http.get('/api/auth/app-config', () => HttpResponse.json({ version: '5.2.1', mfa_enabled: false })));
|
||||
seedStore(useAuthStore, { user: buildUser({ username: 'testuser', role: 'user' }), isAuthenticated: true });
|
||||
seedStore(useSettingsStore, { settings: buildSettings() });
|
||||
});
|
||||
|
||||
describe('AccountTab app stores', () => {
|
||||
it('FE-COMP-ACCOUNT-APPS-001: in a browser it offers both app stores with their QR codes', () => {
|
||||
render(<AccountTab />);
|
||||
expect(screen.getByText('TREK app')).toBeInTheDocument();
|
||||
expect(screen.getByText('Scan a code with your phone, then connect the app to this server.')).toBeInTheDocument();
|
||||
expect(document.querySelectorAll('a.asc-card')).toHaveLength(2);
|
||||
});
|
||||
|
||||
it('FE-COMP-ACCOUNT-APPS-002: inside the app itself there is nothing to download', () => {
|
||||
vi.mocked(isNativeApp).mockReturnValue(true);
|
||||
render(<AccountTab />);
|
||||
expect(screen.queryByText('TREK app')).toBeNull();
|
||||
expect(document.querySelector('a.asc-card')).toBeNull();
|
||||
vi.mocked(isNativeApp).mockReturnValue(false);
|
||||
});
|
||||
});
|
||||
@@ -1,5 +1,5 @@
|
||||
import React, { useId } from 'react'
|
||||
import { User, Save, Lock, KeyRound, AlertTriangle, Shield, Camera, Trash2, Copy, Download, Printer, ShieldCheck } from 'lucide-react'
|
||||
import { User, Save, Lock, KeyRound, AlertTriangle, Shield, Camera, Trash2, Copy, Download, Printer, ShieldCheck, Smartphone } from 'lucide-react'
|
||||
import { useTranslation } from '../../i18n'
|
||||
import Section from './Section'
|
||||
import PasskeysSection from './PasskeysSection'
|
||||
@@ -12,6 +12,8 @@ import { EditorField, GRID_2, INPUT, PANEL } from '../shared/dialogParts'
|
||||
import { SETTINGS_BUTTON, SETTINGS_BUTTON_DANGER, SETTINGS_BUTTON_PRIMARY, SettingRow, SettingRows, SettingsHint, StatusPill, SettingsColumns } from './settingsKit'
|
||||
import { stripTrailingSlashes, useAccountSettings } from './useAccountSettings'
|
||||
import AccountDemoLock from './AccountDemoLock'
|
||||
import AppStoreCards from '../shared/AppStoreCards'
|
||||
import { isNativeApp } from '../../native/platform'
|
||||
|
||||
/** The small turning ring a button shows while its request is on the way. */
|
||||
const SPINNER = 'h-3.5 w-3.5 flex-none animate-spin rounded-full border-2 border-current border-t-transparent'
|
||||
@@ -366,6 +368,13 @@ export default function AccountTab(): React.ReactElement {
|
||||
|
||||
{/* Passkeys */}
|
||||
<PasskeysSection demoMode={demoMode} />
|
||||
|
||||
{/* Where to get the phone app; inside the app itself there is nothing to fetch. */}
|
||||
{!isNativeApp() && (
|
||||
<Section title={t('settings.apps.title')} icon={Smartphone} hint={t('settings.apps.hint')}>
|
||||
<AppStoreCards />
|
||||
</Section>
|
||||
)}
|
||||
</>}
|
||||
/>
|
||||
</AccountDemoLock>
|
||||
|
||||
@@ -1,10 +1,9 @@
|
||||
// FE-SETTINGS-NATIVE-SERVER-001 to FE-SETTINGS-NATIVE-SERVER-008
|
||||
// FE-SETTINGS-NATIVE-SERVER-001 to FE-SETTINGS-NATIVE-SERVER-006
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { fireEvent, render, screen } from '../../../tests/helpers/render';
|
||||
import MSettingsServer from '../../mobile/screens/settings/MSettingsServer';
|
||||
import { nativeServerHost } from '../../native/platform';
|
||||
import { TrekShell } from '../../native/trekShell';
|
||||
import NativeServerLink from '../../pages/login/NativeServerLink';
|
||||
import NativeServerSection from './NativeServerSection';
|
||||
|
||||
vi.mock('../../native/platform', () => ({ nativeServerHost: vi.fn() }));
|
||||
@@ -40,18 +39,3 @@ describe.each([
|
||||
expect(link).toHaveAttribute('target', '_blank');
|
||||
});
|
||||
});
|
||||
|
||||
describe('the sign-in screen link', () => {
|
||||
it('renders nothing in a browser', () => {
|
||||
vi.mocked(nativeServerHost).mockReturnValue(null);
|
||||
const { container } = render(<NativeServerLink />);
|
||||
expect(container).toBeEmptyDOMElement();
|
||||
});
|
||||
|
||||
it('leads back to the address screen in the app', () => {
|
||||
vi.mocked(nativeServerHost).mockReturnValue('trek.example.com');
|
||||
render(<NativeServerLink />);
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Change server' }));
|
||||
expect(TrekShell.resetServer).toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -4,6 +4,7 @@ import userEvent from '@testing-library/user-event';
|
||||
import { http, HttpResponse } from 'msw';
|
||||
import { render, screen, waitFor, within } from '../../../tests/helpers/render';
|
||||
import { server } from '../../../tests/helpers/msw/server';
|
||||
import { locationAt } from '../../../tests/helpers/location';
|
||||
import { ToastContainer } from '../shared/Toast';
|
||||
import { usePluginStore, type ActivePlugin } from '../../store/pluginStore';
|
||||
import type { PluginAction, PluginUserSettingField } from '../../api/client';
|
||||
@@ -367,7 +368,7 @@ describe('PluginSettingsTab', () => {
|
||||
|
||||
it('FE-COMP-PLUGINSETTINGS-020: an OAuth-only plugin gets a card and Connect hands off to the provider', async () => {
|
||||
const user = userEvent.setup();
|
||||
const loc = { href: 'http://localhost/settings', origin: 'http://localhost', pathname: '/settings' };
|
||||
const loc = locationAt('/settings');
|
||||
vi.stubGlobal('location', loc);
|
||||
serve('weather', {}, { configured: true, connected: false });
|
||||
server.use(http.post('/api/plugin-oauth/weather/connect', () =>
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
// FE-HOOK-AI-CONNECT-001 to FE-HOOK-AI-CONNECT-015: pasting a key, an own server, the ChatGPT sign-in and the OpenRouter return.
|
||||
// FE-HOOK-AI-CONNECT-001 to FE-HOOK-AI-CONNECT-017: pasting a key, an own server, the ChatGPT sign-in and the OpenRouter return.
|
||||
import { act, fireEvent, renderHook, waitFor } from '@testing-library/react';
|
||||
import { createElement, type ReactNode } from 'react';
|
||||
import { MemoryRouter, useLocation } from 'react-router';
|
||||
@@ -20,6 +20,7 @@ vi.mock('../../shared/Toast', () => ({ useToast: () => toast }));
|
||||
const { useChatgptConnect, useCustomConnect, useKeyConnect, useOpenrouterReturn, useOpenrouterStart } =
|
||||
await import('./useAiConnect');
|
||||
const { rememberOpenrouterFlow } = await import('./aiConnectModel');
|
||||
const { OnlineOnlyError } = await import('../../../repo/onlineOnly');
|
||||
|
||||
function wrapperAt(url = '/settings') {
|
||||
return ({ children }: { children: ReactNode }) =>
|
||||
@@ -207,7 +208,7 @@ describe('useChatgptConnect', () => {
|
||||
expect(repo.chatgptFinish).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('FE-HOOK-AI-CONNECT-010: an account ChatGPT will not share says so and keeps the flow', async () => {
|
||||
it('FE-HOOK-AI-CONNECT-010: an account ChatGPT will not share says so, and the next try is a fresh sign-in', async () => {
|
||||
repo.chatgptFinish.mockRejectedValueOnce(refused('not_eligible'));
|
||||
const onConnected = vi.fn();
|
||||
const { result } = renderHook(() => useChatgptConnect({ active: true, onConnected }), { wrapper: wrapperAt() });
|
||||
@@ -216,7 +217,50 @@ describe('useChatgptConnect', () => {
|
||||
await act(() => result.current.submit());
|
||||
expect(result.current.error).toEqual({ messageKey: 'assistant.error.notEligible', code: 'not_eligible' });
|
||||
expect(onConnected).not.toHaveBeenCalled();
|
||||
expect(repo.chatgptStart).toHaveBeenCalledTimes(1);
|
||||
// The server took the sign-in when it refused it.
|
||||
await waitFor(() => expect(repo.chatgptStart).toHaveBeenCalledTimes(2));
|
||||
});
|
||||
|
||||
it('FE-HOOK-AI-CONNECT-016: any refusal the server sent starts exactly one fresh sign-in; offline and a wrong address keep this one', async () => {
|
||||
const generic = Object.assign(new Error('generic'), {
|
||||
response: { status: 400, data: { error: 'ChatGPT refused the sign-in (invalid_client)', code: 'generic' } },
|
||||
});
|
||||
repo.chatgptFinish.mockRejectedValueOnce(generic).mockRejectedValueOnce(new OnlineOnlyError());
|
||||
const { result } = renderHook(() => useChatgptConnect({ active: true, onConnected: vi.fn() }), {
|
||||
wrapper: wrapperAt(),
|
||||
});
|
||||
await waitFor(() => expect(result.current.flow).not.toBeNull());
|
||||
act(() => result.current.change(CALLBACK));
|
||||
await act(() => result.current.submit());
|
||||
expect(result.current.error?.code).toBe('generic');
|
||||
await waitFor(() => expect(repo.chatgptStart).toHaveBeenCalledTimes(2));
|
||||
await waitFor(() => expect(result.current.flow).not.toBeNull());
|
||||
|
||||
act(() => result.current.change(CALLBACK));
|
||||
await act(() => result.current.submit());
|
||||
expect(result.current.error?.code).toBe('offline');
|
||||
expect(repo.chatgptStart).toHaveBeenCalledTimes(2);
|
||||
|
||||
// The server refuses a wrong address before it takes the sign-in, so the right one still works.
|
||||
repo.chatgptFinish.mockRejectedValueOnce(refused('wrong_url'));
|
||||
act(() => result.current.change(CALLBACK));
|
||||
await act(() => result.current.submit());
|
||||
expect(result.current.error?.code).toBe('wrong_url');
|
||||
expect(repo.chatgptStart).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it('FE-HOOK-AI-CONNECT-017: the address pasted without http://, as the hint shows it, is taken and sent with it', async () => {
|
||||
const onConnected = vi.fn();
|
||||
const { result } = renderHook(() => useChatgptConnect({ active: true, onConnected }), { wrapper: wrapperAt() });
|
||||
await waitFor(() => expect(result.current.flow).not.toBeNull());
|
||||
const bare = CALLBACK.replace('http://', '');
|
||||
let taken = false;
|
||||
act(() => {
|
||||
taken = result.current.paste(` ${bare} `);
|
||||
});
|
||||
expect(taken).toBe(true);
|
||||
await waitFor(() => expect(onConnected).toHaveBeenCalledTimes(1));
|
||||
expect(repo.chatgptFinish).toHaveBeenCalledWith({ flowId: FLOW.flowId, pastedUrl: CALLBACK });
|
||||
});
|
||||
|
||||
it('FE-HOOK-AI-CONNECT-013: the clipboard fills the field where the browser lets it be read, else the field gets the cursor', async () => {
|
||||
|
||||
@@ -3,7 +3,7 @@ import { useEffect, useEffectEvent, useRef, useState } from 'react';
|
||||
import { useSearchParams } from 'react-router';
|
||||
import { useTranslation } from '../../../i18n';
|
||||
import { aiConnectionsRepo } from '../../../repo/aiConnectionsRepo';
|
||||
import { detectKeyKind, isChatgptCallback, providerLabel } from '../../Assistant/providerCatalog';
|
||||
import { chatgptCallbackUrl, detectKeyKind, isChatgptCallback, providerLabel } from '../../Assistant/providerCatalog';
|
||||
import { useToast } from '../../shared/Toast';
|
||||
import {
|
||||
callbackMatchesFlow,
|
||||
@@ -243,9 +243,9 @@ export function useChatgptConnect({
|
||||
};
|
||||
|
||||
const finish = async (raw: string) => {
|
||||
const url = raw.trim();
|
||||
const url = chatgptCallbackUrl(raw);
|
||||
if (!flow || finishing.current) return;
|
||||
if (!isChatgptCallback(url) || !callbackMatchesFlow(url, flow.authorizeUrl)) {
|
||||
if (!url || !callbackMatchesFlow(url, flow.authorizeUrl)) {
|
||||
setError({ messageKey: 'assistant.connect.chatgptWrong', code: 'wrong_url' });
|
||||
return;
|
||||
}
|
||||
@@ -264,7 +264,9 @@ export function useChatgptConnect({
|
||||
} catch (err) {
|
||||
const code = refusalCode(err);
|
||||
setError({ messageKey: connectErrorKey(err), code });
|
||||
if (code === 'expired') restart();
|
||||
// The server takes a sign-in once, whatever it answers: any refusal it sent
|
||||
// used this one up. Offline the request never left, and a wrong address is refused before the flow is taken.
|
||||
if (code !== null && code !== 'offline' && code !== 'wrong_url') restart();
|
||||
} finally {
|
||||
finishing.current = false;
|
||||
setBusy(false);
|
||||
@@ -298,7 +300,7 @@ export function useChatgptConnect({
|
||||
useOnReturnToTab(opened, () => {
|
||||
if (pasted.trim() || busy) return;
|
||||
readClipboard((text) => {
|
||||
if (flow && !callbackMatchesFlow(text, flow.authorizeUrl)) focusField();
|
||||
if (flow && !callbackMatchesFlow(chatgptCallbackUrl(text) ?? text, flow.authorizeUrl)) focusField();
|
||||
else if (!paste(text)) focusField();
|
||||
}, focusField);
|
||||
});
|
||||
|
||||
@@ -0,0 +1,14 @@
|
||||
// FE-SETTINGS-TRIPOFFLINE-001: where a trip stands on this device, for its menu (#1580).
|
||||
import { describe, expect, it } from 'vitest';
|
||||
|
||||
import { tripOfflineState } from './useTripOfflineStatus';
|
||||
|
||||
describe('tripOfflineState', () => {
|
||||
it('FE-SETTINGS-TRIPOFFLINE-001: off when switched off or not kept, saved as of the last sync, else pending', () => {
|
||||
expect(tripOfflineState(false, true, 1000)).toEqual({ kind: 'off' });
|
||||
expect(tripOfflineState(true, false, 1000)).toEqual({ kind: 'off' });
|
||||
expect(tripOfflineState(true, true, 1000)).toEqual({ kind: 'saved', at: 1000 });
|
||||
expect(tripOfflineState(true, true, null)).toEqual({ kind: 'pending' });
|
||||
expect(tripOfflineState(true, true, undefined)).toEqual({ kind: 'pending' });
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,51 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
|
||||
import { offlineDb } from '../../db/offlineDb';
|
||||
import { isTripOfflineEnabled, isTripPinned } from '../../sync/offlinePrefs';
|
||||
import { isDateEligible } from '../../sync/tripSyncManager';
|
||||
import type { Trip } from '../../types';
|
||||
|
||||
/** Where a trip stands on this device (#1580), as the trip's own menu says it. */
|
||||
export type TripOfflineState = { kind: 'saved'; at: number } | { kind: 'pending' } | { kind: 'off' };
|
||||
|
||||
/**
|
||||
* The trip's state from what decides it: switched off, or kept by neither the
|
||||
* date rule nor a pin, it is not on the device; synced before, it is, as of then;
|
||||
* otherwise the next sync brings it.
|
||||
*/
|
||||
export function tripOfflineState(
|
||||
enabled: boolean,
|
||||
kept: boolean,
|
||||
lastSyncedAt: number | null | undefined
|
||||
): TripOfflineState {
|
||||
if (!enabled || !kept) return { kind: 'off' };
|
||||
if (lastSyncedAt) return { kind: 'saved', at: lastSyncedAt };
|
||||
return { kind: 'pending' };
|
||||
}
|
||||
|
||||
/**
|
||||
* The offline state of one trip, read again each time `active` turns on (the
|
||||
* menu opening), so it shows the last sync rather than the one before it.
|
||||
*/
|
||||
export function useTripOfflineStatus(trip: Trip | null | undefined, active: boolean): TripOfflineState | null {
|
||||
const [state, setState] = useState<TripOfflineState | null>(null);
|
||||
useEffect(() => {
|
||||
if (!active || !trip) return;
|
||||
let cancelled = false;
|
||||
const enabled = isTripOfflineEnabled(trip.id);
|
||||
const kept = isTripPinned(trip.id) || isDateEligible(trip);
|
||||
void offlineDb.syncMeta.get(trip.id).then(
|
||||
(meta) => {
|
||||
if (!cancelled) setState(tripOfflineState(enabled, kept, meta?.lastSyncedAt));
|
||||
},
|
||||
// An unreadable store says nothing about the trip: the line stays away.
|
||||
() => {
|
||||
if (!cancelled) setState(null);
|
||||
}
|
||||
);
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}, [trip, active]);
|
||||
return state;
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
// FE-RN-001 to FE-RN-020
|
||||
// FE-RN-001 to FE-RN-022
|
||||
import userEvent from '@testing-library/user-event';
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
import { render, screen } from '../../../tests/helpers/render';
|
||||
@@ -295,4 +295,23 @@ describe('ReleaseNoticeModal', () => {
|
||||
expect(document.querySelectorAll('.rn-vis-route-stop')).toHaveLength(5);
|
||||
expect(document.querySelector('.rn-vis-route-line')).not.toBeNull();
|
||||
});
|
||||
|
||||
it('FE-RN-021: an apps block draws one tile with its title and both store cards', () => {
|
||||
renderModal(withRelease({ apps: { titleKey: 'rel.apps.title' } }));
|
||||
const tile = document.querySelector('.rn-apps');
|
||||
expect(tile).toHaveTextContent('rel.apps.title');
|
||||
const stores = tile?.querySelectorAll('a.asc-card') ?? [];
|
||||
expect([...stores].map((a) => a.getAttribute('href'))).toEqual([
|
||||
'https://apps.apple.com/app/id6831237775',
|
||||
'https://play.google.com/store/apps/details?id=com.liketrek.trek',
|
||||
]);
|
||||
// On the release column, which is dark in either theme.
|
||||
expect(tile?.querySelector('.asc-row')).toHaveClass('asc-dark');
|
||||
});
|
||||
|
||||
it('FE-RN-022: without an apps block there is no apps tile', () => {
|
||||
renderModal();
|
||||
expect(document.querySelector('.rn-apps')).toBeNull();
|
||||
expect(document.querySelector('.asc-card')).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -2,6 +2,7 @@ import { ArrowRight, Heart, Infinity as InfinityIcon, ShieldCheck, X } from 'luc
|
||||
import React from 'react';
|
||||
import { useTranslation } from '../../i18n/TranslationContext.js';
|
||||
import type { SystemNoticeDTO } from '../../store/systemNoticeStore.js';
|
||||
import AppStoreCards from '../shared/AppStoreCards';
|
||||
import { PATREON_PATH } from '../shared/PatreonIcon';
|
||||
import { ReleaseFeatureVisual } from './ReleaseNoticeVisuals.js';
|
||||
import './releaseNotice.css';
|
||||
@@ -127,6 +128,16 @@ export function ReleaseNoticeModal({ notice, visible, onDismiss, onCTA, onSecond
|
||||
{withSponsorLink(t(release.introKey))}
|
||||
</p>
|
||||
|
||||
{release.apps && (
|
||||
<div className="rn-apps">
|
||||
<div className="rn-feature-shine" aria-hidden="true" />
|
||||
<div className="rn-apps-text">
|
||||
<div className="rn-feature-title">{t(release.apps.titleKey)}</div>
|
||||
</div>
|
||||
<AppStoreCards tone="dark" className="rn-apps-stores" />
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="rn-features-head">
|
||||
<span className="rn-features-label">{t(release.featuresLabelKey)}</span>
|
||||
<span className="rn-features-rule" aria-hidden="true" />
|
||||
|
||||
@@ -647,3 +647,28 @@
|
||||
.rn-sponsor:hover {
|
||||
text-decoration-color: currentColor;
|
||||
}
|
||||
|
||||
/* ── The apps: one tile across the column, the text beside the store cards ── */
|
||||
|
||||
.rn-apps {
|
||||
position: relative;
|
||||
margin-top: 22px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 22px;
|
||||
padding: 16px 16px 16px 20px;
|
||||
border-radius: 20px;
|
||||
background: linear-gradient(160deg, oklch(1 0 0 / 0.1) 0%, oklch(1 0 0 / 0.045) 62%);
|
||||
border: 1px solid oklch(1 0 0 / 0.13);
|
||||
box-shadow: inset 0 1px 0 oklch(1 0 0 / 0.16), 0 12px 28px -16px oklch(0 0 0 / 0.7);
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.rn-apps-text { position: relative; flex: 1 1 200px; min-width: 0; }
|
||||
|
||||
.rn-apps-stores { position: relative; flex: 0 1 520px; min-width: 0; }
|
||||
|
||||
@media (max-width: 1280px) {
|
||||
.rn-apps { flex-direction: column; align-items: stretch; }
|
||||
.rn-apps-stores { flex-basis: auto; }
|
||||
}
|
||||
|
||||
@@ -12,7 +12,7 @@ import type { Day } from '../../../types'
|
||||
import { toggleTourPlacing } from '../../../store/tourPlaceToolStore'
|
||||
import { publishTourFerrataCrossings } from '../../../store/tourFerrataCrossingStore'
|
||||
import { TourPlannerRail, TourPlannerToursRail } from './TourPlannerPanels'
|
||||
import { hikePlannerDefaults } from '../../../../tests/helpers/tourPlannerStub'
|
||||
import { hikePlannerDefaults, mockTourEditorLayout } from '../../../../tests/helpers/tourPlannerStub'
|
||||
import { tourRepo } from '../../../repo/tourRepo'
|
||||
import { useTripStore } from '../../../store/tripStore'
|
||||
import type { TourStage } from '../stages/tourStages'
|
||||
@@ -132,6 +132,12 @@ beforeEach(() => {
|
||||
seedStore(useSettingsStore, { settings: { distance_unit: 'metric' } })
|
||||
})
|
||||
|
||||
function openDifficulty() {
|
||||
const trigger = screen.getByRole('button', { name: 'Maximum trail difficulty' })
|
||||
mockTourEditorLayout(trigger.parentElement ?? trigger)
|
||||
fireEvent.click(trigger)
|
||||
}
|
||||
|
||||
describe('TourPlannerToursRail', () => {
|
||||
it('MDT-02: a multi-day tour unfolds its stages in the list, a day tour has nothing to unfold', async () => {
|
||||
vi.spyOn(tourRepo, 'detail').mockResolvedValue({ tour, waypoints: [] })
|
||||
@@ -702,6 +708,7 @@ describe('TourPlannerRail', () => {
|
||||
render(<TourPlannerRail planner={controller} />)
|
||||
|
||||
expect(screen.getByLabelText('Tour name')).toBeDisabled()
|
||||
expect(screen.getByTestId('tour-type-select')).toBeDisabled()
|
||||
expect(screen.getByRole('button', { name: 'Maximum trail difficulty' })).toBeDisabled()
|
||||
expect(screen.getByRole('button', { name: 'Save' })).toBeDisabled()
|
||||
expect(screen.getByRole('button', { name: 'Back to Tours' })).toBeDisabled()
|
||||
@@ -765,7 +772,7 @@ describe('TourPlannerRail', () => {
|
||||
const controller = planner({ mode: { type: 'new-draft' }, setMaxHikingDifficulty: setDifficulty, acknowledgeAlpine: acknowledge })
|
||||
const { unmount } = render(<TourPlannerRail planner={controller} />)
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Maximum trail difficulty' }))
|
||||
openDifficulty()
|
||||
fireEvent.click(screen.getByRole('button', { name: /T4: Alpine hiking/ }))
|
||||
expect(screen.getByRole('heading', { name: 'Enable alpine routing?' })).toBeInTheDocument()
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Enable alpine routing' }))
|
||||
@@ -775,7 +782,7 @@ describe('TourPlannerRail', () => {
|
||||
|
||||
// The planner remembers the answer, so a rail that mounts anew does not ask again.
|
||||
render(<TourPlannerRail planner={planner({ mode: { type: 'new-draft' }, setMaxHikingDifficulty: setDifficulty, alpineAcknowledged: true })} />)
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Maximum trail difficulty' }))
|
||||
openDifficulty()
|
||||
fireEvent.click(screen.getByRole('button', { name: /T5: Demanding alpine hiking/ }))
|
||||
expect(screen.queryByRole('heading', { name: 'Enable alpine routing?' })).not.toBeInTheDocument()
|
||||
expect(setDifficulty).toHaveBeenLastCalledWith(5)
|
||||
@@ -785,7 +792,7 @@ describe('TourPlannerRail', () => {
|
||||
const setDifficulty = vi.fn()
|
||||
render(<TourPlannerRail planner={planner({ mode: { type: 'new-draft' }, setMaxHikingDifficulty: setDifficulty })} />)
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Maximum trail difficulty' }))
|
||||
openDifficulty()
|
||||
fireEvent.click(screen.getByRole('button', { name: /T4: Alpine hiking/ }))
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Cancel' }))
|
||||
expect(setDifficulty).not.toHaveBeenCalled()
|
||||
@@ -802,7 +809,7 @@ describe('TourPlannerRail', () => {
|
||||
})} />
|
||||
}
|
||||
render(<StatefulDifficultyRail />)
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Maximum trail difficulty' }))
|
||||
openDifficulty()
|
||||
|
||||
for (const label of [
|
||||
'T1: Hiking',
|
||||
@@ -818,6 +825,22 @@ describe('TourPlannerRail', () => {
|
||||
expect(screen.getAllByRole('status').some(el => /T3 routes may include exposed/.test(el.textContent ?? ''))).toBe(true)
|
||||
})
|
||||
|
||||
it('TOUR-PLANNER-RAIL-024: an open tour type list closes when saving locks the editor', () => {
|
||||
const controller = planner({ mode: { type: 'new-draft' } })
|
||||
const { rerender } = render(<TourPlannerRail planner={controller} />)
|
||||
const trigger = screen.getByTestId('tour-type-select')
|
||||
mockTourEditorLayout(trigger)
|
||||
fireEvent.click(trigger)
|
||||
expect(screen.getByRole('group', { name: 'Tour type' })).toBeInTheDocument()
|
||||
|
||||
rerender(<TourPlannerRail planner={{ ...controller, isSaving: true }} />)
|
||||
expect(trigger).toBeDisabled()
|
||||
expect(trigger).toHaveAttribute('aria-expanded', 'false')
|
||||
expect(screen.queryByTestId('tour-type-option-hike')).not.toBeInTheDocument()
|
||||
rerender(<TourPlannerRail planner={controller} />)
|
||||
expect(trigger).toHaveAttribute('aria-expanded', 'false')
|
||||
})
|
||||
|
||||
it('TOUR-PLANNER-RAIL-009: neutral shows only the Plan new entry and new-draft guidance hides after the first waypoint', () => {
|
||||
const controller = planner({ mode: { type: 'neutral' } })
|
||||
const { rerender } = render(<TourPlannerRail planner={controller} />)
|
||||
|
||||
@@ -12,6 +12,7 @@ import { useRailHeadProps } from './railHead'
|
||||
import EmptyState from '../../shared/EmptyState'
|
||||
import { useToast } from '../../shared/Toast'
|
||||
import { Tooltip } from '../../shared/Tooltip'
|
||||
import { PopoverBoundary } from '../../shared/useAnchoredPopover'
|
||||
import { BOX } from '../../Planner/bookings/bookingParts'
|
||||
import { BarButton, SoftPill } from '../../Planner/planParts'
|
||||
import TourListRow from '../TourListRow'
|
||||
@@ -335,6 +336,7 @@ export function TourPlannerRail({ planner,
|
||||
const { t } = useTranslation()
|
||||
const [confirmDiscard, setConfirmDiscard] = useState(false)
|
||||
const [pendingDifficulty, setPendingDifficulty] = useState<1 | 2 | 3 | 4 | 5 | 6 | null>(null)
|
||||
const editorScrollRef = useRef<HTMLDivElement>(null)
|
||||
const isSaving = planner.isSaving
|
||||
// Nothing in the editor changes while the viewer may not edit or a save is in flight.
|
||||
const locked = !canEdit || isSaving
|
||||
@@ -389,44 +391,46 @@ export function TourPlannerRail({ planner,
|
||||
</BarButton>
|
||||
</div>
|
||||
|
||||
<div className="flex min-h-0 flex-1 flex-col gap-4 overflow-y-auto px-3 py-3.5">
|
||||
<TourRemoteChangeNotice planner={planner} />
|
||||
<WalkImportDraftNotice planner={planner} />
|
||||
<WalkRoutePendingNotice planner={planner} />
|
||||
<TourNameField planner={planner} locked={locked} />
|
||||
<div ref={editorScrollRef} data-testid="tour-planner-editor-scroll" className="flex min-h-0 flex-1 flex-col gap-4 overflow-y-auto px-3 py-3.5">
|
||||
<PopoverBoundary value={editorScrollRef}>
|
||||
<TourRemoteChangeNotice planner={planner} />
|
||||
<WalkImportDraftNotice planner={planner} />
|
||||
<WalkRoutePendingNotice planner={planner} />
|
||||
<TourNameField planner={planner} locked={locked} />
|
||||
|
||||
<TourTypeFields planner={planner} locked={locked} />
|
||||
<TourTypeFields planner={planner} locked={locked} />
|
||||
|
||||
<TourStageModeField planner={planner} locked={locked} />
|
||||
<TourStageModeField planner={planner} locked={locked} />
|
||||
|
||||
{recordedTrack?.available && <RecordedTrackCard recordedTrack={recordedTrack} disabled={isSaving} />}
|
||||
{recordedTrack?.available && <RecordedTrackCard recordedTrack={recordedTrack} disabled={isSaving} />}
|
||||
|
||||
<UnreachableNotice planner={planner} />
|
||||
<WalkFerryNotice planner={planner} />
|
||||
<UnreachableNotice planner={planner} />
|
||||
<WalkFerryNotice planner={planner} />
|
||||
|
||||
<TourStageLossNotice planner={planner} />
|
||||
<TourStageDayNotice planner={planner} />
|
||||
<TourStageLossNotice planner={planner} />
|
||||
<TourStageDayNotice planner={planner} />
|
||||
|
||||
<TourWaypointList planner={planner} canEdit={canEdit} isSaving={isSaving} tourPlaceIds={tourPlaceIds} />
|
||||
<TourWaypointList planner={planner} canEdit={canEdit} isSaving={isSaving} tourPlaceIds={tourPlaceIds} />
|
||||
|
||||
<BikeWaysCard planner={planner} />
|
||||
<BikeWaysCard planner={planner} />
|
||||
|
||||
<RunWaysCard planner={planner} />
|
||||
<RunWaysCard planner={planner} />
|
||||
|
||||
<HorseRoutesCard planner={planner} />
|
||||
<HorseRoutesCard planner={planner} />
|
||||
|
||||
<SkiPlannerSummary planner={planner} />
|
||||
<SkiPlannerSummary planner={planner} />
|
||||
|
||||
{planner.tourType === 'hike' && (
|
||||
<HikeWaysCard tripId={planner.tripId} route={planner.route} routeCurrent={planner.routeCurrent}
|
||||
routingLimit={planner.maxHikingDifficulty} />
|
||||
)}
|
||||
{planner.tourType === 'hike' && (
|
||||
<HikeWaysCard tripId={planner.tripId} route={planner.route} routeCurrent={planner.routeCurrent}
|
||||
routingLimit={planner.maxHikingDifficulty} />
|
||||
)}
|
||||
|
||||
<TourPoiSearchCard planner={planner} />
|
||||
<TourPoiSearchCard planner={planner} />
|
||||
|
||||
<PaddleEditorCards planner={planner} locked={locked} checklist={paddleChecklist} />
|
||||
<PaddleEditorCards planner={planner} locked={locked} checklist={paddleChecklist} />
|
||||
|
||||
<TourDetailsSection planner={planner} locked={locked} onDifficultyChange={changeDifficulty} />
|
||||
<TourDetailsSection planner={planner} locked={locked} onDifficultyChange={changeDifficulty} />
|
||||
</PopoverBoundary>
|
||||
</div>
|
||||
|
||||
<TourEditorRailFooter planner={planner} canEdit={canEdit} locked={locked} isSavedEdit={isSavedEdit} onDiscard={requestClose} />
|
||||
|
||||
@@ -111,7 +111,7 @@ function BikeProfileField({ planner }: { planner: TourPlannerController }) {
|
||||
* discipline and, for cross-country, the technique, then what the piste router
|
||||
* is asked for. A short line says how its legs are laid.
|
||||
*/
|
||||
function SkiFields({ planner }: { planner: TourPlannerController }) {
|
||||
function SkiFields({ planner, locked }: TourTypeFieldsProps) {
|
||||
const { t } = useTranslation();
|
||||
const { choice } = planner.ski;
|
||||
return (
|
||||
@@ -121,7 +121,12 @@ function SkiFields({ planner }: { planner: TourPlannerController }) {
|
||||
{t('tours.ski.plannedHint')}
|
||||
</span>
|
||||
{choice.discipline !== null && (
|
||||
<SkiRouteOptions discipline={choice.discipline} options={choice.options} onChange={planner.ski.setOption} />
|
||||
<SkiRouteOptions
|
||||
discipline={choice.discipline}
|
||||
options={choice.options}
|
||||
onChange={planner.ski.setOption}
|
||||
locked={locked}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
@@ -157,7 +162,7 @@ export function TourTypeFields({ planner, locked }: TourTypeFieldsProps) {
|
||||
|
||||
{planner.isRun && <RunFields planner={planner} locked={locked} />}
|
||||
|
||||
{planner.isSki && <SkiFields planner={planner} />}
|
||||
{planner.isSki && <SkiFields planner={planner} locked={locked} />}
|
||||
|
||||
{planner.isPaddle && (
|
||||
<div data-testid="tour-planner-paddle-fields" className="flex min-w-0 flex-col gap-3">
|
||||
|
||||
@@ -47,7 +47,10 @@ export function TourTypeSelect<T extends ImportableTourType = PlannableTourType>
|
||||
const { t } = useTranslation();
|
||||
const valueId = useId();
|
||||
const offered: readonly ImportableTourType[] = types ?? PLANNER_TOUR_TYPES;
|
||||
const list = usePopoverList(offered.indexOf(value), { estimatedHeight: 50 * offered.length + 20 });
|
||||
const list = usePopoverList(offered.indexOf(value), {
|
||||
estimatedHeight: 50 * offered.length + 20,
|
||||
disabled,
|
||||
});
|
||||
const { open, toggle, triggerRef, listId } = list;
|
||||
const label = t('tours.planner.tourType');
|
||||
const pick = (type: T) => {
|
||||
|
||||
@@ -47,6 +47,7 @@ interface SkiRouteOptionsProps {
|
||||
discipline: SkiDiscipline;
|
||||
options: SkiRouteOptionsInput | null | undefined;
|
||||
onChange: (patch: Partial<SkiRouteOptionsInput>) => void;
|
||||
locked?: boolean;
|
||||
}
|
||||
|
||||
/** One switch of the piste router on its own row, its label beside it. */
|
||||
@@ -102,7 +103,7 @@ function LiftClasses({ avoided, onChange }: { avoided: SkiLiftClass[]; onChange:
|
||||
* weigh most for a downhill skier, groomed and lit trails for cross-country,
|
||||
* the lifts for anyone who rides them. Every change plans the tour again.
|
||||
*/
|
||||
export function SkiRouteOptions({ discipline, options, onChange }: SkiRouteOptionsProps) {
|
||||
export function SkiRouteOptions({ discipline, options, onChange, locked }: SkiRouteOptionsProps) {
|
||||
const { t } = useTranslation();
|
||||
const read = new Set(skiOptionsReadBy(discipline));
|
||||
const current: Options = { ...DEFAULT_SKI_ROUTE_OPTIONS, ...options };
|
||||
@@ -119,6 +120,7 @@ export function SkiRouteOptions({ discipline, options, onChange }: SkiRouteOptio
|
||||
<CustomSelect
|
||||
id="tour-planner-ski-difficulty"
|
||||
ariaLabel={t('tours.ski.options.maxDifficulty')}
|
||||
disabled={locked}
|
||||
size="sm"
|
||||
value={current.max_difficulty}
|
||||
onChange={(value) => onChange({ max_difficulty: value as SkiDifficulty })}
|
||||
|
||||
@@ -11,7 +11,7 @@ import { analyzeRouteGeometry } from '../../utils/routeGeometry'
|
||||
import TourListRow from './TourListRow'
|
||||
import { TourPlannerRail, TourPlannerToursRail } from './planner/TourPlannerPanels'
|
||||
import type { TourPlannerController } from './planner/useTourPlanner'
|
||||
import { hikePlannerDefaults } from '../../../tests/helpers/tourPlannerStub'
|
||||
import { hikePlannerDefaults, mockTourEditorLayout } from '../../../tests/helpers/tourPlannerStub'
|
||||
|
||||
vi.mock('../../../../server/src/config', () => { throw new Error('Config initialization is forbidden in client tests') })
|
||||
vi.mock('../../../../server/src/db/database', () => { throw new Error('Legacy database imports are forbidden in client tests') })
|
||||
@@ -151,7 +151,9 @@ describe('Tours English and German copy', () => {
|
||||
}
|
||||
rerender(<TourPlannerRail planner={planner({ mode: { type: 'new-draft' }, status: 'ready', error: 'save' })} />)
|
||||
expect(screen.getByLabelText(toursText(de, 'tours.planner.status.saveFailed'))).toBeInTheDocument()
|
||||
fireEvent.click(screen.getByRole('button', { name: toursText(de, 'tours.planner.maxDifficulty') }))
|
||||
const difficulty = screen.getByRole('button', { name: toursText(de, 'tours.planner.maxDifficulty') })
|
||||
mockTourEditorLayout(difficulty.parentElement ?? difficulty)
|
||||
fireEvent.click(difficulty)
|
||||
fireEvent.click(screen.getByRole('button', { name: toursText(de, 'tours.planner.difficulty.t4') }))
|
||||
expect(screen.getByRole('heading', { name: toursText(de, 'tours.planner.difficulty.alpineTitle') })).toBeInTheDocument()
|
||||
expect(screen.getByText(toursText(de, 'tours.planner.difficulty.alpineBody'))).toBeInTheDocument()
|
||||
@@ -187,4 +189,4 @@ describe('Tours English and German copy', () => {
|
||||
expect(await screen.findByText(toursText(fr, 'tours.planner.neutralTitle'))).toBeInTheDocument()
|
||||
assertNoRawToursKeys()
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
@@ -284,6 +284,43 @@ describe('WalkStationsCard', () => {
|
||||
expect(within(cafe).queryByText(/Open/)).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('opens what the linked place has to tell under its stop, and leaves a stop without it as it is (#3205)', async () => {
|
||||
seedStore(useTripStore, {
|
||||
places: [
|
||||
buildPlace({
|
||||
id: 77,
|
||||
name: 'Lenbachhaus',
|
||||
description: 'Blue Rider collection',
|
||||
address: 'Luisenstrasse 33',
|
||||
website: 'https://lenbachhaus.de',
|
||||
}),
|
||||
],
|
||||
});
|
||||
vi.mocked(tourRepo.detail).mockImplementation(() =>
|
||||
detail([
|
||||
{ lat: 48, lng: 11, role: 'start', sequence: 0, key: 'stop-01', linked_place_id: 77, stay_minutes: 60 },
|
||||
{ lat: 48.002, lng: 11, role: 'end', sequence: 1, key: 'stop-02', name: 'Cafe', stay_minutes: 0 },
|
||||
])
|
||||
);
|
||||
card();
|
||||
|
||||
const museum = await rowOf('Lenbachhaus');
|
||||
const toggle = within(museum).getByRole('button', { name: /Lenbachhaus/ });
|
||||
expect(toggle).toHaveAttribute('aria-expanded', 'false');
|
||||
expect(within(museum).queryByText('Blue Rider collection')).not.toBeInTheDocument();
|
||||
fireEvent.click(toggle);
|
||||
expect(toggle).toHaveAttribute('aria-expanded', 'true');
|
||||
expect(within(museum).getByText('Blue Rider collection')).toBeInTheDocument();
|
||||
expect(within(museum).getByText('Luisenstrasse 33')).toBeInTheDocument();
|
||||
expect(within(museum).getByRole('link', { name: 'Open Website' })).toHaveAttribute(
|
||||
'href',
|
||||
'https://lenbachhaus.de'
|
||||
);
|
||||
|
||||
const cafe = await rowOf('Cafe');
|
||||
expect(within(cafe).queryByRole('button', { name: /Cafe/ })).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('shows the times in the 12 hour format where the user chose it', async () => {
|
||||
seedStore(useSettingsStore, { settings: { time_format: '12h' } });
|
||||
card(onMonday());
|
||||
|
||||
@@ -1,10 +1,13 @@
|
||||
import type { TourListItem, TourVisitStatus } from '@trek/shared';
|
||||
import { Check, CheckCheck, Info, Redo2, SkipForward, Undo2 } from 'lucide-react';
|
||||
import type { Place, TourListItem, TourVisitStatus } from '@trek/shared';
|
||||
import { Check, CheckCheck, ChevronDown, ExternalLink, Info, MapPin, Redo2, SkipForward, Undo2 } from 'lucide-react';
|
||||
import { useState } from 'react';
|
||||
import { useTranslation } from '../../../i18n';
|
||||
import { useTourVisitStore } from '../../../store/tourVisitStore';
|
||||
import type { Assignment, AssignmentsMap, Day } from '../../../types';
|
||||
import { safeHttpUrl } from '../../../utils/safeUrl';
|
||||
import { SoftPill } from '../../Planner/planParts';
|
||||
import { DialogSection, fs } from '../../shared/DialogShell';
|
||||
import MarkdownText from '../../shared/MarkdownText';
|
||||
import { useToast } from '../../shared/Toast';
|
||||
import { stationMarkNote, stationRingClass } from '../planner/stationMarks';
|
||||
import { StationPills, StationShield } from '../planner/stationParts';
|
||||
@@ -83,23 +86,62 @@ function StatusActions({
|
||||
* trip place it stands for), stay, the day's arrival and opening hours, and
|
||||
* what can be marked.
|
||||
*/
|
||||
/** What a station's linked place has to tell (#3205): its description, address and website. */
|
||||
function placeDetailsOf(place: Place | null | undefined) {
|
||||
if (!place) return null;
|
||||
const description = place.description?.trim() || '';
|
||||
const address = place.address?.trim() || '';
|
||||
const website = safeHttpUrl(place.website);
|
||||
return description || address || website ? { description, address, website } : null;
|
||||
}
|
||||
|
||||
/** The linked place's details, opened under its station without leaving the walk. */
|
||||
function StationDetails({ details }: { details: NonNullable<ReturnType<typeof placeDetailsOf>> }) {
|
||||
const { t } = useTranslation();
|
||||
return (
|
||||
<span className="flex flex-col gap-1 text-content-secondary" style={fs(11.5, 'body')}>
|
||||
{details.description && <MarkdownText className="leading-[1.5]">{details.description}</MarkdownText>}
|
||||
{details.address && (
|
||||
<span className="flex items-start gap-1">
|
||||
<MapPin size={11} strokeWidth={2.2} aria-hidden="true" className="mt-[2px] flex-none text-content-faint" />
|
||||
<bdi className="min-w-0 [overflow-wrap:anywhere]">{details.address}</bdi>
|
||||
</span>
|
||||
)}
|
||||
{details.website && (
|
||||
<a
|
||||
href={details.website}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="inline-flex items-center gap-1 self-start font-semibold text-content underline-offset-2 hover:underline"
|
||||
>
|
||||
<ExternalLink size={11} strokeWidth={2.2} aria-hidden="true" />
|
||||
{t('inspector.website')}
|
||||
</a>
|
||||
)}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
function StationRow({
|
||||
station,
|
||||
index,
|
||||
status,
|
||||
placeName,
|
||||
place,
|
||||
schedule,
|
||||
onMark,
|
||||
}: {
|
||||
station: TourPlannerWaypoint;
|
||||
index: number;
|
||||
status: TourVisitStatus | undefined;
|
||||
placeName: string | undefined;
|
||||
place: Place | null;
|
||||
schedule: StationSchedule | undefined;
|
||||
onMark: ((status: TourVisitStatus | 'planned') => void) | null;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
const name = station.name ?? placeName ?? t('tours.walk.stationNumbered', { number: index + 1 });
|
||||
const [open, setOpen] = useState(false);
|
||||
const details = placeDetailsOf(place);
|
||||
const name = station.name ?? place?.name ?? t('tours.walk.stationNumbered', { number: index + 1 });
|
||||
const nameClass = `truncate font-semibold text-content ${status === 'skipped' ? 'line-through' : ''}`;
|
||||
return (
|
||||
<li
|
||||
data-testid="walk-station"
|
||||
@@ -121,13 +163,31 @@ function StationRow({
|
||||
{station.protected && <StationShield />}
|
||||
</span>
|
||||
<span className="flex min-w-0 flex-1 flex-col gap-1">
|
||||
<span
|
||||
className={`truncate font-semibold text-content ${status === 'skipped' ? 'line-through' : ''}`}
|
||||
style={fs(12.5, 'body')}
|
||||
>
|
||||
{name}
|
||||
</span>
|
||||
{details ? (
|
||||
// A station that has more to tell opens it in place (#3205).
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setOpen((v) => !v)}
|
||||
aria-expanded={open}
|
||||
className="flex min-w-0 items-center gap-1 self-start text-start"
|
||||
>
|
||||
<span className={nameClass} style={fs(12.5, 'body')}>
|
||||
{name}
|
||||
</span>
|
||||
<ChevronDown
|
||||
size={13}
|
||||
strokeWidth={2.2}
|
||||
aria-hidden="true"
|
||||
className={`flex-none text-content-faint transition-transform ${open ? 'rotate-180' : ''}`}
|
||||
/>
|
||||
</button>
|
||||
) : (
|
||||
<span className={nameClass} style={fs(12.5, 'body')}>
|
||||
{name}
|
||||
</span>
|
||||
)}
|
||||
<StationPills point={station} />
|
||||
{open && details && <StationDetails details={details} />}
|
||||
<StationScheduleLine schedule={schedule} name={name} />
|
||||
{status && (
|
||||
<span className="text-content-faint" style={fs(11, 'body')}>
|
||||
@@ -252,7 +312,7 @@ export function WalkStationsCard({
|
||||
station={station}
|
||||
index={index}
|
||||
status={station.key ? visits?.[station.key] : undefined}
|
||||
placeName={placeOf(station)?.name}
|
||||
place={placeOf(station)}
|
||||
schedule={schedule.byStation.get(station.id)}
|
||||
onMark={marking === 'ready' && station.key ? (next) => onMark(station.key ?? '', next) : null}
|
||||
/>
|
||||
|
||||
@@ -0,0 +1,15 @@
|
||||
import { useTranslation } from '../../i18n';
|
||||
|
||||
/**
|
||||
* What the waiting states show while the app hands over from its address
|
||||
* screen (native/appBoot.ts): that screen's ground and its spinner, which only
|
||||
* comes up when the wait is long enough to notice. Styled in native/nativeApp.css.
|
||||
*/
|
||||
export default function AppBootScreen() {
|
||||
const { t } = useTranslation();
|
||||
return (
|
||||
<div className="app-boot" role="status" aria-label={t('common.loading')}>
|
||||
<span aria-hidden="true" />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
// FE-APPSTORE-001 to FE-APPSTORE-003
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { render } from '../../../tests/helpers/render';
|
||||
import AppStoreCards from './AppStoreCards';
|
||||
|
||||
describe('AppStoreCards', () => {
|
||||
it('FE-APPSTORE-001: links both stores in a new tab, each with its QR code', () => {
|
||||
render(<AppStoreCards />);
|
||||
const cards = [...document.querySelectorAll<HTMLAnchorElement>('a.asc-card')];
|
||||
expect(cards.map((a) => a.href)).toEqual([
|
||||
'https://apps.apple.com/app/id6831237775',
|
||||
'https://play.google.com/store/apps/details?id=com.liketrek.trek',
|
||||
]);
|
||||
for (const a of cards) {
|
||||
expect(a).toHaveAttribute('target', '_blank');
|
||||
expect(a).toHaveAttribute('rel', 'noopener noreferrer');
|
||||
expect(a.querySelector('.asc-qr path')?.getAttribute('d')).toMatch(/^M0 0\.5h7/);
|
||||
}
|
||||
});
|
||||
|
||||
it('FE-APPSTORE-002: names each store and translates the lines around it', () => {
|
||||
render(<AppStoreCards />);
|
||||
const [ios, android] = document.querySelectorAll('a.asc-card');
|
||||
expect(ios).toHaveTextContent('Download on the');
|
||||
expect(ios).toHaveTextContent('App Store');
|
||||
expect(ios).toHaveTextContent('iPhone and iPad');
|
||||
expect(android).toHaveTextContent('Get it on');
|
||||
expect(android).toHaveTextContent('Google Play');
|
||||
expect(android).toHaveTextContent('Phone and tablet');
|
||||
});
|
||||
|
||||
it('FE-APPSTORE-003: the dark tone marks the row, the theme tone does not', () => {
|
||||
const { unmount } = render(<AppStoreCards tone="dark" className="x" />);
|
||||
expect(document.querySelector('.asc-row')).toHaveClass('asc-dark', 'x');
|
||||
unmount();
|
||||
render(<AppStoreCards />);
|
||||
expect(document.querySelector('.asc-row')).not.toHaveClass('asc-dark');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,65 @@
|
||||
import React from 'react';
|
||||
import { useTranslation } from '../../i18n/TranslationContext.js';
|
||||
import './appStoreCards.css';
|
||||
|
||||
/**
|
||||
* The two app stores TREK is in, each as a card with its QR code: scanned with a
|
||||
* phone it opens the store page, clicked it opens it here. The README draws the
|
||||
* same cards. The QR codes are generated from the store addresses below (qrcode,
|
||||
* margin 0, level M); regenerate them if an address changes.
|
||||
*/
|
||||
const APP_STORES = [
|
||||
{
|
||||
id: 'ios',
|
||||
href: 'https://apps.apple.com/app/id6831237775',
|
||||
store: 'App Store',
|
||||
captionKey: 'settings.apps.downloadOn',
|
||||
devicesKey: 'settings.apps.iosDevices',
|
||||
logo: 'M12.152 6.896c-.948 0-2.415-1.078-3.96-1.04-2.04.027-3.91 1.183-4.961 3.014-2.117 3.675-.546 9.103 1.519 12.09 1.013 1.454 2.208 3.09 3.792 3.039 1.52-.065 2.09-.987 3.935-.987 1.831 0 2.35.987 3.96.948 1.637-.026 2.676-1.48 3.676-2.948 1.156-1.688 1.636-3.325 1.662-3.415-.039-.013-3.182-1.221-3.22-4.857-.026-3.04 2.48-4.494 2.597-4.559-1.429-2.09-3.623-2.324-4.39-2.376-2-.156-3.675 1.09-4.61 1.09zM15.53 3.83c.843-1.012 1.4-2.427 1.245-3.83-1.207.052-2.662.805-3.532 1.818-.78.896-1.454 2.338-1.273 3.714 1.338.104 2.715-.688 3.559-1.701',
|
||||
qrSize: 29,
|
||||
qr: 'M0 0.5h7m2 0h1m2 0h1m2 0h5m2 0h7M0 1.5h1m5 0h1m3 0h3m4 0h1m2 0h1m1 0h1m5 0h1M0 2.5h1m1 0h3m1 0h1m1 0h1m5 0h1m1 0h1m3 0h1m1 0h1m1 0h3m1 0h1M0 3.5h1m1 0h3m1 0h1m1 0h1m2 0h2m4 0h1m1 0h1m2 0h1m1 0h3m1 0h1M0 4.5h1m1 0h3m1 0h1m1 0h1m2 0h5m2 0h3m1 0h1m1 0h3m1 0h1M0 5.5h1m5 0h1m1 0h3m1 0h5m1 0h1m1 0h1m1 0h1m5 0h1M0 6.5h7m1 0h1m1 0h1m1 0h1m1 0h1m1 0h1m1 0h1m1 0h1m1 0h7M8 7.5h3m2 0h1m1 0h2m2 0h2M0 8.5h1m1 0h5m4 0h1m2 0h4m1 0h1m2 0h5M0 9.5h3m2 0h1m2 0h4m3 0h1m3 0h4m1 0h1m3 0h1M0 10.5h4m1 0h7m6 0h1m1 0h1m1 0h2M5 11.5h1m1 0h3m1 0h1m2 0h2m2 0h2m1 0h2m1 0h2m1 0h1M2 12.5h1m3 0h3m1 0h1m1 0h1m2 0h3m5 0h1m1 0h2M0 13.5h1m4 0h1m3 0h1m1 0h1m1 0h2m1 0h1m2 0h6m3 0h1M1 14.5h3m1 0h2m5 0h3m3 0h1m2 0h1m2 0h3M0 15.5h1m2 0h2m2 0h7m2 0h1m1 0h3m3 0h1m2 0h1M3 16.5h2m1 0h1m3 0h1m1 0h1m1 0h1m1 0h4m3 0h1m1 0h2M0 17.5h4m5 0h3m3 0h1m1 0h3m2 0h3m1 0h1m1 0h1M0 18.5h1m1 0h1m2 0h2m8 0h3m2 0h2m2 0h1m1 0h1M0 19.5h1m1 0h2m1 0h1m3 0h4m1 0h1m5 0h2m2 0h1m2 0h1M0 20.5h1m1 0h1m1 0h1m1 0h3m8 0h1m2 0h5m1 0h3M8 21.5h1m1 0h5m2 0h2m1 0h1m3 0h5M0 22.5h7m2 0h1m1 0h1m1 0h2m3 0h3m1 0h1m1 0h3M0 23.5h1m5 0h1m1 0h1m1 0h1m2 0h1m5 0h2m3 0h1M0 24.5h1m1 0h3m1 0h1m1 0h1m2 0h2m1 0h1m2 0h1m2 0h5m1 0h1m1 0h1M0 25.5h1m1 0h3m1 0h1m1 0h2m1 0h1m6 0h1m4 0h1m1 0h2M0 26.5h1m1 0h3m1 0h1m1 0h1m1 0h1m1 0h1m2 0h1m3 0h2m1 0h6M0 27.5h1m5 0h1m2 0h3m3 0h1m2 0h1m1 0h2m1 0h3m1 0h1M0 28.5h7m1 0h2m1 0h1m3 0h2m1 0h2m1 0h1m2 0h1m1 0h1',
|
||||
},
|
||||
{
|
||||
id: 'android',
|
||||
href: 'https://play.google.com/store/apps/details?id=com.liketrek.trek',
|
||||
store: 'Google Play',
|
||||
captionKey: 'settings.apps.getItOn',
|
||||
devicesKey: 'settings.apps.androidDevices',
|
||||
logo: 'M22.018 13.298l-3.919 2.218-3.515-3.493 3.543-3.521 3.891 2.202a1.49 1.49 0 0 1 0 2.594zM1.337.924a1.486 1.486 0 0 0-.112.568v21.017c0 .217.045.419.124.6l11.155-11.087L1.337.924zm12.207 10.065l3.258-3.238L3.45.195a1.466 1.466 0 0 0-.946-.179l11.04 10.973zm0 2.067l-11 10.933c.298.036.612-.016.906-.183l13.324-7.54-3.23-3.21z',
|
||||
qrSize: 37,
|
||||
qr: 'M0 0.5h7m2 0h1m3 0h1m1 0h1m2 0h1m1 0h3m1 0h2m4 0h7M0 1.5h1m5 0h1m4 0h1m2 0h1m2 0h3m5 0h4m1 0h1m5 0h1M0 2.5h1m1 0h3m1 0h1m1 0h2m2 0h5m2 0h4m1 0h1m1 0h1m3 0h1m1 0h3m1 0h1M0 3.5h1m1 0h3m1 0h1m1 0h2m1 0h1m1 0h1m2 0h5m1 0h1m2 0h2m3 0h1m1 0h3m1 0h1M0 4.5h1m1 0h3m1 0h1m1 0h2m3 0h1m4 0h3m1 0h2m1 0h1m2 0h1m1 0h1m1 0h3m1 0h1M0 5.5h1m5 0h1m1 0h6m4 0h1m3 0h1m2 0h4m1 0h1m5 0h1M0 6.5h7m1 0h1m1 0h1m1 0h1m1 0h1m1 0h1m1 0h1m1 0h1m1 0h1m1 0h1m1 0h1m1 0h1m1 0h7M8 7.5h1m1 0h4m2 0h1m6 0h1m4 0h1M0 8.5h1m1 0h5m2 0h1m3 0h3m2 0h1m1 0h7m3 0h5M0 9.5h5m5 0h1m4 0h3m3 0h1m4 0h1m1 0h1m2 0h1m3 0h1M0 10.5h3m1 0h4m1 0h3m1 0h1m3 0h1m2 0h9m1 0h1m2 0h1m1 0h2M2 11.5h2m3 0h1m5 0h1m2 0h1m4 0h1m1 0h1m2 0h3m1 0h4m2 0h1M1 12.5h1m1 0h1m2 0h1m3 0h1m1 0h2m2 0h2m2 0h1m1 0h6m1 0h4m1 0h3M0 13.5h1m6 0h1m1 0h3m1 0h1m2 0h6m1 0h2m3 0h1m2 0h1M2 14.5h1m3 0h2m1 0h1m1 0h5m1 0h1m3 0h1m4 0h3m2 0h3m1 0h2M2 15.5h2m3 0h1m1 0h1m2 0h7m2 0h2m5 0h5m2 0h2M1 16.5h1m2 0h3m3 0h2m1 0h2m1 0h1m4 0h1m1 0h1m1 0h3m1 0h2m1 0h1m1 0h1M2 17.5h1m2 0h1m2 0h2m1 0h2m2 0h1m2 0h1m1 0h1m1 0h1m1 0h3m1 0h1m2 0h1m2 0h2M1 18.5h1m4 0h1m3 0h2m2 0h3m2 0h1m2 0h1m3 0h2m1 0h1m2 0h1m2 0h2M1 19.5h3m4 0h5m2 0h1m2 0h5m1 0h1m5 0h3m3 0h1M0 20.5h1m1 0h1m1 0h1m1 0h2m2 0h1m4 0h1m1 0h1m1 0h2m1 0h1m1 0h4m1 0h2m1 0h3M1 21.5h1m6 0h2m1 0h1m1 0h2m1 0h1m1 0h3m1 0h2m4 0h1m4 0h1M2 22.5h1m1 0h5m1 0h1m2 0h4m1 0h1m1 0h1m1 0h1m2 0h1m1 0h1m3 0h3m1 0h2M0 23.5h1m2 0h1m1 0h1m5 0h2m2 0h1m7 0h1m4 0h2m1 0h2m2 0h1M1 24.5h2m3 0h1m3 0h4m4 0h1m1 0h7m1 0h3m1 0h1m1 0h2M0 25.5h4m1 0h1m2 0h4m3 0h2m4 0h1m6 0h1m4 0h1M0 26.5h1m2 0h1m1 0h2m3 0h1m1 0h3m5 0h1m2 0h2m1 0h2m2 0h2m2 0h3M0 27.5h1m1 0h3m3 0h2m6 0h1m4 0h1m1 0h1m2 0h7m2 0h1M0 28.5h1m1 0h1m1 0h1m1 0h1m1 0h2m1 0h2m1 0h1m2 0h1m4 0h4m1 0h9M8 29.5h6m2 0h2m1 0h3m1 0h1m3 0h2m3 0h2m1 0h1M0 30.5h7m2 0h1m5 0h3m2 0h2m4 0h1m1 0h1m1 0h1m1 0h1m1 0h1m1 0h1M0 31.5h1m5 0h1m1 0h1m1 0h6m1 0h8m1 0h3m3 0h2m1 0h1M0 32.5h1m1 0h3m1 0h1m1 0h2m1 0h1m1 0h1m1 0h2m2 0h1m1 0h1m2 0h9m1 0h1m1 0h1M0 33.5h1m1 0h3m1 0h1m1 0h1m2 0h1m1 0h3m2 0h1m1 0h3m1 0h2m3 0h2m1 0h1m1 0h2M0 34.5h1m1 0h3m1 0h1m1 0h1m3 0h1m2 0h2m2 0h1m1 0h2m2 0h5m4 0h1m1 0h1M0 35.5h1m5 0h1m5 0h1m1 0h2m2 0h7m3 0h3m1 0h1m3 0h1M0 36.5h7m1 0h1m1 0h1m1 0h1m1 0h2m1 0h1m1 0h1m3 0h4m2 0h2m1 0h5',
|
||||
},
|
||||
] as const;
|
||||
|
||||
interface Props {
|
||||
/** `dark` for a surface that stays dark in either theme, like the release modal. */
|
||||
tone?: 'theme' | 'dark';
|
||||
className?: string;
|
||||
}
|
||||
|
||||
export default function AppStoreCards({ tone = 'theme', className }: Props): React.ReactElement {
|
||||
const { t } = useTranslation();
|
||||
return (
|
||||
<div className={['asc-row', tone === 'dark' ? 'asc-dark' : '', className ?? ''].filter(Boolean).join(' ')}>
|
||||
{APP_STORES.map((s) => (
|
||||
<a key={s.id} className="asc-card" href={s.href} target="_blank" rel="noopener noreferrer">
|
||||
<span className="asc-qr" aria-hidden="true">
|
||||
<svg viewBox={`0 0 ${s.qrSize} ${s.qrSize}`} shapeRendering="crispEdges">
|
||||
<path className="asc-qr-dots" d={s.qr} />
|
||||
</svg>
|
||||
</span>
|
||||
<span className="asc-text">
|
||||
<span className="asc-caption">
|
||||
<svg className="asc-logo" viewBox="0 0 24 24" aria-hidden="true">
|
||||
<path d={s.logo} />
|
||||
</svg>
|
||||
{t(s.captionKey)}
|
||||
</span>
|
||||
<span className="asc-store">{s.store}</span>
|
||||
<span className="asc-devices">{t(s.devicesKey)}</span>
|
||||
</span>
|
||||
</a>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -8,7 +8,7 @@ import type { TourPlannerController } from '../Tours/planner/useTourPlanner'
|
||||
import ToursSidebar from '../Tours/ToursSidebar'
|
||||
import type { Day } from '../../types'
|
||||
import CustomSelect from './CustomSelect'
|
||||
import { hikePlannerDefaults } from '../../../tests/helpers/tourPlannerStub'
|
||||
import { hikePlannerDefaults, mockTourEditorLayout } from '../../../tests/helpers/tourPlannerStub'
|
||||
|
||||
vi.mock('../../repo/tourRepo', () => ({ tourRepo: {} }))
|
||||
vi.mock('../../store/settingsStore', () => ({
|
||||
@@ -57,6 +57,7 @@ describe('CustomSelect consumer contracts', () => {
|
||||
expect(screen.getByLabelText('Maximum trail difficulty')).toBe(trigger)
|
||||
expect(trigger).toHaveAttribute('id', 'tour-planner-difficulty')
|
||||
expect(document.querySelectorAll('[id="tour-planner-difficulty"]')).toHaveLength(1)
|
||||
mockTourEditorLayout(trigger.parentElement ?? trigger)
|
||||
await user.click(trigger)
|
||||
const menu = within(document.getElementById(trigger.getAttribute('aria-controls')!)!)
|
||||
for (const difficulty of [1, 2, 3, 4, 5, 6]) {
|
||||
@@ -132,4 +133,4 @@ describe('CustomSelect consumer contracts', () => {
|
||||
await user.click(screen.getByRole('button', { name: /^Planned\s*1$/ }))
|
||||
expect(setFilter).toHaveBeenLastCalledWith('planned')
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
@@ -1,9 +1,10 @@
|
||||
import React, { useState, useRef, useEffect, useId } from 'react'
|
||||
import { createPortal } from 'react-dom'
|
||||
import { ChevronDown, Check } from 'lucide-react'
|
||||
import { useAnchoredPosition, scrollAnchorIntoView } from '../../hooks/useAnchoredPosition'
|
||||
import { scrollAnchorIntoView } from '../../hooks/useAnchoredPosition'
|
||||
import { useTranslation } from '../../i18n'
|
||||
import { selectionHaptic } from '../../native/haptics'
|
||||
import { useAnchoredPopover } from './useAnchoredPopover'
|
||||
|
||||
interface SelectOption {
|
||||
// Callers use both string keys and numeric ids (e.g. day/place ids) as values, and
|
||||
@@ -85,7 +86,6 @@ export default function CustomSelect({
|
||||
menuFit = 'anchor',
|
||||
id,
|
||||
}: CustomSelectProps) {
|
||||
const [open, setOpen] = useState(false)
|
||||
const [search, setSearch] = useState('')
|
||||
const ref = useRef<HTMLDivElement>(null)
|
||||
const triggerRef = useRef<HTMLButtonElement>(null)
|
||||
@@ -97,23 +97,24 @@ export default function CustomSelect({
|
||||
|
||||
// Follows the trigger while the sheet scrolls and while the on-screen keyboard
|
||||
// resizes the viewport, instead of freezing at the rect measured on open (#1999).
|
||||
const anchored = useAnchoredPosition(ref, open)
|
||||
const { open, bounded, box: anchored, setOpen } = useAnchoredPopover(ref, { disabled })
|
||||
const menuOpen = open && (!bounded || !!anchored)
|
||||
|
||||
useEffect(() => {
|
||||
if (!open || !searchable || !searchRef.current) return
|
||||
if (!menuOpen || !searchable || !searchRef.current) return
|
||||
if (!keyboardDirection.current) searchRef.current.focus()
|
||||
// Focusing raises the keyboard on a phone; scroll the trigger up so the list
|
||||
// it just opened is not left underneath it (#2000).
|
||||
scrollAnchorIntoView(ref.current)
|
||||
}, [open, searchable])
|
||||
}, [menuOpen, searchable])
|
||||
|
||||
useEffect(() => {
|
||||
if (!open || !keyboardDirection.current) return
|
||||
if (!menuOpen || !keyboardDirection.current) return
|
||||
const buttons = dropRef.current?.querySelectorAll<HTMLButtonElement>('button')
|
||||
const direction = keyboardDirection.current
|
||||
keyboardDirection.current = null
|
||||
if (buttons?.length) buttons[direction === 'last' ? buttons.length - 1 : 0].focus()
|
||||
}, [open])
|
||||
}, [menuOpen])
|
||||
|
||||
useEffect(() => {
|
||||
const handleClick = (e: MouseEvent) => {
|
||||
@@ -123,7 +124,7 @@ export default function CustomSelect({
|
||||
}
|
||||
if (open) document.addEventListener('mousedown', handleClick)
|
||||
return () => document.removeEventListener('mousedown', handleClick)
|
||||
}, [open])
|
||||
}, [open, setOpen])
|
||||
|
||||
const selected = options.find(o => sameValue(value, o.value))
|
||||
const filtered = searchable && search
|
||||
@@ -152,6 +153,8 @@ export default function CustomSelect({
|
||||
: options
|
||||
|
||||
const sm = size === 'sm'
|
||||
const availableOptionsHeight = (anchored?.maxHeight ?? 220) - (searchable ? 38 : 0)
|
||||
const optionsHeight = bounded ? Math.max(0, availableOptionsHeight - 2) : Math.max(96, availableOptionsHeight)
|
||||
|
||||
const closeMenu = () => {
|
||||
setOpen(false)
|
||||
@@ -223,7 +226,7 @@ export default function CustomSelect({
|
||||
</button>
|
||||
|
||||
{/* Dropdown */}
|
||||
{open && createPortal(
|
||||
{menuOpen && createPortal(
|
||||
<div ref={dropRef} id={menuId} role="group" aria-label={ariaLabel || selected?.label || placeholder || undefined} onKeyDown={handleKeyDown} style={{
|
||||
position: 'fixed',
|
||||
...(anchored
|
||||
@@ -233,7 +236,7 @@ export default function CustomSelect({
|
||||
// Never narrower than the trigger, and never past the right-hand edge of
|
||||
// the window. The cap is read at render time rather than measured, and
|
||||
// that is enough: every reason the anchor moved already re-renders this.
|
||||
...(menuFit === 'content'
|
||||
...(!bounded && menuFit === 'content'
|
||||
? {
|
||||
minWidth: anchored.width,
|
||||
width: 'max-content',
|
||||
@@ -251,6 +254,7 @@ export default function CustomSelect({
|
||||
boxShadow: '0 8px 32px rgba(0,0,0,0.12)',
|
||||
overflow: 'hidden',
|
||||
animation: 'trek-menu-enter 200ms cubic-bezier(0.23, 1, 0.32, 1)',
|
||||
overflowWrap: bounded ? 'anywhere' : undefined,
|
||||
transformOrigin: anchored?.flipped ? 'bottom center' : 'top center',
|
||||
willChange: 'transform, opacity',
|
||||
}}>
|
||||
@@ -277,7 +281,7 @@ export default function CustomSelect({
|
||||
{/* Options — capped at whatever the viewport still shows, so a list opened
|
||||
beside an on-screen keyboard shrinks instead of hiding under it (#2000). */}
|
||||
<div style={{
|
||||
maxHeight: Math.min(220, Math.max(96, (anchored?.maxHeight ?? 220) - (searchable ? 38 : 0))),
|
||||
maxHeight: Math.min(220, optionsHeight),
|
||||
overflowY: 'auto',
|
||||
// The panel is portaled to document.body and positioned fixed, so its
|
||||
// scroll chain runs to the viewport rather than to the sheet it looks
|
||||
|
||||
@@ -0,0 +1,124 @@
|
||||
/* The store cards: a QR code on its white tile, the store's mark and name beside it.
|
||||
The theme tone follows the appearance tokens; .asc-dark is for a surface that is
|
||||
dark in either theme (the release modal). */
|
||||
|
||||
.asc-row {
|
||||
display: grid;
|
||||
/* Always side by side: two compact cards read as one row of stores. */
|
||||
grid-template-columns: repeat(2, minmax(0, 1fr));
|
||||
gap: 10px;
|
||||
}
|
||||
|
||||
.asc-card {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
min-width: 0;
|
||||
padding: 8px 12px 8px 8px;
|
||||
border-radius: 16px;
|
||||
border: 1px solid var(--border-faint);
|
||||
background: var(--bg-card);
|
||||
color: var(--text-primary);
|
||||
text-decoration: none;
|
||||
transition:
|
||||
transform 160ms ease,
|
||||
border-color 160ms ease,
|
||||
box-shadow 160ms ease;
|
||||
}
|
||||
.asc-card:hover {
|
||||
transform: translateY(-1px);
|
||||
border-color: var(--border-primary);
|
||||
box-shadow: 0 10px 24px -14px rgb(0 0 0 / 0.35); /* a neutral lift shadow */
|
||||
}
|
||||
.asc-card:focus-visible {
|
||||
outline: 2px solid var(--accent);
|
||||
outline-offset: 2px;
|
||||
}
|
||||
|
||||
/* A QR code needs its light quiet zone in either theme to scan. */
|
||||
.asc-qr {
|
||||
flex: none;
|
||||
display: grid;
|
||||
place-items: center;
|
||||
width: 56px;
|
||||
height: 56px;
|
||||
padding: 5px;
|
||||
border-radius: 10px;
|
||||
background: #ffffff; /* a QR code needs a white quiet zone to scan */
|
||||
border: 1px solid var(--border-faint);
|
||||
}
|
||||
.asc-qr svg {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
display: block;
|
||||
}
|
||||
.asc-qr-dots {
|
||||
fill: none;
|
||||
stroke: #0f172a;
|
||||
} /* QR modules stay dark on their white tile */
|
||||
|
||||
.asc-text {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
min-width: 0;
|
||||
line-height: 1.2;
|
||||
}
|
||||
.asc-caption {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
font-size: calc(10.5px * var(--fs-scale-caption, 1));
|
||||
color: var(--text-muted);
|
||||
white-space: nowrap;
|
||||
}
|
||||
.asc-logo {
|
||||
width: 12px;
|
||||
height: 12px;
|
||||
flex: none;
|
||||
fill: currentColor;
|
||||
}
|
||||
.asc-store {
|
||||
margin-top: 2px;
|
||||
font-size: calc(16px * var(--fs-scale-subtitle, 1));
|
||||
font-weight: 700;
|
||||
letter-spacing: -0.02em;
|
||||
color: var(--text-primary);
|
||||
white-space: nowrap;
|
||||
}
|
||||
.asc-devices {
|
||||
margin-top: 2px;
|
||||
font-size: calc(10.5px * var(--fs-scale-caption, 1));
|
||||
color: var(--text-muted);
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.asc-dark .asc-card {
|
||||
background: linear-gradient(160deg, oklch(1 0 0 / 0.1) 0%, oklch(1 0 0 / 0.045) 62%);
|
||||
border-color: oklch(1 0 0 / 0.13);
|
||||
color: #f5f5f7; /* the release modal is dark in either theme */
|
||||
box-shadow: inset 0 1px 0 oklch(1 0 0 / 0.16);
|
||||
}
|
||||
.asc-dark .asc-card:hover {
|
||||
border-color: oklch(1 0 0 / 0.26);
|
||||
}
|
||||
.asc-dark .asc-qr {
|
||||
border-color: transparent;
|
||||
}
|
||||
.asc-dark .asc-store {
|
||||
color: #f5f5f7;
|
||||
} /* the release modal is dark in either theme */
|
||||
.asc-dark .asc-caption,
|
||||
.asc-dark .asc-devices {
|
||||
color: oklch(1 0 0 / 0.6);
|
||||
}
|
||||
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.asc-card {
|
||||
transition: none;
|
||||
}
|
||||
.asc-card:hover {
|
||||
transform: none;
|
||||
}
|
||||
}
|
||||
@@ -161,12 +161,15 @@ export function PopoverListPanel({ list, label, className = '', children }: {
|
||||
className?: string
|
||||
children: ReactNode
|
||||
}) {
|
||||
const { open, box, menuRef, listId, onListKey } = list
|
||||
const { open, box, bounded, menuRef, listId, onListKey } = list
|
||||
if (!open || !box) return null
|
||||
return createPortal(
|
||||
<div ref={menuRef} id={listId} role="group" aria-label={label} onKeyDown={onListKey}
|
||||
className={`fixed z-[var(--z-toast)] overflow-y-auto ${className}`}
|
||||
style={{ ...POPOVER, top: box.top, bottom: box.bottom, left: box.left, maxHeight: box.maxHeight }}>
|
||||
className={`fixed z-[var(--z-toast)] overflow-y-auto ${bounded ? 'overflow-x-hidden overscroll-contain [overflow-wrap:anywhere] [&>button]:shrink-0' : ''} ${className}`}
|
||||
style={{
|
||||
...POPOVER, top: box.top, bottom: box.bottom, left: box.left, width: box.width || undefined, maxHeight: box.maxHeight,
|
||||
minWidth: bounded ? 0 : undefined,
|
||||
}}>
|
||||
{children}
|
||||
</div>,
|
||||
document.body,
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
import { createContext, use, useCallback, useState, type RefObject } from 'react';
|
||||
import { useAnchoredPosition } from '../../hooks/useAnchoredPosition';
|
||||
|
||||
/** The scrolling content that contains a panel's dropdown triggers. */
|
||||
export const PopoverBoundary = createContext<RefObject<HTMLElement | null> | null>(null);
|
||||
|
||||
export function useAnchoredPopover(
|
||||
anchorRef: RefObject<HTMLElement | null>,
|
||||
{
|
||||
disabled = false,
|
||||
estimatedHeight,
|
||||
matchWidth = true,
|
||||
}: {
|
||||
disabled?: boolean;
|
||||
estimatedHeight?: number;
|
||||
matchWidth?: boolean;
|
||||
}
|
||||
) {
|
||||
const boundaryRef = use(PopoverBoundary);
|
||||
const bounded = !!boundaryRef;
|
||||
const unavailable = bounded && disabled;
|
||||
const [expanded, setOpen] = useState(false);
|
||||
if (unavailable && expanded) setOpen(false);
|
||||
const open = expanded && !unavailable;
|
||||
const hide = useCallback(() => setOpen(false), []);
|
||||
const box = useAnchoredPosition(anchorRef, open, {
|
||||
matchWidth: bounded || matchWidth,
|
||||
estimatedHeight,
|
||||
boundary: boundaryRef ? { ref: boundaryRef, onAnchorHidden: hide } : undefined,
|
||||
});
|
||||
return { open, box, bounded, setOpen };
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user