mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-11-28 23:50:08 +00:00
Compare commits
158 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 6068c34c35 | |||
| 06b08cd9d5 | |||
| 10713e41cd | |||
| d78dc79e21 | |||
| 4f8c3f045e | |||
| c7cb0bc067 | |||
| 68af65a2a6 | |||
| 04d134755a | |||
| 8510d4a729 | |||
| 5989ba5f1f | |||
| 7c0c749bcc | |||
| 94163f76e0 | |||
| c39f739b7f | |||
| 7e9ab58a16 | |||
| 41772c0d8e | |||
| d6ce33c51c | |||
| edb1eab0c3 | |||
| 91a37286ca | |||
| 382c1a78dc | |||
| b3c2f0b7e2 | |||
| c785a0950a | |||
| c8615e0362 | |||
| bc6b56c84c | |||
| c00b6dd636 | |||
| 7e01f9661b | |||
| dee1a361c3 | |||
| d94f97f9ae | |||
| aad9272b2e | |||
| 59f6e349bf | |||
| dc4b7854d7 | |||
| a4446f16be | |||
| 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'
|
||||
|
||||
+22
-14
@@ -35,7 +35,7 @@ permissions:
|
||||
# Server tests i/10 one slice of the server suite, with coverage
|
||||
# Server coverage merges the slices, checks the per-domain
|
||||
# thresholds, uploads lcov
|
||||
# Server Postgres 14 i/3, Server Postgres 18 i/3
|
||||
# Server Postgres 14 i/3, Server Postgres 19 i/3
|
||||
# per supported major, in three slices: the probe
|
||||
# (the repository SQL against Postgres, first slice
|
||||
# only), then a slice of the lane (every suite that
|
||||
@@ -55,7 +55,7 @@ permissions:
|
||||
# Client e2e i/2 one slice of the browser flows in Chromium and
|
||||
# WebKit, in the Playwright container
|
||||
# Docker and Helm builds the image and boots it until ready, on
|
||||
# SQLite and on Postgres 18; lints and renders the
|
||||
# SQLite and on Postgres 19; lints and renders the
|
||||
# Helm chart and checks the compose files
|
||||
# Sonar SonarCloud analysis, not required
|
||||
# ci-ok the one required check (below)
|
||||
@@ -600,7 +600,7 @@ jobs:
|
||||
uses: actions/upload-artifact@v6
|
||||
with:
|
||||
name: server-blob-${{ matrix.shard }}
|
||||
path: server/.vitest-reports/
|
||||
path: server/.vitest/blob/
|
||||
include-hidden-files: true
|
||||
if-no-files-found: error
|
||||
retention-days: 1
|
||||
@@ -621,7 +621,7 @@ jobs:
|
||||
uses: actions/download-artifact@v7
|
||||
with:
|
||||
pattern: server-blob-*
|
||||
path: server/.vitest-reports/
|
||||
path: server/.vitest/blob/
|
||||
merge-multiple: true
|
||||
|
||||
- name: Merge the slices and check the thresholds
|
||||
@@ -639,7 +639,7 @@ jobs:
|
||||
retention-days: 1
|
||||
|
||||
# TREK on Postgres, once per supported major: the oldest (14) and the newest
|
||||
# (18). Both steps run against the same service, the probe on an empty
|
||||
# (19). Both steps run against the same service, the probe on an empty
|
||||
# database of its own, the lane on databases it creates and drops.
|
||||
#
|
||||
# The probe (server/scripts/pg-probe.ts): against an empty Postgres it
|
||||
@@ -696,7 +696,7 @@ jobs:
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
postgres: [14, 18]
|
||||
postgres: [14, 19]
|
||||
shard: [1, 2, 3]
|
||||
services:
|
||||
postgres:
|
||||
@@ -757,14 +757,14 @@ jobs:
|
||||
if-no-files-found: ignore
|
||||
retention-days: 14
|
||||
|
||||
# The image ships the 18 client tools, which write settings a 14 server
|
||||
# The image ships the 19 client tools, which write settings a 14 server
|
||||
# does not know; the backup round trip runs with the same tools here.
|
||||
- name: Install the PostgreSQL 18 client tools
|
||||
- name: Install the PostgreSQL 19 client tools
|
||||
run: |
|
||||
set -euo pipefail
|
||||
sudo /usr/share/postgresql-common/pgdg/apt.postgresql.org.sh -y >/dev/null
|
||||
sudo apt-get install -y --no-install-recommends postgresql-client-18 >/dev/null
|
||||
/usr/lib/postgresql/18/bin/pg_restore --version
|
||||
sudo apt-get install -y --no-install-recommends postgresql-client-19 >/dev/null
|
||||
/usr/lib/postgresql/19/bin/pg_restore --version
|
||||
|
||||
- name: Run the Postgres lane
|
||||
if: ${{ !cancelled() }}
|
||||
@@ -1028,7 +1028,7 @@ jobs:
|
||||
uses: actions/upload-artifact@v6
|
||||
with:
|
||||
name: client-blob-${{ matrix.shard }}
|
||||
path: client/.vitest-reports/
|
||||
path: client/.vitest/blob/
|
||||
include-hidden-files: true
|
||||
if-no-files-found: error
|
||||
retention-days: 1
|
||||
@@ -1049,7 +1049,7 @@ jobs:
|
||||
uses: actions/download-artifact@v7
|
||||
with:
|
||||
pattern: client-blob-*
|
||||
path: client/.vitest-reports/
|
||||
path: client/.vitest/blob/
|
||||
merge-multiple: true
|
||||
|
||||
- name: Merge the slices and check the thresholds
|
||||
@@ -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.
|
||||
@@ -1339,7 +1347,7 @@ jobs:
|
||||
set -euo pipefail
|
||||
docker network create trek-ci-pg
|
||||
docker run -d --name trek-ci-db --network trek-ci-pg \
|
||||
-e POSTGRES_PASSWORD=ci -e POSTGRES_DB=trek postgres:18
|
||||
-e POSTGRES_PASSWORD=ci -e POSTGRES_DB=trek postgres:19
|
||||
for _ in $(seq 1 30); do
|
||||
docker exec trek-ci-db pg_isready -U postgres -d trek >/dev/null 2>&1 && break
|
||||
sleep 2
|
||||
@@ -1460,7 +1468,7 @@ jobs:
|
||||
path: plugin-sdk/coverage/
|
||||
|
||||
- name: Scan
|
||||
uses: SonarSource/sonarqube-scan-action@59202af334b4ba7b5db01b701b8e79f8b3bef0f4 # v8.5.0
|
||||
uses: SonarSource/sonarqube-scan-action@70bad232163b09d998ea0707ee80c0ec80798c16 # v8.5.1
|
||||
env:
|
||||
# SonarQube Cloud is the scan action's default host, so no
|
||||
# SONAR_HOST_URL — the token is a sonarcloud.io token for the
|
||||
|
||||
+5
-1
@@ -55,7 +55,8 @@ coverage
|
||||
coverage-*/
|
||||
*.lcov
|
||||
.nyc_output
|
||||
# Blob reports of a sharded vitest run (test.yml)
|
||||
# Blob reports of a sharded vitest run (test.yml) and the other files vitest writes
|
||||
.vitest
|
||||
.vitest-reports
|
||||
|
||||
# Cache
|
||||
@@ -73,3 +74,6 @@ minio-licence.key
|
||||
|
||||
.run
|
||||
.full-review
|
||||
|
||||
# Built by server/scripts/build-atlas-mesh.mjs (npm run dev/build, Docker build)
|
||||
server/assets/atlas-mesh/
|
||||
|
||||
@@ -137,7 +137,7 @@ These principles come out of a full-repo audit and shape all new code:
|
||||
|
||||
## Quality gates in CI
|
||||
|
||||
`.github/workflows/test.yml` runs, per package: typecheck (server also `typecheck:tests`, client also the strict-mode ratchet `lint:strict`), lint (client and server through `lint:warnings`, which also holds the warning count per rule), `lint:pages`, `lint:rtl`, `lint:size` (client and server), the server's `lint:strict`, `lint:boundaries`, `lint:tx`, `lint:dialect`, `lint:engine-dispatch`, `lint:test-sql`, `lint:test-mocks`, `lint:test-new-service`, `lint:query-api`, `lint:mcp-zod`, `lint:service-http` and `lint:response-contracts`, the client's and server's `lint:format`, `lint:layers`, `lint:offline`, `lint:dup`, `lint:pairs`, `lint:skips`, `lint:i18n-keys` and `theme:lint`, shared's `contracts:open`, the repo-wide `lint:knip` (in `server-lint`), `check:plugin-facts`, `i18n:parity:strict` (with the untranslated-strings ratchet), the S3 contract suite, TREK on Postgres (`server-postgres`, once per supported major, 14 and 18, each in three slices: first the Postgres probe (in the first slice), every dialect helper on SQLite and Postgres and the statements every repository method reaches with sample arguments, its SQL errors per method and the methods it cannot measure held to a baseline that only shrinks and fails while it is still unmeasured; then the Postgres lane, every suite that boots the app on the real database module, found by `server/tests/postgres/lane.ts` rather than listed, plus PARITY-PG and the write lock; see `server/CLAUDE.md`), the browser end-to-end flows (Chromium and WebKit, in the Playwright container, in two slices), a client build with `check:gl-split`, coverage for all four packages, then a SonarCloud scan. It also builds the Docker image and boots it until `/api/health/ready` answers, on SQLite and on Postgres 18, and lints and renders the Helm chart against the Kubernetes schemas and runs `docker compose config` on every compose file (both in `docker`, each part when its area changed). `lint-prettier.yml` additionally runs `lint` + `lint:format` on `shared/`, both check-only. `plugin-sdk` has no lint script and is outside the eslint gates. **Not in CI**: the screenshot and help-media Playwright projects; run them locally. There are no git hooks; nothing runs before a commit except you. Other workflows build Docker images, scan them, and publish `trek-plugin-sdk` on `plugin-sdk-v*` tags.
|
||||
`.github/workflows/test.yml` runs, per package: typecheck (server also `typecheck:tests`, client also the strict-mode ratchet `lint:strict`), lint (client and server through `lint:warnings`, which also holds the warning count per rule), `lint:pages`, `lint:rtl`, `lint:size` (client and server), the server's `lint:strict`, `lint:boundaries`, `lint:tx`, `lint:dialect`, `lint:engine-dispatch`, `lint:test-sql`, `lint:test-mocks`, `lint:test-new-service`, `lint:query-api`, `lint:mcp-zod`, `lint:service-http` and `lint:response-contracts`, the client's and server's `lint:format`, `lint:layers`, `lint:offline`, `lint:dup`, `lint:pairs`, `lint:skips`, `lint:i18n-keys` and `theme:lint`, shared's `contracts:open`, the repo-wide `lint:knip` (in `server-lint`), `check:plugin-facts`, `i18n:parity:strict` (with the untranslated-strings ratchet), the S3 contract suite, TREK on Postgres (`server-postgres`, once per supported major, 14 and 19, each in three slices: first the Postgres probe (in the first slice), every dialect helper on SQLite and Postgres and the statements every repository method reaches with sample arguments, its SQL errors per method and the methods it cannot measure held to a baseline that only shrinks and fails while it is still unmeasured; then the Postgres lane, every suite that boots the app on the real database module, found by `server/tests/postgres/lane.ts` rather than listed, plus PARITY-PG and the write lock; see `server/CLAUDE.md`), the browser end-to-end flows (Chromium and WebKit, in the Playwright container, in two slices), a client build with `check:gl-split`, coverage for all four packages, then a SonarCloud scan. It also builds the Docker image and boots it until `/api/health/ready` answers, on SQLite and on Postgres 19, and lints and renders the Helm chart against the Kubernetes schemas and runs `docker compose config` on every compose file (both in `docker`, each part when its area changed). `lint-prettier.yml` additionally runs `lint` + `lint:format` on `shared/`, both check-only. `plugin-sdk` has no lint script and is outside the eslint gates. **Not in CI**: the screenshot and help-media Playwright projects; run them locally. There are no git hooks; nothing runs before a commit except you. Other workflows build Docker images, scan them, and publish `trek-plugin-sdk` on `plugin-sdk-v*` tags.
|
||||
|
||||
- **Job names read "<Area> <what>[ <variant>][ i/n]"** (`Server tests 3/10`, `Server Postgres 14 2/3`, `Docker and Helm`): the area first, one of Changes, Shared, Server, Client, Docker or Sonar, then lower case, with no colon, no parentheses and no middle dot, and a slice only at the end, so the checks list sorts by area. The workflow is named `CI`, so a check reads `CI / Server tests 3/10`. Job ids are the names in kebab-case (`server-tests`), the jobs stand in `test.yml` in area order, and the list at the top of `test.yml` says what each job holds. A new job follows the scheme and joins that list; `scripts/ci/workflow-jobs.test.mjs` fails on a name outside it. `ci-ok`, `lint` and `check-target` keep their names: the ruleset requires them by name.
|
||||
- **What the folded jobs hold.** `Shared tests` is the plugin SDK's typecheck and coverage, run before the root install so the SDK resolves only its own dependencies, then i18n parity and shared's coverage. `Client types` is the typecheck and the strict ratchet; `Client checks` the source ratchets, then the production build with `check:gl-split`. `Docker and Helm` builds and boots the image when the image area changed and checks the chart and compose files when the deploy area changed. Inside a folded job each group of steps runs after a failure in another, so one red check shows every gate that failed; the step names say which.
|
||||
|
||||
+23
-12
@@ -41,9 +41,10 @@ COPY server/package.json ./server/
|
||||
RUN npm ci --workspace=server --ignore-scripts
|
||||
COPY --from=shared-builder /app/shared/dist ./shared/dist
|
||||
COPY server/ ./server/
|
||||
# tsc needs more than the 2 GB heap Node picks on a host with about 12 GB of RAM;
|
||||
# on a bigger build machine the default is larger, so only small hosts failed.
|
||||
RUN NODE_OPTIONS=--max-old-space-size=4096 npm run build --workspace=server
|
||||
# The globe Atlas geometry is built from the committed boundary files (no network,
|
||||
# deterministic) here rather than committed; it lands in server/assets with the rest.
|
||||
RUN node server/scripts/build-atlas-mesh.mjs
|
||||
RUN npm run build --workspace=server
|
||||
|
||||
# ── Stage 4: production runtime ──────────────────────────────────────────────
|
||||
FROM node:24-trixie-slim
|
||||
@@ -73,22 +74,30 @@ COPY server/package.json ./server/
|
||||
# The upgrade takes the Debian security fixes the base image was built before
|
||||
# (zlib, 11/2026, failed the image scan until node:24-trixie-slim caught up).
|
||||
#
|
||||
# postgresql-client-18 brings pg_dump, pg_restore and psql to
|
||||
# /usr/lib/postgresql/18/bin, which back up and restore an install on Postgres
|
||||
# postgresql-client-19 brings pg_dump, pg_restore and psql to
|
||||
# /usr/lib/postgresql/19/bin, which back up and restore an install on Postgres
|
||||
# (TREK_DB_URL). A client handles every server up to its own major and refuses
|
||||
# a newer one, so the image carries the newest major TREK supports (14 to 18).
|
||||
# a newer one, so the image carries the newest major TREK supports (14 to 19).
|
||||
# Debian 13 ships 17 only, so it comes from the PostgreSQL project's apt
|
||||
# repository (PGDG): the `18` component lists that major's packages and no
|
||||
# other, and the repository's signing key (fingerprint B97B 0AFC AA1A 47F0 44F2
|
||||
# 44A0 7FCC 7D46 ACCC 4CF8) is kept beside the entrypoint instead of fetched at
|
||||
# build time. Raise both together when TREK supports a newer major.
|
||||
# repository (PGDG): its `main` component carries every major the project
|
||||
# supports, and the package name pins the one installed. The per-major
|
||||
# components can trail a new release, so the image does not rely on them. The
|
||||
# repository's signing key (fingerprint B97B 0AFC AA1A 47F0 44F2 44A0 7FCC 7D46
|
||||
# ACCC 4CF8) is kept beside the entrypoint instead of fetched at build time.
|
||||
# Raise the package together with SUPPORTED_SERVER_MAJORS in
|
||||
# server/src/db/engine/postgres/server-checks.ts.
|
||||
# Earlier images carried the version 18 tools, and installs that set
|
||||
# TREK_DB_PG_BIN_DIR=/usr/lib/postgresql/18/bin (the old .env.example value)
|
||||
# would lose backups and the pre-migrate snapshot after updating, so that path
|
||||
# stays as a link to the 19 tools, which handle every supported server.
|
||||
COPY server/scripts/pgdg-apt-key.asc /etc/apt/keyrings/pgdg.asc
|
||||
RUN echo 'deb [signed-by=/etc/apt/keyrings/pgdg.asc] http://apt.postgresql.org/pub/repos/apt trixie-pgdg main 18' \
|
||||
RUN echo 'deb [signed-by=/etc/apt/keyrings/pgdg.asc] http://apt.postgresql.org/pub/repos/apt trixie-pgdg main' \
|
||||
> /etc/apt/sources.list.d/pgdg.list && \
|
||||
apt-get update && \
|
||||
apt-get upgrade -y --no-install-recommends && \
|
||||
apt-get install -y --no-install-recommends tzdata dumb-init wget ca-certificates \
|
||||
libkitinerary-bin libsqlite3-0 postgresql-client-18 && \
|
||||
libkitinerary-bin libsqlite3-0 postgresql-client-19 && \
|
||||
mkdir -p /usr/lib/postgresql/18 && ln -s /usr/lib/postgresql/19/bin /usr/lib/postgresql/18/bin && \
|
||||
npm ci --workspace=server --omit=dev --ignore-scripts && \
|
||||
{ ln -sf "$(find /usr/lib -name kitinerary-extractor -type f | head -1)" /usr/local/bin/kitinerary-extractor || true; } && \
|
||||
rm -rf /var/lib/apt/lists/* /usr/local/lib/node_modules/npm /usr/local/bin/npm /usr/local/bin/npx && \
|
||||
@@ -101,6 +110,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>
|
||||
|
||||
@@ -323,7 +288,7 @@ docker compose up -d
|
||||
See [Install with Docker Compose](https://github.com/liketrek/TREK/wiki/Install-Docker-Compose)
|
||||
for the full walkthrough.
|
||||
|
||||
TREK stores its data in SQLite by default. Set `TREK_DB_URL` to run it on a PostgreSQL 14 to 18 database instead. The
|
||||
TREK stores its data in SQLite by default. Set `TREK_DB_URL` to run it on a PostgreSQL 14 to 19 database instead. The
|
||||
[`docker-compose.postgres.yml`](docker-compose.postgres.yml) example starts one beside TREK, and the
|
||||
[Postgres guide](https://github.com/liketrek/TREK/wiki/Database-Postgres) covers the requirements, the backups and
|
||||
how to move an existing SQLite install to Postgres with the command TREK ships for it.
|
||||
@@ -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,8 @@
|
||||
apiVersion: v2
|
||||
name: trek
|
||||
version: 5.1.4
|
||||
version: 5.2.2
|
||||
description: Minimal Helm chart for TREK app
|
||||
appVersion: "5.1.4"
|
||||
home: https://github.com/liketrek/TREK
|
||||
sources:
|
||||
- https://github.com/liketrek/TREK
|
||||
appVersion: "5.2.2"
|
||||
|
||||
@@ -0,0 +1,8 @@
|
||||
{{- range .Values.extraObjects }}
|
||||
---
|
||||
{{- if kindIs "string" . }}
|
||||
{{ tpl . $ }}
|
||||
{{- else }}
|
||||
{{ tpl (toYaml .) $ }}
|
||||
{{- end }}
|
||||
{{- end }}
|
||||
+24
-1
@@ -190,7 +190,7 @@ env:
|
||||
# starting it on SQLite. The role in the URL owns TREK's database and must not be a superuser
|
||||
# (nor a member of one, nor hold a right that reaches the server's files or programs): a
|
||||
# restore runs the backup's SQL as that role and refuses one that could reach the database host. The wiki page shows the
|
||||
# SQL that creates such a role. PostgreSQL 14 to 18 is supported.
|
||||
# SQL that creates such a role. PostgreSQL 14 to 19 is supported.
|
||||
# url: "postgres://trek:<password>@postgres.example.internal:5432/trek?sslmode=require"
|
||||
database:
|
||||
url: ""
|
||||
@@ -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();
|
||||
}
|
||||
});
|
||||
@@ -102,9 +102,9 @@ test('#1809 iPhone: flow screens scroll the document, full-screen ones do not',
|
||||
// deliberately do NOT scroll the document (and so keep the address bar), and
|
||||
// the map must not collapse to zero height now that the shell has none.
|
||||
await page.goto('/atlas')
|
||||
await expect(page.locator('.leaflet-container')).toBeVisible({ timeout: 20_000 })
|
||||
await expect(page.locator('canvas[aria-label="Atlas"]')).toBeVisible({ timeout: 20_000 })
|
||||
const atlas = await page.evaluate(() => {
|
||||
const map = document.querySelector('.leaflet-container') as HTMLElement
|
||||
const map = document.querySelector('canvas[aria-label="Atlas"]') as HTMLElement
|
||||
window.scrollBy(0, 400)
|
||||
return {
|
||||
top: document.scrollingElement!.scrollTop,
|
||||
|
||||
@@ -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%;
|
||||
}
|
||||
|
||||
+20
-16
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@trek/client",
|
||||
"version": "5.1.4",
|
||||
"version": "5.2.2",
|
||||
"engines": {
|
||||
"node": "^22.22.2 || ^24.15.0 || >=26.0.0"
|
||||
},
|
||||
@@ -53,7 +53,7 @@
|
||||
"format:check": "prettier --check \"src/**/*.tsx\" \"src/**/*.css\""
|
||||
},
|
||||
"dependencies": {
|
||||
"@assistant-ui/react": "0.15.37",
|
||||
"@assistant-ui/react": "0.15.38",
|
||||
"@capacitor/action-sheet": "^8.1.1",
|
||||
"@capacitor/android": "^8.6.2",
|
||||
"@capacitor/app": "^8.1.1",
|
||||
@@ -102,23 +102,24 @@
|
||||
"@fontsource/shrikhand": "^5.3.0",
|
||||
"@fontsource/yellowtail": "^5.3.0",
|
||||
"@maplibre/maplibre-gl-leaflet": "0.1.4",
|
||||
"@noble/hashes": "^1.8.0",
|
||||
"@simplewebauthn/browser": "^13.3.0",
|
||||
"@noble/hashes": "^2.4.0",
|
||||
"@simplewebauthn/browser": "^14.0.0",
|
||||
"@trek/shared": "*",
|
||||
"axios": "^1.21.0",
|
||||
"dexie": "^4.4.7",
|
||||
"drag-drop-touch": "^1.3.1",
|
||||
"earcut": "^3.0.2",
|
||||
"heic-to": "^1.6.7",
|
||||
"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",
|
||||
@@ -126,6 +127,7 @@
|
||||
"rehype-sanitize": "^6.0.0",
|
||||
"remark-breaks": "^4.0.0",
|
||||
"remark-gfm": "^4.0.1",
|
||||
"topojson-client": "^3.1.0",
|
||||
"tz-lookup": "^6.1.25",
|
||||
"zod": "^4.6.7",
|
||||
"zustand": "^5.0.15"
|
||||
@@ -136,16 +138,18 @@
|
||||
"@jscpd/core": "^4.2.5",
|
||||
"@jscpd/tokenizer": "^4.2.6",
|
||||
"@playwright/test": "^1.65.1",
|
||||
"@testing-library/jest-dom": "^6.10.0",
|
||||
"@testing-library/dom": "^10.4.1",
|
||||
"@testing-library/jest-dom": "^8.0.0",
|
||||
"@testing-library/react": "^16.3.3",
|
||||
"@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/react": "^19.3.0",
|
||||
"@trivago/prettier-plugin-sort-imports": "^6.0.3",
|
||||
"@types/leaflet": "^1.9.23",
|
||||
"@types/node": "^26.6.11",
|
||||
"@types/react": "^19.3.2",
|
||||
"@types/react-dom": "^19.3.0",
|
||||
"@types/topojson-client": "^3.1.5",
|
||||
"@vitejs/plugin-react": "^6.2.1",
|
||||
"@vitest/coverage-v8": "^4.1.12",
|
||||
"@vitest/coverage-v8": "^5.1.2",
|
||||
"autoprefixer": "^10.7.0",
|
||||
"eslint": "^10.11.0",
|
||||
"eslint-config-flat-gitignore": "^2.4.0",
|
||||
@@ -154,18 +158,18 @@
|
||||
"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",
|
||||
"prettier-plugin-tailwindcss": "^0.8.1",
|
||||
"rollup-plugin-visualizer": "^7.1.2",
|
||||
"rollup-plugin-visualizer": "^7.3.0",
|
||||
"sharp": "^0.35.5",
|
||||
"tailwindcss": "^3.4.19",
|
||||
"typescript": "^6.0.3",
|
||||
"typescript-eslint": "^8.72.1",
|
||||
"typescript-eslint": "^8.74.0",
|
||||
"vite": "8.3.8",
|
||||
"vite-plugin-pwa": "^2.0.0",
|
||||
"vitest": "^4.1.12"
|
||||
"vitest": "^5.1.2"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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,24 +1,24 @@
|
||||
{
|
||||
"src": {
|
||||
"@typescript-eslint/no-non-null-assertion": 367,
|
||||
"@typescript-eslint/no-misused-promises": 820,
|
||||
"no-console": 88,
|
||||
"complexity": 216,
|
||||
"@typescript-eslint/no-explicit-any": 138,
|
||||
"trek/no-swallowed-catch": 126,
|
||||
"@typescript-eslint/no-non-null-assertion": 345,
|
||||
"@typescript-eslint/no-misused-promises": 812,
|
||||
"no-console": 85,
|
||||
"complexity": 215,
|
||||
"@typescript-eslint/no-explicit-any": 114,
|
||||
"trek/no-swallowed-catch": 124,
|
||||
"max-params": 31,
|
||||
"trek/store-without-selector": 66,
|
||||
"react-hooks/refs": 534,
|
||||
"react-hooks/set-state-in-effect": 189,
|
||||
"trek/store-without-selector": 65,
|
||||
"react-hooks/refs": 522,
|
||||
"react-hooks/set-state-in-effect": 188,
|
||||
"@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/exhaustive-deps": 112,
|
||||
"@typescript-eslint/no-unused-vars": 100,
|
||||
"react-hooks/immutability": 26,
|
||||
"max-lines-per-function": 126,
|
||||
"react-hooks/static-components": 38,
|
||||
"react-hooks/preserve-manual-memoization": 12,
|
||||
"no-useless-assignment": 7,
|
||||
"no-empty": 19,
|
||||
"no-empty": 18,
|
||||
"trek/no-window-globals": 41,
|
||||
"react-refresh/only-export-components": 44,
|
||||
"unused-disable-directive": 5,
|
||||
@@ -34,18 +34,17 @@
|
||||
"react-hooks/exhaustive-deps": 44
|
||||
},
|
||||
"tests": {
|
||||
"@typescript-eslint/no-explicit-any": 489,
|
||||
"@typescript-eslint/no-non-null-assertion": 1872,
|
||||
"@typescript-eslint/no-explicit-any": 484,
|
||||
"@typescript-eslint/no-non-null-assertion": 1849,
|
||||
"@typescript-eslint/no-misused-promises": 22,
|
||||
"@typescript-eslint/no-unused-vars": 51,
|
||||
"@typescript-eslint/no-unused-vars": 48,
|
||||
"@typescript-eslint/no-floating-promises": 33,
|
||||
"trek/no-window-globals": 325,
|
||||
"trek/no-swallowed-catch": 14,
|
||||
"react-hooks/globals": 5,
|
||||
"react-hooks/refs": 22,
|
||||
"trek/no-window-globals": 321,
|
||||
"trek/no-swallowed-catch": 6,
|
||||
"react-hooks/globals": 4,
|
||||
"react-hooks/refs": 16,
|
||||
"@typescript-eslint/no-this-alias": 1,
|
||||
"trek/store-without-selector": 3,
|
||||
"@typescript-eslint/no-unsafe-function-type": 2,
|
||||
"no-console": 2,
|
||||
"react-refresh/only-export-components": 1
|
||||
}
|
||||
|
||||
@@ -135,24 +135,24 @@
|
||||
{
|
||||
"feature": "Atlas country/region action sheet",
|
||||
"hooks": ["src/pages/atlas/useAtlasCountryActions.ts"],
|
||||
"desktop": ["src/pages/AtlasPage.tsx"],
|
||||
"desktop": ["src/pages/atlas/AtlasCountryActionDialog.tsx"],
|
||||
"mobile": ["src/mobile/screens/atlas/MAtlasCountryPopup.tsx"]
|
||||
},
|
||||
{
|
||||
"feature": "Atlas globe",
|
||||
"hooks": ["src/pages/atlas/useAtlasGlobe.ts", "src/pages/atlas/useGlobeStats.ts"],
|
||||
"desktop": ["src/pages/atlas/AtlasGlobeView.tsx"],
|
||||
"mobile": ["src/mobile/screens/atlas/MAtlasGlobe.tsx"]
|
||||
},
|
||||
{
|
||||
"feature": "Atlas page: atlasModel",
|
||||
"hooks": ["src/pages/atlas/atlasModel.ts"],
|
||||
"desktop": [
|
||||
"src/components/Atlas/AtlasCountryPlaces.tsx",
|
||||
"src/components/shared/CountryFlag.tsx",
|
||||
"src/pages/AtlasPage.tsx"
|
||||
"src/pages/atlas/AtlasGlobeView.tsx"
|
||||
],
|
||||
"mobile": ["src/mobile/screens/atlas/MAtlas.tsx", "src/mobile/screens/atlas/MAtlasBucketSheet.tsx"]
|
||||
},
|
||||
{
|
||||
"feature": "Atlas page: useAtlas",
|
||||
"hooks": ["src/pages/atlas/useAtlas.ts"],
|
||||
"desktop": ["src/pages/AtlasPage.tsx"],
|
||||
"mobile": ["src/mobile/screens/atlas/MAtlas.tsx", "src/mobile/screens/atlas/atlasController.ts"]
|
||||
"mobile": ["src/mobile/screens/atlas/MAtlasGlobe.tsx"]
|
||||
},
|
||||
{
|
||||
"feature": "Audit log",
|
||||
@@ -1127,8 +1127,8 @@
|
||||
"src/mobile/screens/admin/MAdminUi.tsx": "Phone only admin UI primitives (button, card, field, input, secret input, sheet frame).",
|
||||
"src/mobile/screens/admin/MPluginVersionDate.tsx": "Markup only; the published date of a plugin version in MAdminPluginsPanel, formatted with the user's date format through useFormatDate.",
|
||||
"src/mobile/screens/admin/MStorageReclaimCard.tsx": "Markup only; renders the reclaim view and handlers that MAdminStoragePanel takes from useStoragePanel, the twin of StorageReclaimSection.",
|
||||
"src/mobile/screens/atlas/MAtlasSearch.tsx": "Phone full screen country search overlay; options, suggestions and selection come through props from MAtlas.",
|
||||
"src/mobile/screens/atlas/MAtlasStatsCard.tsx": "Markup only; renders the AtlasStats that MAtlas passes in.",
|
||||
"src/mobile/screens/atlas/MAtlas.tsx": "The phone route entry; it only renders MAtlasGlobe, which runs on useAtlasGlobe in the \"Atlas globe\" pair.",
|
||||
"src/mobile/screens/atlas/MAtlasStatsCard.tsx": "Markup only; renders the globe figures from useGlobeStats that MAtlasGlobe passes in.",
|
||||
"src/mobile/screens/collections/MCollCategoryPicker.tsx": "Phone only category dropdown; value and categories come through props from the collection sheets.",
|
||||
"src/mobile/screens/collections/MCollInvites.tsx": "Markup only; the invites and accept and decline come through props from useCollections via MCollections.",
|
||||
"src/mobile/screens/collections/MCollLabelsSheet.tsx": "Phone label sheet; create, update, delete and assign come through props from useCollections.",
|
||||
@@ -1207,6 +1207,16 @@
|
||||
"src/mobile/screens/trip/tabs/tabModel.ts": "Phone tab prop type and status colour tokens only the phone tabs use.",
|
||||
"src/mobile/screens/trip/tabs/transportsModel.ts": "Phone transport card readers (metadata, day and time cells) for MTransportsTab and MBookingsTab.",
|
||||
"src/mobile/screens/vacay/MVacayMonth.tsx": "Markup only; its day cell colours come from the phone vacayDayModel.",
|
||||
"src/mobile/screens/vacay/vacayDayModel.ts": "Phone day cell colour model for MVacayMonth; the desktop card styles its cells inline."
|
||||
"src/mobile/screens/vacay/vacayDayModel.ts": "Phone day cell colour model for MVacayMonth; the desktop card styles its cells inline.",
|
||||
"src/mobile/screens/atlas/hub/MAtlasHub.tsx": "The Atlas hub as a phone sheet: the tab strip and the sheets on top; the desktop opens AtlasGlobePassport, a dialog with its own markup, over the same useAtlasGlobe state.",
|
||||
"src/mobile/screens/atlas/hub/MHubOverview.tsx": "Phone layout of one tab of the Atlas hub sheet (MAtlasHub); the desktop draws the same tab inside AtlasGlobePassport with its own markup, and both read the state of useAtlasGlobe and the derived values of pages/atlas/atlasHubModel.ts.",
|
||||
"src/mobile/screens/atlas/hub/MHubBadges.tsx": "Phone layout of one tab of the Atlas hub sheet (MAtlasHub); the desktop draws the same tab inside AtlasGlobePassport with its own markup, and both read the state of useAtlasGlobe and the derived values of pages/atlas/atlasHubModel.ts.",
|
||||
"src/mobile/screens/atlas/hub/MHubWishlist.tsx": "Phone layout of one tab of the Atlas hub sheet (MAtlasHub); the desktop draws the same tab inside AtlasGlobePassport with its own markup, and both read the state of useAtlasGlobe and the derived values of pages/atlas/atlasHubModel.ts.",
|
||||
"src/mobile/screens/atlas/hub/MHubTours.tsx": "Phone layout of one tab of the Atlas hub sheet (MAtlasHub); the desktop draws the same tab inside AtlasGlobePassport with its own markup, and both read the state of useAtlasGlobe and the derived values of pages/atlas/atlasHubModel.ts.",
|
||||
"src/mobile/screens/atlas/hub/MHubTravellers.tsx": "Phone layout of one tab of the Atlas hub sheet (MAtlasHub); the desktop draws the same tab inside AtlasGlobePassport with its own markup, and both read the state of useAtlasGlobe and the derived values of pages/atlas/atlasHubModel.ts.",
|
||||
"src/mobile/screens/atlas/hub/mHubKit.tsx": "The phone's building blocks for the Atlas hub tabs on the --m-* tokens; markup only, the desktop has its own kit in pages/atlas/atlasHubKit.tsx.",
|
||||
"src/mobile/screens/atlas/hub/MHubDawarich.tsx": "Phone layout of the Atlas hub's Dawarich tab; the desktop tab AtlasGlobeDawarich draws its own markup over the same useDawarichAtlas hook.",
|
||||
"src/mobile/screens/atlas/MAtlasLayersSheet.tsx": "The globe's layers as a phone sheet (switches and the colouring); the desktop opens GlobeLayersDialog over the same useAtlasGlobe state.",
|
||||
"src/mobile/screens/atlas/MAtlasCountrySheets.tsx": "The globe's country action card and country sheet on the phone; the desktop opens GlobeCountryDialogs over the same useAtlasGlobe state and useAtlasCountryActions."
|
||||
}
|
||||
}
|
||||
|
||||
@@ -139,7 +139,6 @@
|
||||
"src/components/Admin/useSchoolHolidayCatalog.ts",
|
||||
"src/components/Atlas/AtlasCountryPlaces.test.tsx",
|
||||
"src/components/Atlas/AtlasCountryPlaces.tsx",
|
||||
"src/components/Atlas/useGlassGlare.ts",
|
||||
"src/components/BackgroundTasks/BackgroundTasksWidget.extra.test.tsx",
|
||||
"src/components/BackgroundTasks/BackgroundTasksWidget.test.tsx",
|
||||
"src/components/BackgroundTasks/BackgroundTasksWidget.tsx",
|
||||
@@ -266,10 +265,6 @@
|
||||
"src/components/Dashboard/CollectionsWidget.tsx",
|
||||
"src/components/Dawarich/DawarichAcceptDialog.test.tsx",
|
||||
"src/components/Dawarich/DawarichAcceptDialog.tsx",
|
||||
"src/components/Dawarich/DawarichAtlasDialog.test.tsx",
|
||||
"src/components/Dawarich/DawarichAtlasDialog.tsx",
|
||||
"src/components/Dawarich/DawarichAtlasSidePanel.test.tsx",
|
||||
"src/components/Dawarich/DawarichAtlasSidePanel.tsx",
|
||||
"src/components/Dawarich/DawarichBadge.test.tsx",
|
||||
"src/components/Dawarich/DawarichBadge.tsx",
|
||||
"src/components/Dawarich/DawarichSuggestionsPanel.test.tsx",
|
||||
@@ -1146,7 +1141,6 @@
|
||||
"src/constants/tripTabs.ts",
|
||||
"src/db/cacheAssignment.ts",
|
||||
"src/db/offlineDb.test.ts",
|
||||
"src/db/offlineDb.ts",
|
||||
"src/help/contexts/admin.ts",
|
||||
"src/help/contexts/atlas.ts",
|
||||
"src/help/contexts/collections.ts",
|
||||
@@ -1284,12 +1278,9 @@
|
||||
"src/mobile/screens/admin/MAdminUsersSection.tsx",
|
||||
"src/mobile/screens/admin/MApiProviderBlocks.tsx",
|
||||
"src/mobile/screens/atlas/MAtlas.tsx",
|
||||
"src/mobile/screens/atlas/MAtlasBucketSheet.tsx",
|
||||
"src/mobile/screens/atlas/MAtlasCountryPopup.test.tsx",
|
||||
"src/mobile/screens/atlas/MAtlasCountryPopup.tsx",
|
||||
"src/mobile/screens/atlas/MAtlasSearch.tsx",
|
||||
"src/mobile/screens/atlas/MAtlasStatsCard.tsx",
|
||||
"src/mobile/screens/atlas/atlasController.ts",
|
||||
"src/mobile/screens/collections/MCollAddSheet.tsx",
|
||||
"src/mobile/screens/collections/MCollCategoryPicker.tsx",
|
||||
"src/mobile/screens/collections/MCollEditSheet.tsx",
|
||||
@@ -1440,9 +1431,7 @@
|
||||
"src/mobile/useIsPhone.ts",
|
||||
"src/pages/AdminPage.test.tsx",
|
||||
"src/pages/AdminPage.tsx",
|
||||
"src/pages/AtlasPage.test.tsx",
|
||||
"src/pages/AtlasPage.tsx",
|
||||
"src/pages/AtlasPage.wiring.test.tsx",
|
||||
"src/pages/CollectionsPage.test.tsx",
|
||||
"src/pages/CollectionsPage.tsx",
|
||||
"src/pages/CollectionsPage.wiring.test.tsx",
|
||||
@@ -1497,7 +1486,6 @@
|
||||
"src/pages/admin/AdminSettingsTab.test.tsx",
|
||||
"src/pages/admin/AdminSettingsTab.tsx",
|
||||
"src/pages/admin/AdminStatCard.tsx",
|
||||
"src/pages/admin/AdminUpdateBanner.test.tsx",
|
||||
"src/pages/admin/AdminUpdateBanner.tsx",
|
||||
"src/pages/admin/AdminUserModals.test.tsx",
|
||||
"src/pages/admin/AdminUserModals.tsx",
|
||||
@@ -1509,13 +1497,8 @@
|
||||
"src/pages/admin/adminModel.ts",
|
||||
"src/pages/admin/useAdmin.ts",
|
||||
"src/pages/admin/useNotificationDefaults.ts",
|
||||
"src/pages/atlas/AtlasCountrySearch.tsx",
|
||||
"src/pages/atlas/AtlasLayerToggle.test.tsx",
|
||||
"src/pages/atlas/AtlasLayerToggle.tsx",
|
||||
"src/pages/atlas/atlasModel.test.ts",
|
||||
"src/pages/atlas/atlasModel.ts",
|
||||
"src/pages/atlas/useAtlas.test.tsx",
|
||||
"src/pages/atlas/useAtlas.ts",
|
||||
"src/pages/collections/collectionsModel.test.ts",
|
||||
"src/pages/collections/collectionsModel.ts",
|
||||
"src/pages/collections/useCollections.test.tsx",
|
||||
@@ -1888,10 +1871,7 @@
|
||||
"tests/unit/mobile/admin/MAdminSheets.test.tsx",
|
||||
"tests/unit/mobile/admin/MAdminStoragePanel.test.tsx",
|
||||
"tests/unit/mobile/admin/MAdminUsersSection.test.tsx",
|
||||
"tests/unit/mobile/atlas/MAtlas.test.tsx",
|
||||
"tests/unit/mobile/atlas/MAtlasBucketSheet.test.tsx",
|
||||
"tests/unit/mobile/atlas/MAtlasCountryPopup.test.tsx",
|
||||
"tests/unit/mobile/atlas/MAtlasSearch.test.tsx",
|
||||
"tests/unit/mobile/atlas/MAtlasStatsCard.test.tsx",
|
||||
"tests/unit/mobile/collections/MCollAddSheet.test.tsx",
|
||||
"tests/unit/mobile/collections/MCollCategoryPicker.test.tsx",
|
||||
@@ -2121,7 +2101,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",
|
||||
|
||||
@@ -72,8 +72,8 @@ const UNUSED_BASELINE = join(HERE, 'i18n-unused-baseline.json');
|
||||
/**
|
||||
* Where else a translation key can be named: the server sends keys for the
|
||||
* client to translate (system notices, notification channels), the plugin
|
||||
* SDK names the ones plugin surfaces use, and the shared book engine names
|
||||
* its layout templates. Read only to find which en keys are reached.
|
||||
* SDK names the ones plugin surfaces use, the shared book engine names
|
||||
* its layout templates and the Atlas badge rules their titles. Read only to find which en keys are reached.
|
||||
*/
|
||||
export const REFERENCE_ROOTS = [
|
||||
// The address screen the native apps ship (vite.native.config.js): its own
|
||||
@@ -82,6 +82,8 @@ export const REFERENCE_ROOTS = [
|
||||
join(HERE, '..', '..', 'server', 'src'),
|
||||
join(HERE, '..', '..', 'plugin-sdk', 'src'),
|
||||
join(HERE, '..', '..', 'shared', 'src', 'book'),
|
||||
// The Atlas badge rules name each badge's title and description keys.
|
||||
join(HERE, '..', '..', 'shared', 'src', 'atlas'),
|
||||
];
|
||||
|
||||
/** How many en keys a template may reach and still pass without an entry below. */
|
||||
|
||||
@@ -13,7 +13,6 @@
|
||||
"src/components/Collections/ListEditorModal.tsx": 1,
|
||||
"src/components/Collections/MSaveToCollectionSheet.tsx": 3,
|
||||
"src/components/Dawarich/DawarichAcceptDialog.tsx": 3,
|
||||
"src/components/Dawarich/DawarichAtlasDialog.tsx": 3,
|
||||
"src/components/Dawarich/DawarichSuggestionsPanel.tsx": 1,
|
||||
"src/components/Journey/ContributorInviteDialog.tsx": 1,
|
||||
"src/components/Journey/JourneyDetailPageAddTripDialog.tsx": 1,
|
||||
|
||||
@@ -42,7 +42,6 @@
|
||||
"src/components/Collections/useSaveTripPlacesToList.ts",
|
||||
"src/components/Collections/useTripCopyPicker.ts",
|
||||
"src/components/Dashboard/useCollectionLists.ts",
|
||||
"src/components/Dawarich/DawarichAtlasDialog.tsx",
|
||||
"src/components/Files/FileManagerAuthedImg.tsx",
|
||||
"src/components/Files/FileManagerImageLightbox.tsx",
|
||||
"src/components/Files/docsync/useConflicts.ts",
|
||||
@@ -130,8 +129,6 @@
|
||||
"src/pages/OAuthAuthorizePage.tsx",
|
||||
"src/pages/admin/useAdmin.ts",
|
||||
"src/pages/admin/useNotificationDefaults.ts",
|
||||
"src/pages/atlas/useAtlas.ts",
|
||||
"src/pages/atlas/useAtlasCountryActions.ts",
|
||||
"src/pages/collections/useCollections.ts",
|
||||
"src/pages/dashboard/useDashboard.ts",
|
||||
"src/pages/dashboard/useTripSearch.ts",
|
||||
|
||||
@@ -82,7 +82,6 @@
|
||||
"mobile/screens/trip/map/MMapArea.tsx": 3,
|
||||
"mobile/screens/trip/tabs/MFileLightbox.tsx": 2,
|
||||
"mobile/screens/vacay/MVacayMonth.tsx": 1,
|
||||
"pages/AtlasPage.tsx": 2,
|
||||
"pages/JourneyDetailPage.tsx": 1,
|
||||
"pages/JourneyPublicPage.tsx": 3,
|
||||
"pages/LoginPage.tsx": 23,
|
||||
@@ -90,7 +89,6 @@
|
||||
"pages/VacayPage.tsx": 1,
|
||||
"pages/admin/AdminNotificationsTab.tsx": 1,
|
||||
"pages/admin/AdminSettingsTab.tsx": 1,
|
||||
"pages/atlas/AtlasLayerToggle.tsx": 1,
|
||||
"pages/sharedTrip/SharedMap.tsx": 4,
|
||||
"styles/collections.css": 1,
|
||||
"styles/studio.css": 7,
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
{
|
||||
"components/AtlasGlobe/atlasGlobe.css": 1,
|
||||
"components/Collections/CollectionMap.tsx": 1,
|
||||
"components/Packing/PackingItemDetail.tsx": 1,
|
||||
"components/Studio/LineHandles.tsx": 1,
|
||||
@@ -8,5 +9,6 @@
|
||||
"mobile/screens/trip/MTripShell.tsx": 1,
|
||||
"mobile/screens/vacay/MVacay.tsx": 1,
|
||||
"pages/CollectionsPage.tsx": 1,
|
||||
"pages/atlas/AtlasGlobeView.tsx": 1,
|
||||
"pages/tripPlanner/PlanMapStage.tsx": 4
|
||||
}
|
||||
|
||||
@@ -8,19 +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": 2331,
|
||||
"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/atlas/useAtlas.ts": 1207,
|
||||
"src/pages/JourneyDetailPage.test.tsx": 3886,
|
||||
"src/pages/LoginPage.tsx": 1273,
|
||||
"src/pages/TripPlannerPage.tsx": 1127,
|
||||
"src/pages/tripPlanner/useTripPlanner.roadtrip.test.tsx": 3518,
|
||||
"src/pages/tripPlanner/useTripPlanner.test.tsx": 3267,
|
||||
"src/styles/studio.css": 1918
|
||||
|
||||
@@ -110,14 +110,12 @@
|
||||
"src/mobile/screens/trip/sheets/MReservationSheet.tsx": 1,
|
||||
"src/mobile/screens/trip/tabs/transportsModel.ts": 1,
|
||||
"src/mobile/screens/vacay/MVacaySettingsSheet.tsx": 1,
|
||||
"src/pages/AtlasPage.tsx": 6,
|
||||
"src/pages/FilesPage.tsx": 1,
|
||||
"src/pages/JourneyDetailPage.tsx": 1,
|
||||
"src/pages/LoginPage.tsx": 1,
|
||||
"src/pages/VacayPage.tsx": 1,
|
||||
"src/pages/admin/useAdmin.ts": 4,
|
||||
"src/pages/atlas/atlasModel.ts": 2,
|
||||
"src/pages/atlas/useAtlas.ts": 9,
|
||||
"src/pages/collections/collectionsModel.ts": 1,
|
||||
"src/pages/journeyDetail/useJourneyDetail.ts": 3,
|
||||
"src/pages/sharedTrip/SharedPlanView.tsx": 1,
|
||||
|
||||
@@ -21,7 +21,6 @@
|
||||
"components/Collections/CollectionHero.tsx": 1,
|
||||
"components/Collections/MSaveToCollectionSheet.tsx": 12,
|
||||
"components/Collections/StatusBadge.tsx": 4,
|
||||
"components/Dawarich/DawarichAtlasDialog.tsx": 3,
|
||||
"components/Files/FileManagerAvatarChip.tsx": 1,
|
||||
"components/Files/FileManagerImageLightbox.tsx": 8,
|
||||
"components/Journey/ContributorInviteDialog.tsx": 76,
|
||||
@@ -45,7 +44,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,
|
||||
@@ -163,11 +162,8 @@
|
||||
"mobile/screens/admin/MAdminUi.tsx": 7,
|
||||
"mobile/screens/admin/MAdminUsersSection.tsx": 13,
|
||||
"mobile/screens/admin/MApiProviderBlocks.tsx": 10,
|
||||
"mobile/screens/atlas/MAtlas.tsx": 5,
|
||||
"mobile/screens/atlas/MAtlasBucketSheet.tsx": 14,
|
||||
"mobile/screens/atlas/MAtlasCountryPopup.tsx": 11,
|
||||
"mobile/screens/atlas/MAtlasSearch.tsx": 5,
|
||||
"mobile/screens/atlas/MAtlasStatsCard.tsx": 3,
|
||||
"mobile/screens/atlas/MAtlasStatsCard.tsx": 2,
|
||||
"mobile/screens/collections/MCollAddSheet.tsx": 6,
|
||||
"mobile/screens/collections/MCollCategoryPicker.tsx": 2,
|
||||
"mobile/screens/collections/MCollEditSheet.tsx": 2,
|
||||
@@ -262,7 +258,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,
|
||||
@@ -282,7 +278,6 @@
|
||||
"mobile/screens/vacay/MVacaySettingsSheet.tsx": 34,
|
||||
"mobile/screens/vacay/MVacayShareSheet.tsx": 10,
|
||||
"mobile/screens/vacay/vacayDayModel.ts": 1,
|
||||
"pages/AtlasPage.tsx": 32,
|
||||
"pages/DashboardPage.tsx": 1,
|
||||
"pages/FilesPage.tsx": 11,
|
||||
"pages/ForgotPasswordPage.tsx": 18,
|
||||
@@ -297,7 +292,6 @@
|
||||
"pages/ResetPasswordPage.tsx": 23,
|
||||
"pages/TripPlannerPage.tsx": 7,
|
||||
"pages/VacayPage.tsx": 13,
|
||||
"pages/atlas/useAtlas.ts": 2,
|
||||
"pages/collections/useCollections.ts": 1,
|
||||
"pages/login/MfaCodeStep.tsx": 4,
|
||||
"pages/sharedTrip/SharedChrome.tsx": 2,
|
||||
|
||||
@@ -2,6 +2,8 @@
|
||||
"components/Admin/GitHubPanel.tsx": 3,
|
||||
"components/Admin/PluginPoiCategoryList.tsx": 1,
|
||||
"components/Admin/useCategoryAdmin.ts": 1,
|
||||
"components/AtlasGlobe/BadgeMedal.tsx": 2,
|
||||
"components/AtlasGlobe/badgeTiers.ts": 4,
|
||||
"components/Budget/CostsPanel.tsx": 1,
|
||||
"components/Budget/CostsToolbar.tsx": 1,
|
||||
"components/Collab/CollabNotesFilePreviewPortal.tsx": 3,
|
||||
@@ -11,7 +13,6 @@
|
||||
"components/Collections/ImportCollectionModal.tsx": 1,
|
||||
"components/Collections/MoveToListModal.tsx": 1,
|
||||
"components/Collections/SaveTripPlacesToListModal.tsx": 1,
|
||||
"components/Dawarich/DawarichAtlasSidePanel.tsx": 1,
|
||||
"components/Files/FileManagerImageLightbox.tsx": 1,
|
||||
"components/Files/FileManagerRow.tsx": 3,
|
||||
"components/Files/FileManagerToolbar.tsx": 1,
|
||||
@@ -56,9 +57,8 @@
|
||||
"components/shared/PasswordChecklist.tsx": 2,
|
||||
"mobile/components/MSheet.tsx": 1,
|
||||
"mobile/components/MWalletButton.tsx": 1,
|
||||
"mobile/screens/atlas/MAtlas.tsx": 1,
|
||||
"mobile/screens/atlas/MAtlasCountryPopup.tsx": 2,
|
||||
"mobile/screens/atlas/MAtlasSearch.tsx": 1,
|
||||
"mobile/screens/atlas/hub/MHubTravellers.tsx": 1,
|
||||
"mobile/screens/collections/MCollEditSheet.tsx": 2,
|
||||
"mobile/screens/collections/MCollPlaceSheet.tsx": 2,
|
||||
"mobile/screens/collections/MCollShareSheet.tsx": 1,
|
||||
@@ -71,8 +71,11 @@
|
||||
"mobile/screens/trip/roadtrip/MRtKindSheet.tsx": 1,
|
||||
"mobile/screens/trip/roadtrip/MRtStopSheet.tsx": 1,
|
||||
"mobile/screens/trip/sheets/MCostSheet.tsx": 1,
|
||||
"pages/AtlasPage.tsx": 1,
|
||||
"pages/admin/AdminUserModals.tsx": 1,
|
||||
"pages/atlas/AtlasCountryActionDialog.tsx": 1,
|
||||
"pages/atlas/AtlasGlobeView.tsx": 2,
|
||||
"pages/atlas/atlasGlobePaint.ts": 10,
|
||||
"pages/atlas/useAtlasGlobe.ts": 1,
|
||||
"pages/sharedTrip/SharedChrome.tsx": 4,
|
||||
"pages/sharedTrip/SharedMap.tsx": 2
|
||||
}
|
||||
|
||||
+28
-5
@@ -1,13 +1,13 @@
|
||||
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 +185,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 +552,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 +607,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 +629,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 +705,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()
|
||||
|
||||
+15
-3
@@ -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">
|
||||
@@ -315,7 +320,7 @@ function RouteFallback() {
|
||||
}
|
||||
|
||||
export default function App() {
|
||||
const { loadUser, isAuthenticated, demoMode, setManaged, setDemoMode, setDevMode, setIsPrerelease, setAppVersion, setHasMapsKey, setHasAmapKey, setPlacesProvider, setServerTimezone, setAppRequireMfa, setTripRemindersEnabled, setPlacesPhotosEnabled, setPlacesAutocompleteEnabled, setPlacesDetailsEnabled, setPlacesEnrichEnabled, setPlaceShadowEnabled } = useAuthStore()
|
||||
const { loadUser, isAuthenticated, demoMode, setManaged, setDemoMode, setDevMode, setIsPrerelease, setAppVersion, setHasMapsKey, setHasAmapKey, setPlacesProvider, setServerTimezone, setAppRequireMfa, setTripRemindersEnabled, setAtlasCompareEnabled, setPlacesPhotosEnabled, setPlacesAutocompleteEnabled, setPlacesDetailsEnabled, setPlacesEnrichEnabled, setPlaceShadowEnabled } = useAuthStore()
|
||||
const { loadSettings } = useSettingsStore()
|
||||
const { loadAddons } = useAddonStore()
|
||||
const { loadPlugins } = usePluginStore()
|
||||
@@ -346,7 +351,7 @@ export default function App() {
|
||||
}, Math.min(30_000, 1_000 * 2 ** attempt))
|
||||
})
|
||||
})
|
||||
fetchAppConfig(0).then(async (config: { managed?: boolean; demo_mode?: boolean; dev_mode?: boolean; is_prerelease?: boolean; has_maps_key?: boolean; has_amap_key?: boolean; places_provider?: string; version?: string; timezone?: string; require_mfa?: boolean; trip_reminders_enabled?: boolean; places_photos_enabled?: boolean; places_autocomplete_enabled?: boolean; places_details_enabled?: boolean; places_enrich_enabled?: boolean; place_shadow_enabled?: boolean; max_upload_mb?: number; permissions?: Record<string, PermissionLevel> }) => {
|
||||
fetchAppConfig(0).then(async (config: { managed?: boolean; demo_mode?: boolean; dev_mode?: boolean; is_prerelease?: boolean; has_maps_key?: boolean; has_amap_key?: boolean; places_provider?: string; version?: string; timezone?: string; require_mfa?: boolean; trip_reminders_enabled?: boolean; atlas_compare_enabled?: boolean; places_photos_enabled?: boolean; places_autocomplete_enabled?: boolean; places_details_enabled?: boolean; places_enrich_enabled?: boolean; place_shadow_enabled?: boolean; max_upload_mb?: number; permissions?: Record<string, PermissionLevel> }) => {
|
||||
setManaged(!!config?.managed)
|
||||
setDemoMode(!!config?.demo_mode)
|
||||
if (config?.dev_mode) setDevMode(true)
|
||||
@@ -358,6 +363,7 @@ export default function App() {
|
||||
if (config?.timezone) setServerTimezone(config.timezone)
|
||||
if (config?.require_mfa !== undefined) setAppRequireMfa(!!config.require_mfa)
|
||||
if (config?.trip_reminders_enabled !== undefined) setTripRemindersEnabled(config.trip_reminders_enabled)
|
||||
if (config?.atlas_compare_enabled !== undefined) setAtlasCompareEnabled(config.atlas_compare_enabled)
|
||||
if (config?.places_photos_enabled !== undefined) setPlacesPhotosEnabled(config.places_photos_enabled)
|
||||
if (config?.places_autocomplete_enabled !== undefined) setPlacesAutocompleteEnabled(config.places_autocomplete_enabled)
|
||||
if (config?.places_details_enabled !== undefined) setPlacesDetailsEnabled(config.places_details_enabled)
|
||||
@@ -398,6 +404,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,4 +1,3 @@
|
||||
import React from 'react'
|
||||
import { render, waitFor, act } from '@testing-library/react'
|
||||
import { MemoryRouter } from 'react-router'
|
||||
import { describe, it, expect, beforeEach, vi } from 'vitest'
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
import React from 'react'
|
||||
import { render, screen } from '@testing-library/react'
|
||||
import { MemoryRouter } from 'react-router'
|
||||
import { describe, it, expect, beforeEach, vi } from 'vitest'
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import type { ComponentType } from 'react'
|
||||
import { useTranslation } from '../../i18n'
|
||||
import { Puzzle, ListChecks, Wallet, FileText, CalendarDays, Globe, Briefcase, Image, Terminal, Link2, Compass, BookOpen, Sparkles, Luggage, Plane, Bookmark, Users, Loader2, Mountain, CarFront, Radar } from 'lucide-react'
|
||||
import { Puzzle, ListChecks, Wallet, FileText, CalendarDays, Globe, Briefcase, Image, Terminal, Link2, Compass, BookOpen, Sparkles, Luggage, Plane, Bookmark, Users, Loader2, Mountain, CarFront, Radar, Trophy } from 'lucide-react'
|
||||
import EmptyState from '../shared/EmptyState'
|
||||
import DawarichIcon from '../shared/DawarichIcon'
|
||||
import AirTrailIcon from '../shared/AirTrailIcon'
|
||||
@@ -94,6 +94,8 @@ export default function AddonManager({ bagTrackingEnabled, onToggleBagTracking,
|
||||
wandererOffered,
|
||||
toggleToursWanderer,
|
||||
mapSwitches,
|
||||
atlasCompare,
|
||||
toggleAtlasCompare,
|
||||
} = useAddonManager()
|
||||
if (loading) {
|
||||
return (
|
||||
@@ -109,6 +111,17 @@ export default function AddonManager({ bagTrackingEnabled, onToggleBagTracking,
|
||||
* parent as shelf rows, and each shelf only shows while its parent is on —
|
||||
* a provider toggled under a disabled Journey would hit the server's 409. */
|
||||
const shelfFor = (addon: Addon) => {
|
||||
if (addon.id === 'atlas' && addon.enabled) {
|
||||
return (
|
||||
<AddonSubRow
|
||||
icon={<Trophy size={14} />}
|
||||
title={t('admin.atlasCompare.title')}
|
||||
description={t('admin.atlasCompare.subtitle')}
|
||||
enabled={atlasCompare}
|
||||
onToggle={() => void toggleAtlasCompare()}
|
||||
/>
|
||||
)
|
||||
}
|
||||
if (addon.id === 'packing' && addon.enabled && onToggleBagTracking) {
|
||||
return (
|
||||
<AddonSubRow
|
||||
|
||||
@@ -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>
|
||||
|
||||
@@ -2,7 +2,7 @@ import type { AdminFeatureToggleResponse } from '@trek/shared';
|
||||
import { Bike, Footprints, MountainSnow } from 'lucide-react';
|
||||
import { useEffect, useEffectEvent, useState } from 'react';
|
||||
|
||||
import { adminApi } from '../../../api/client';
|
||||
import { adminApi, authApi } from '../../../api/client';
|
||||
import { cycleMapAdminApi, hikingMapAdminApi, skiRoutingAdminApi } from '../../../api/tourBaseMaps';
|
||||
import { wandererAdminApi } from '../../../api/wanderer';
|
||||
import { useTranslation } from '../../../i18n';
|
||||
@@ -43,6 +43,9 @@ export function useAddonManager() {
|
||||
const [toursHikingMap, setToursHikingMap] = useState(false);
|
||||
const [toursCycleMap, setToursCycleMap] = useState(false);
|
||||
const [toursSkiRouting, setToursSkiRouting] = useState(false);
|
||||
// The Atlas ranking switch is an app setting the app config already carries.
|
||||
const atlasCompare = useAuthStore((s) => s.atlasCompareEnabled);
|
||||
const setAtlasCompare = useAuthStore((s) => s.setAtlasCompareEnabled);
|
||||
|
||||
const loadAddons = async () => {
|
||||
try {
|
||||
@@ -105,6 +108,11 @@ export function useAddonManager() {
|
||||
void refreshGlobalAddons();
|
||||
toast.success(t('admin.addons.toast.updated'));
|
||||
};
|
||||
/** Whether travellers on this instance see the Atlas ranking and each other's profiles. */
|
||||
const toggleAtlasCompare = () =>
|
||||
flipToursSwitch(atlasCompare, setAtlasCompare, (enabled) =>
|
||||
authApi.updateAppSettings({ atlas_compare_enabled: enabled })
|
||||
);
|
||||
const toggleToursWanderer = () => flipToursSwitch(toursWanderer, setToursWanderer, wandererAdminApi.update);
|
||||
/** The maps and the piste router Tours offers on their operators' terms, one switch each (MAP-01, BIK-06, SKI-02). */
|
||||
const mapSwitches = [
|
||||
@@ -167,5 +175,7 @@ export function useAddonManager() {
|
||||
wandererOffered,
|
||||
toggleToursWanderer,
|
||||
mapSwitches,
|
||||
atlasCompare,
|
||||
toggleAtlasCompare,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
@@ -1,150 +0,0 @@
|
||||
// FE-STA2-PANE-001 to FE-STA2-PANE-006
|
||||
// STA-02: the Atlas tab of the user's own tour activities: the distance large
|
||||
// with how many tours at its corner, the climb, the types, what the numbers
|
||||
// rest on, and the full list in a dialog.
|
||||
import userEvent from '@testing-library/user-event';
|
||||
import { summarizeTourActivities, type TourActivityStatsEntry, type TourActivityStatsResponse } from '@trek/shared';
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { buildSettings } from '../../../../tests/helpers/factories';
|
||||
import { render, screen } from '../../../../tests/helpers/render';
|
||||
import { resetAllStores, seedStore } from '../../../../tests/helpers/store';
|
||||
import { useSettingsStore } from '../../../store/settingsStore';
|
||||
import { AtlasTourActivityPane } from './AtlasTourActivityPane';
|
||||
import type { TourActivityStats } from './useTourActivityStats';
|
||||
|
||||
const hook = vi.hoisted(() => ({ current: null as unknown, active: [] as boolean[] }));
|
||||
vi.mock('./useTourActivityStats', () => ({
|
||||
useTourActivityStats: (active: boolean) => {
|
||||
hook.active.push(active);
|
||||
return hook.current;
|
||||
},
|
||||
}));
|
||||
|
||||
const TODAY = '2026-10-20';
|
||||
|
||||
function entry(overrides: Partial<TourActivityStatsEntry> = {}): TourActivityStatsEntry {
|
||||
return {
|
||||
place_id: 1,
|
||||
name: 'Ridge',
|
||||
tour_type: 'hike',
|
||||
trip: { id: 5, title: 'Alps' },
|
||||
derived_from_place_id: null,
|
||||
date: '2026-07-02',
|
||||
basis: 'plan',
|
||||
track: null,
|
||||
day_count: 1,
|
||||
distance_km: 12,
|
||||
ascent_m: 800,
|
||||
descent_m: 790,
|
||||
excluded: false,
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
function statsOf(data: TourActivityStatsResponse | null, overrides: Partial<TourActivityStats> = {}) {
|
||||
const stats: TourActivityStats = {
|
||||
status: data ? 'ready' : 'loading',
|
||||
data,
|
||||
summary: data ? summarizeTourActivities(data.entries, { today: TODAY }) : null,
|
||||
period: 'all',
|
||||
setPeriod: vi.fn(),
|
||||
periods: ['all', 'thisYear', 'last12'],
|
||||
type: 'all',
|
||||
setType: vi.fn(),
|
||||
types: ['all', 'hike', 'kayak'],
|
||||
pending: new Set(),
|
||||
setExcluded: vi.fn().mockResolvedValue(undefined),
|
||||
retry: vi.fn(),
|
||||
...overrides,
|
||||
};
|
||||
hook.current = stats;
|
||||
return stats;
|
||||
}
|
||||
|
||||
const data: TourActivityStatsResponse = {
|
||||
entries: [
|
||||
entry(),
|
||||
entry({ place_id: 2, name: 'Summit', date: '2026-08-01', distance_km: 20.5, ascent_m: 1200, descent_m: 1200 }),
|
||||
entry({
|
||||
place_id: 3,
|
||||
name: 'Lake',
|
||||
tour_type: 'kayak',
|
||||
basis: 'track',
|
||||
track: { place_id: 9, name: 'Watch' },
|
||||
distance_km: 8,
|
||||
ascent_m: null,
|
||||
descent_m: null,
|
||||
}),
|
||||
],
|
||||
uncounted: { unassigned: 0, undated: 1 },
|
||||
};
|
||||
|
||||
beforeEach(() => {
|
||||
resetAllStores();
|
||||
vi.clearAllMocks();
|
||||
hook.active = [];
|
||||
seedStore(useSettingsStore, { settings: buildSettings({ distance_unit: 'metric' }) });
|
||||
});
|
||||
|
||||
describe('AtlasTourActivityPane', () => {
|
||||
it('FE-STA2-PANE-001: follows whether the tab is shown, silent before, loading until the read is there', () => {
|
||||
statsOf(null, { status: 'idle' });
|
||||
const { rerender } = render(<AtlasTourActivityPane active={false} />);
|
||||
expect(hook.active).toEqual([false]);
|
||||
expect(screen.queryByRole('status')).not.toBeInTheDocument();
|
||||
statsOf(null);
|
||||
rerender(<AtlasTourActivityPane active />);
|
||||
expect(hook.active).toEqual([false, true]);
|
||||
expect(screen.getByRole('status')).toHaveTextContent('Loading');
|
||||
});
|
||||
|
||||
it('FE-STA2-PANE-002: shows the distance large with the tour count at its corner, and the climb', () => {
|
||||
statsOf(data);
|
||||
render(<AtlasTourActivityPane active />);
|
||||
expect(screen.getByTestId('atlas-tour-activity-distance')).toHaveTextContent('40.5km');
|
||||
expect(screen.getByTestId('atlas-tour-activity-count')).toHaveTextContent('3');
|
||||
expect(screen.getByTestId('atlas-tour-activity-ascent')).toHaveTextContent('2000m');
|
||||
expect(screen.getByTestId('atlas-tour-activity-type-hike')).toHaveTextContent('2');
|
||||
expect(screen.getByTestId('atlas-tour-activity-type-kayak')).toHaveTextContent('8 km');
|
||||
});
|
||||
|
||||
it('FE-STA2-PANE-003: says what the numbers rest on and what does not count', () => {
|
||||
statsOf(data);
|
||||
render(<AtlasTourActivityPane active />);
|
||||
expect(screen.getByTestId('tour-activity-basis-plan')).toHaveTextContent('Planned2');
|
||||
expect(screen.getByTestId('tour-activity-basis-track')).toHaveTextContent('Recorded1');
|
||||
expect(screen.getByTestId('tour-activity-undated')).toHaveTextContent('1');
|
||||
});
|
||||
|
||||
it('FE-STA2-PANE-004: one type chosen leaves the type columns out; nothing done says so', () => {
|
||||
statsOf(data, { type: 'hike', summary: summarizeTourActivities(data.entries, { today: TODAY, type: 'hike' }) });
|
||||
const { rerender } = render(<AtlasTourActivityPane active />);
|
||||
expect(screen.queryByTestId('atlas-tour-activity-type-hike')).not.toBeInTheDocument();
|
||||
|
||||
statsOf(data, { summary: summarizeTourActivities(data.entries, { today: TODAY, from: '2027-01-01' }) });
|
||||
rerender(<AtlasTourActivityPane active />);
|
||||
expect(screen.getByText('No completed tours in this period')).toBeInTheDocument();
|
||||
expect(screen.queryByRole('button', { name: 'Show tours' })).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-STA2-PANE-005: the full list opens in the dialog', async () => {
|
||||
statsOf(data);
|
||||
const user = userEvent.setup();
|
||||
render(<AtlasTourActivityPane active />);
|
||||
await user.click(screen.getByRole('button', { name: 'Show tours' }));
|
||||
expect(screen.getByRole('heading', { name: 'My tour activities' })).toBeInTheDocument();
|
||||
expect(screen.getByTestId('tour-activity-list')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-STA2-PANE-006: offline and failed reads say so, a failed one with a retry', async () => {
|
||||
statsOf(null, { status: 'offline' });
|
||||
const { rerender } = render(<AtlasTourActivityPane active />);
|
||||
expect(screen.getByText(/needs a connection/i)).toBeInTheDocument();
|
||||
|
||||
const failed = statsOf(null, { status: 'error' });
|
||||
rerender(<AtlasTourActivityPane active />);
|
||||
expect(screen.getByRole('alert')).toHaveTextContent('Tour activities could not be loaded');
|
||||
await userEvent.setup().click(screen.getByRole('button', { name: 'Try again' }));
|
||||
expect(failed.retry).toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -1,223 +0,0 @@
|
||||
import type { TourActivitySummary } from '@trek/shared';
|
||||
import { Footprints, ListOrdered } from 'lucide-react';
|
||||
import { useState } from 'react';
|
||||
import { useTranslation } from '../../../i18n';
|
||||
import type { DistanceUnit } from '../../../types';
|
||||
import { fs } from '../../shared/DialogShell';
|
||||
import { Tooltip } from '../../shared/Tooltip';
|
||||
import { CardAction, InfoDot } from '../../Tours/tourParts';
|
||||
import { ActivityFilters, ActivityStatusLine, BasisBadges, UncountedBadges } from './tourActivityParts';
|
||||
import { distanceReading, heightReading, typeIcon, typeLabel, useDistanceUnit } from './tourActivityReading';
|
||||
import { TourActivityStatsDialog } from './TourActivityStatsDialog';
|
||||
import { splitMeasure } from './tourActivityStatsModel';
|
||||
import { useTourActivityStats, type TourActivityStats } from './useTourActivityStats';
|
||||
|
||||
/** The wash the hero tile sits on, as the Atlas numbers do: the text colour, faintly, over the glass. */
|
||||
const HERO_TINT = 'color-mix(in srgb, var(--text-primary) 7%, transparent)';
|
||||
/** How many types the strip names before the dialog takes over. */
|
||||
const STRIP_TYPES = 3;
|
||||
const EYEBROW = 'mt-1.5 whitespace-nowrap font-semibold uppercase tracking-wide text-content-faint';
|
||||
|
||||
function Divider() {
|
||||
return <span aria-hidden="true" className="mx-3 my-3 w-0.5 flex-none rounded-full bg-edge-faint" />;
|
||||
}
|
||||
|
||||
/**
|
||||
* The distance of the period, large, with how many tours at its corner; the
|
||||
* tour count stands in when no tour knows its distance.
|
||||
*/
|
||||
function Hero({ summary, unit }: { summary: TourActivitySummary; unit: DistanceUnit }) {
|
||||
const { t } = useTranslation();
|
||||
const reading = distanceReading(summary.totals, unit);
|
||||
const shown = reading ? splitMeasure(reading.text) : { value: String(summary.totals.count), unit: '' };
|
||||
const countLabel = `${t('tours.mode.tours')}: ${summary.totals.count}`;
|
||||
return (
|
||||
<div
|
||||
className="relative mx-2 my-2 flex flex-col justify-center rounded-xl px-5 py-4"
|
||||
style={{ background: HERO_TINT }}
|
||||
>
|
||||
<div className="flex items-baseline gap-1.5" data-testid="atlas-tour-activity-distance">
|
||||
<span className="font-black tabular-nums leading-none text-content" style={fs(40, 'title')}>
|
||||
{shown.value}
|
||||
</span>
|
||||
{shown.unit && (
|
||||
<span className="font-medium text-content-muted" style={fs(14, 'body')}>
|
||||
{shown.unit}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
<span className={EYEBROW} style={fs(9)}>
|
||||
{reading ? t('tours.detail.distance') : t('tours.mode.tours')}
|
||||
</span>
|
||||
{reading && (
|
||||
<Tooltip label={countLabel}>
|
||||
<span
|
||||
aria-label={countLabel}
|
||||
data-testid="atlas-tour-activity-count"
|
||||
className="absolute -end-2 -top-2 inline-flex h-[22px] items-center gap-1 rounded-full bg-surface-card px-2 font-geist font-semibold tabular-nums text-content shadow-sm ring-1 ring-inset ring-edge-faint"
|
||||
style={fs(11)}
|
||||
>
|
||||
<Footprints size={11} strokeWidth={2.2} className="flex-none text-content-muted" />
|
||||
{summary.totals.count}
|
||||
</span>
|
||||
</Tooltip>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/** A height sum as the Atlas numbers stand: the value, its unit, and what it is below. */
|
||||
function Figure({ label, text, testId }: { label: string; text: string; testId: string }) {
|
||||
const { value, unit } = splitMeasure(text);
|
||||
return (
|
||||
<div className="flex flex-none flex-col items-center justify-center px-3 py-4" data-testid={testId}>
|
||||
<span className="flex items-baseline gap-1">
|
||||
<span className="font-black tabular-nums leading-none text-content" style={fs(24, 'subtitle')}>
|
||||
{value}
|
||||
</span>
|
||||
<span className="font-medium text-content-muted" style={fs(11, 'body')}>
|
||||
{unit}
|
||||
</span>
|
||||
</span>
|
||||
<span className={EYEBROW} style={fs(9)}>
|
||||
{label}
|
||||
</span>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/** The types of the period, the most tours first: each an icon with its count at the corner, its distance below. */
|
||||
function TypeColumns({ summary, unit }: { summary: TourActivitySummary; unit: DistanceUnit }) {
|
||||
const { t } = useTranslation();
|
||||
return (
|
||||
<div className="flex flex-none items-center gap-4 px-2 py-3">
|
||||
{summary.types.slice(0, STRIP_TYPES).map((scope) => {
|
||||
const Icon = typeIcon(scope.type);
|
||||
const distance = distanceReading(scope, unit);
|
||||
const label = `${typeLabel(scope.type, t)}: ${scope.count}${distance ? `, ${distance.text}` : ''}`;
|
||||
return (
|
||||
<Tooltip key={scope.type} label={label}>
|
||||
<span
|
||||
aria-label={label}
|
||||
className="flex flex-col items-center gap-1.5"
|
||||
data-testid={`atlas-tour-activity-type-${scope.type}`}
|
||||
>
|
||||
<span className="relative">
|
||||
<span className="grid h-8 w-8 place-items-center rounded-full bg-surface-card text-content-secondary shadow-sm ring-1 ring-inset ring-edge-faint">
|
||||
<Icon size={15} strokeWidth={1.9} />
|
||||
</span>
|
||||
<span
|
||||
className="absolute -end-1.5 -top-1.5 grid h-4 min-w-4 place-items-center rounded-full bg-accent px-1 font-geist font-semibold tabular-nums text-accent-text ring-2 ring-surface-card"
|
||||
style={fs(9)}
|
||||
>
|
||||
{scope.count}
|
||||
</span>
|
||||
</span>
|
||||
{distance && (
|
||||
<span
|
||||
className="whitespace-nowrap font-semibold tabular-nums text-content-secondary"
|
||||
style={fs(11, 'body')}
|
||||
>
|
||||
{distance.text}
|
||||
</span>
|
||||
)}
|
||||
</span>
|
||||
</Tooltip>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/** What the sums rest on, what does not count, and the way into the full list. */
|
||||
interface StripProps {
|
||||
stats: TourActivityStats;
|
||||
summary: TourActivitySummary;
|
||||
onOpen: () => void;
|
||||
}
|
||||
|
||||
function SideColumn({ stats, summary, onOpen }: StripProps) {
|
||||
const { t } = useTranslation();
|
||||
const uncounted = stats.data?.uncounted ?? { unassigned: 0, undated: 0 };
|
||||
return (
|
||||
<div className="flex flex-none flex-col items-start justify-center gap-1.5 px-3 py-3">
|
||||
<div className="flex flex-wrap items-center gap-1.5">
|
||||
<BasisBadges byBasis={summary.totals.byBasis} />
|
||||
<InfoDot label={t('tours.stats.title')} description={t('tours.stats.basisInfo')} />
|
||||
</div>
|
||||
<div className="flex flex-wrap items-center gap-1.5">
|
||||
<UncountedBadges upcoming={summary.upcoming} {...uncounted} />
|
||||
</div>
|
||||
{summary.done.length > 0 && (
|
||||
<CardAction icon={<ListOrdered size={13} strokeWidth={2.2} />} onClick={onOpen}>
|
||||
{t('tours.stats.showTours')}
|
||||
</CardAction>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/** The numbers of the period, or why there are none, with the filters before them. */
|
||||
function Strip({ stats, summary, onOpen }: StripProps) {
|
||||
const { t } = useTranslation();
|
||||
const unit = useDistanceUnit();
|
||||
const ascent = heightReading(summary.totals.ascentM, unit);
|
||||
const descent = heightReading(summary.totals.descentM, unit);
|
||||
const counted = summary.totals.count > 0;
|
||||
return (
|
||||
<>
|
||||
<div className="flex flex-none flex-col items-start justify-center gap-1.5 px-3 py-3">
|
||||
<ActivityFilters stats={stats} quiet />
|
||||
</div>
|
||||
{counted ? (
|
||||
<>
|
||||
<Hero summary={summary} unit={unit} />
|
||||
{ascent && <Figure label={t('tours.detail.ascent')} text={ascent.text} testId="atlas-tour-activity-ascent" />}
|
||||
{descent && (
|
||||
<Figure label={t('tours.detail.descent')} text={descent.text} testId="atlas-tour-activity-descent" />
|
||||
)}
|
||||
{stats.type === 'all' && summary.types.length > 1 && (
|
||||
<>
|
||||
<Divider />
|
||||
<TypeColumns summary={summary} unit={unit} />
|
||||
</>
|
||||
)}
|
||||
</>
|
||||
) : (
|
||||
<p className="m-0 flex max-w-[260px] items-center px-4 py-5 text-content-muted" style={fs(12, 'body')}>
|
||||
{t(stats.data?.entries.length ? 'tours.stats.none' : 'tours.stats.empty')}
|
||||
</p>
|
||||
)}
|
||||
<Divider />
|
||||
<SideColumn stats={stats} summary={summary} onOpen={onOpen} />
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* STA-02: the Atlas tab of the user's own tour activities: the period and type,
|
||||
* the distance done with how many tours at its corner, the climb, the types,
|
||||
* and what the numbers rest on (the trip planning, or recorded tracks where
|
||||
* linked). The full list, where a tour can be left out, opens in a dialog. The
|
||||
* read waits until the tab is first shown.
|
||||
*/
|
||||
export function AtlasTourActivityPane({ active, maxWidth }: { active: boolean; maxWidth?: number }) {
|
||||
const stats = useTourActivityStats(active);
|
||||
const [open, setOpen] = useState(false);
|
||||
return (
|
||||
<div
|
||||
className="flex w-full items-stretch justify-center overflow-x-auto px-2"
|
||||
style={{ maxWidth }}
|
||||
data-testid="atlas-tour-activity"
|
||||
>
|
||||
{stats.summary ? (
|
||||
<Strip stats={stats} summary={stats.summary} onOpen={() => setOpen(true)} />
|
||||
) : (
|
||||
<div className="flex items-center px-6 py-5">
|
||||
<ActivityStatusLine stats={stats} />
|
||||
</div>
|
||||
)}
|
||||
<TourActivityStatsDialog stats={stats} open={open} onClose={() => setOpen(false)} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -18,18 +18,10 @@ import { Tooltip } from '../../shared/Tooltip';
|
||||
import { FigureBadge } from '../../Tours/paddle/FigureBadge';
|
||||
import { TourDayRowPill } from '../../Tours/TourDayRowFacts';
|
||||
import { tourDayRowIcon } from '../../Tours/tourDayRowIcon';
|
||||
import { typeIcon, typeLabel, type Translate } from './tourActivityReading';
|
||||
import { periodYear, type ActivityPeriod, type ActivityType } from './tourActivityStatsModel';
|
||||
import { periodLabel, typeIcon, typeLabel } from './tourActivityReading';
|
||||
import { type ActivityType } from './tourActivityStatsModel';
|
||||
import type { TourActivityStats } from './useTourActivityStats';
|
||||
|
||||
/** What a period is called in the filter. */
|
||||
function periodLabel(period: ActivityPeriod, t: Translate): string {
|
||||
if (period === 'all') return t('tours.stats.period.all');
|
||||
if (period === 'thisYear') return t('tours.stats.period.thisYear');
|
||||
if (period === 'last12') return t('tours.stats.period.last12');
|
||||
return String(periodYear(period));
|
||||
}
|
||||
|
||||
/** The period and type filters, as head band pills or quiet ones in a panel. */
|
||||
export function ActivityFilters({ stats, quiet = false }: { stats: TourActivityStats; quiet?: boolean }) {
|
||||
const { t } = useTranslation();
|
||||
|
||||
@@ -4,7 +4,7 @@ import { useSettingsStore } from '../../../store/settingsStore';
|
||||
import type { DistanceUnit } from '../../../types';
|
||||
import { formatDistance, formatElevation } from '../../../utils/units';
|
||||
import { tourDayRowIcon } from '../../Tours/tourDayRowIcon';
|
||||
import { sumReading, type ActivityType } from './tourActivityStatsModel';
|
||||
import { periodYear, sumReading, type ActivityPeriod, type ActivityType } from './tourActivityStatsModel';
|
||||
|
||||
export type Translate = (key: string, params?: Record<string, unknown>) => string;
|
||||
|
||||
@@ -37,3 +37,11 @@ export function heightReading(sum: TourActivityTotals['ascentM'], unit: Distance
|
||||
export function partialHint(sum: TourActivityTotals['distanceKm'], t: Translate): string {
|
||||
return t('tours.scope.partialBody', { known: sum.known, of: sum.of });
|
||||
}
|
||||
|
||||
/** What a period is called in the filter. */
|
||||
export function periodLabel(period: ActivityPeriod, t: Translate): string {
|
||||
if (period === 'all') return t('tours.stats.period.all');
|
||||
if (period === 'thisYear') return t('tours.stats.period.thisYear');
|
||||
if (period === 'last12') return t('tours.stats.period.last12');
|
||||
return String(periodYear(period));
|
||||
}
|
||||
|
||||
@@ -1,48 +0,0 @@
|
||||
import { useRef, type RefObject } from 'react'
|
||||
|
||||
export interface GlassGlare {
|
||||
/** Goes on the panel itself — the glare is measured against its box. */
|
||||
panelRef: RefObject<HTMLDivElement | null>
|
||||
/** The soft light under the cursor. */
|
||||
glareRef: RefObject<HTMLDivElement | null>
|
||||
/** The lit stretch of border around it. */
|
||||
borderGlareRef: RefObject<HTMLDivElement | null>
|
||||
onMouseMove: (e: { clientX: number; clientY: number }) => void
|
||||
onMouseLeave: () => void
|
||||
}
|
||||
|
||||
/**
|
||||
* The Atlas panels' liquid-glass hover: a pool of light under the cursor and the
|
||||
* piece of border nearest to it lighting up.
|
||||
*
|
||||
* Extracted so a second panel beside the first one behaves identically. Two
|
||||
* hand-copied versions of a gradient are two versions that drift, and the whole
|
||||
* point of the effect is that the panels look like one material.
|
||||
*
|
||||
* Written straight to the DOM rather than through state: this runs on every
|
||||
* mousemove, and a re-render per frame would cost more than the effect is worth.
|
||||
*/
|
||||
export function useGlassGlare(dark: boolean): GlassGlare {
|
||||
const panelRef = useRef<HTMLDivElement>(null)
|
||||
const glareRef = useRef<HTMLDivElement>(null)
|
||||
const borderGlareRef = useRef<HTMLDivElement>(null)
|
||||
|
||||
const onMouseMove = (e: { clientX: number; clientY: number }): void => {
|
||||
if (!panelRef.current || !glareRef.current || !borderGlareRef.current) return
|
||||
const rect = panelRef.current.getBoundingClientRect()
|
||||
const x = e.clientX - rect.left
|
||||
const y = e.clientY - rect.top
|
||||
glareRef.current.style.background = `radial-gradient(circle 300px at ${x}px ${y}px, ${dark ? 'rgba(255,255,255,0.025)' : 'rgba(255,255,255,0.25)'} 0%, transparent 70%)`
|
||||
glareRef.current.style.opacity = '1'
|
||||
borderGlareRef.current.style.opacity = '1'
|
||||
borderGlareRef.current.style.maskImage = `radial-gradient(circle 150px at ${x}px ${y}px, black 0%, transparent 100%)`
|
||||
borderGlareRef.current.style.webkitMaskImage = `radial-gradient(circle 150px at ${x}px ${y}px, black 0%, transparent 100%)`
|
||||
}
|
||||
|
||||
const onMouseLeave = (): void => {
|
||||
if (glareRef.current) glareRef.current.style.opacity = '0'
|
||||
if (borderGlareRef.current) borderGlareRef.current.style.opacity = '0'
|
||||
}
|
||||
|
||||
return { panelRef, glareRef, borderGlareRef, onMouseMove, onMouseLeave }
|
||||
}
|
||||
@@ -0,0 +1,120 @@
|
||||
import { forwardRef, useEffect, useImperativeHandle, useRef, useState } from 'react';
|
||||
import { GlobeEngine, type AtlasMeshManifest, type GlobeHit } from './GlobeEngine';
|
||||
import { placeLabels, type GlobeLabel } from './globeLabels';
|
||||
import { globeTheme } from './globeTheme';
|
||||
|
||||
export interface AtlasGlobeHandle {
|
||||
engine: GlobeEngine | null;
|
||||
}
|
||||
|
||||
export interface AtlasGlobeProps {
|
||||
fetchJson: (path: string) => Promise<unknown>;
|
||||
dark: boolean;
|
||||
/** Country name for a label, by ISO A2 (localised by the caller). */
|
||||
labelFor: (a2: string) => string | null;
|
||||
/** Whether a country's region names are drawn when zoomed in. */
|
||||
labelRegionsOf?: (a2: string) => boolean;
|
||||
/** Paints statuses once the geometry is in (and again whenever this changes). */
|
||||
paint: (engine: GlobeEngine) => void;
|
||||
paintKey: unknown;
|
||||
onHover?: (hit: GlobeHit | null, x: number, y: number) => void;
|
||||
onSelect?: (hit: GlobeHit | null, x: number, y: number) => void;
|
||||
onReady?: (manifest: AtlasMeshManifest) => void;
|
||||
onFrame?: (engine: GlobeEngine) => void;
|
||||
onError?: (err: unknown) => void;
|
||||
insetBottom?: number;
|
||||
className?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* The Atlas globe: a WebGL2 canvas driven by GlobeEngine, with country names
|
||||
* as HTML labels on top so every script, the user's text size and screen
|
||||
* readers work without a glyph atlas.
|
||||
*/
|
||||
const AtlasGlobe = forwardRef<AtlasGlobeHandle, AtlasGlobeProps>(function AtlasGlobe(props, ref) {
|
||||
const canvasRef = useRef<HTMLCanvasElement>(null);
|
||||
const labelsRef = useRef<HTMLDivElement>(null);
|
||||
const engineRef = useRef<GlobeEngine | null>(null);
|
||||
const propsRef = useRef(props);
|
||||
propsRef.current = props;
|
||||
const [ready, setReady] = useState(false);
|
||||
|
||||
useImperativeHandle(
|
||||
ref,
|
||||
() => ({
|
||||
get engine() {
|
||||
return engineRef.current;
|
||||
},
|
||||
}),
|
||||
[]
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
const canvas = canvasRef.current;
|
||||
if (!canvas) return;
|
||||
let engine: GlobeEngine;
|
||||
try {
|
||||
engine = new GlobeEngine({
|
||||
canvas,
|
||||
fetchJson: (p) => propsRef.current.fetchJson(p),
|
||||
theme: globeTheme(propsRef.current.dark),
|
||||
onHover: (h, x, y) => propsRef.current.onHover?.(h, x, y),
|
||||
onSelect: (h, x, y) => propsRef.current.onSelect?.(h, x, y),
|
||||
onError: (e) => propsRef.current.onError?.(e),
|
||||
onReady: () => {
|
||||
if (engine.manifest) propsRef.current.onReady?.(engine.manifest);
|
||||
propsRef.current.paint(engine);
|
||||
setReady(true);
|
||||
},
|
||||
onFrame: (e) => {
|
||||
if (labelsRef.current)
|
||||
placeLabels(labelsRef.current, labelPool, e, propsRef.current.labelFor, propsRef.current.labelRegionsOf);
|
||||
propsRef.current.onFrame?.(e);
|
||||
},
|
||||
});
|
||||
} catch (err) {
|
||||
propsRef.current.onError?.(err);
|
||||
return;
|
||||
}
|
||||
const labelPool: GlobeLabel[] = [];
|
||||
engine.onRegionLoaded = () => propsRef.current.paint(engine);
|
||||
engineRef.current = engine;
|
||||
return () => {
|
||||
engine.dispose();
|
||||
engineRef.current = null;
|
||||
};
|
||||
}, []);
|
||||
|
||||
const { dark, paint, paintKey } = props;
|
||||
useEffect(() => {
|
||||
engineRef.current?.setTheme(globeTheme(dark));
|
||||
}, [dark]);
|
||||
|
||||
// paint changes with everything it reads; paintKey also with the regions that
|
||||
// arrived since, which paint reads from the engine.
|
||||
useEffect(() => {
|
||||
const e = engineRef.current;
|
||||
if (e && ready && paintKey !== undefined) {
|
||||
paint(e);
|
||||
e.kick();
|
||||
}
|
||||
}, [paint, paintKey, ready]);
|
||||
|
||||
useEffect(() => {
|
||||
engineRef.current?.setInsetBottom(props.insetBottom ?? 0);
|
||||
}, [props.insetBottom]);
|
||||
|
||||
return (
|
||||
<div className={props.className} style={{ position: 'absolute', inset: 0, overflow: 'hidden' }}>
|
||||
<canvas
|
||||
ref={canvasRef}
|
||||
style={{ position: 'absolute', inset: 0, width: '100%', height: '100%', touchAction: 'none', cursor: 'grab' }}
|
||||
aria-label="Atlas"
|
||||
role="img"
|
||||
/>
|
||||
<div ref={labelsRef} aria-hidden="true" style={{ position: 'absolute', inset: 0, pointerEvents: 'none' }} />
|
||||
</div>
|
||||
);
|
||||
});
|
||||
|
||||
export default AtlasGlobe;
|
||||
@@ -0,0 +1,173 @@
|
||||
import type { BadgeMotif, BadgeTier } from '@trek/shared';
|
||||
import {
|
||||
CalendarClock,
|
||||
Compass,
|
||||
Earth,
|
||||
Flag,
|
||||
Flame,
|
||||
Footprints,
|
||||
Globe,
|
||||
Map as MapIcon,
|
||||
Moon,
|
||||
Orbit,
|
||||
Plane,
|
||||
PlaneTakeoff,
|
||||
Sailboat,
|
||||
Snowflake,
|
||||
Sparkles,
|
||||
Star,
|
||||
TowerControl,
|
||||
TreePalm,
|
||||
type LucideIcon,
|
||||
} from 'lucide-react';
|
||||
import React from 'react';
|
||||
import { TIERS } from './badgeTiers';
|
||||
|
||||
/**
|
||||
* A badge as a hexagonal glass medal: a tinted glass body, a ring in the tier's
|
||||
* metal, and a motif drawn for this badge alone. The shine is a CSS layer that
|
||||
* follows the pointer (see .ag-medal in atlasGlobe.css). Map/medal paint, not UI
|
||||
* surfaces, so the colours are literal here.
|
||||
*/
|
||||
|
||||
const HEX = '46,3 89,27 89,77 46,101 3,77 3,27';
|
||||
const INNER = '46,12 80,31 80,73 46,92 12,73 12,31';
|
||||
const INK = '#e0f2fe'; // theme-lint-disable: medal line art
|
||||
const ACCENT = '#7dd3fc'; // theme-lint-disable: medal line art
|
||||
|
||||
/**
|
||||
* One drawn symbol per motif, from the same icon set as the rest of TREK so every
|
||||
* medal reads at a glance and shares one stroke weight. Badges that come in steps
|
||||
* (5, 10, 25 countries) carry their number under the symbol.
|
||||
*/
|
||||
const ICONS: Record<BadgeMotif, LucideIcon> = {
|
||||
first: Footprints,
|
||||
countries: Flag,
|
||||
continents: Earth,
|
||||
seven: Earth,
|
||||
region: MapIcon,
|
||||
earth: Orbit,
|
||||
moon: Moon,
|
||||
flights: Plane,
|
||||
longhaul: PlaneTakeoff,
|
||||
airports: TowerControl,
|
||||
dateline: CalendarClock,
|
||||
equator: Globe,
|
||||
hemispheres: Compass,
|
||||
tropics: TreePalm,
|
||||
polar: Snowflake,
|
||||
streak: Flame,
|
||||
burst: Sparkles,
|
||||
wish: Star,
|
||||
islands: Sailboat,
|
||||
};
|
||||
|
||||
function Motif({ motif, label }: { motif: BadgeMotif; label?: string }): React.ReactElement {
|
||||
const Icon = ICONS[motif];
|
||||
if (motif === 'seven') {
|
||||
// All seven continents: the globe with seven lit points around it.
|
||||
return (
|
||||
<>
|
||||
<Icon x={31} y={37} size={30} color={INK} strokeWidth={1.6} />
|
||||
{Array.from({ length: 7 }, (_, i) => {
|
||||
const a = (i / 7) * Math.PI * 2 - Math.PI / 2;
|
||||
return <circle key={i} cx={46 + Math.cos(a) * 25} cy={52 + Math.sin(a) * 25} r="2.4" fill={ACCENT} />;
|
||||
})}
|
||||
</>
|
||||
);
|
||||
}
|
||||
if (!label) return <Icon x={28} y={34} size={36} color={INK} strokeWidth={1.5} />;
|
||||
const long = label.length >= 4;
|
||||
return (
|
||||
<>
|
||||
<Icon x={33} y={28} size={26} color={INK} strokeWidth={1.7} />
|
||||
<text
|
||||
x="46"
|
||||
y="75"
|
||||
textAnchor="middle"
|
||||
fontWeight="700"
|
||||
fontSize={long ? 11 : label.length === 3 ? 13 : 15}
|
||||
letterSpacing="0.2"
|
||||
fill={INK}
|
||||
>
|
||||
{label}
|
||||
</text>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
export interface BadgeMedalProps {
|
||||
motif: BadgeMotif;
|
||||
tier: BadgeTier;
|
||||
earned: boolean;
|
||||
/** 0..1 progress ring for a badge not yet earned. */
|
||||
progress?: number;
|
||||
/** Short text some motifs carry (a number, a country code). */
|
||||
label?: string;
|
||||
/** Back side: shown instead of the motif. */
|
||||
back?: React.ReactNode;
|
||||
size?: number;
|
||||
id: string;
|
||||
}
|
||||
|
||||
export default function BadgeMedal({
|
||||
motif,
|
||||
tier,
|
||||
earned,
|
||||
progress = 0,
|
||||
label,
|
||||
back,
|
||||
size = 92,
|
||||
id,
|
||||
}: BadgeMedalProps): React.ReactElement {
|
||||
const [c1, c2] = TIERS[tier];
|
||||
const g = `bm-${id}`;
|
||||
return (
|
||||
<svg viewBox="0 0 92 104" width={size} height={(size * 104) / 92} aria-hidden="true">
|
||||
<defs>
|
||||
<linearGradient id={`${g}-r`} x1="0" y1="0" x2="1" y2="1">
|
||||
<stop offset="0" stopColor={c1} />
|
||||
<stop offset="0.5" stopColor={c2} />
|
||||
<stop offset="1" stopColor={c1} />
|
||||
</linearGradient>
|
||||
<radialGradient id={`${g}-f`} cx="0.35" cy="0.25" r="0.9">
|
||||
<stop offset="0" stopColor="rgb(125 211 252 / 0.32)" />
|
||||
<stop offset="0.55" stopColor="rgb(30 41 70 / 0.82)" />
|
||||
<stop offset="1" stopColor="rgb(10 14 28 / 0.96)" />
|
||||
</radialGradient>
|
||||
<filter id={`${g}-g`} x="-30%" y="-30%" width="160%" height="160%">
|
||||
<feGaussianBlur stdDeviation="2" result="b" />
|
||||
<feMerge>
|
||||
<feMergeNode in="b" />
|
||||
<feMergeNode in="SourceGraphic" />
|
||||
</feMerge>
|
||||
</filter>
|
||||
</defs>
|
||||
<polygon
|
||||
points={HEX}
|
||||
fill={`url(#${g}-f)`}
|
||||
stroke={`url(#${g}-r)`}
|
||||
strokeWidth={earned ? 5 : 2}
|
||||
strokeOpacity={earned ? 1 : 0.35}
|
||||
strokeDasharray={earned ? undefined : '4 3'}
|
||||
/>
|
||||
<polygon points={INNER} fill="none" stroke="rgb(255 255 255 / 0.14)" strokeWidth="1" />
|
||||
{!earned && progress > 0 && (
|
||||
<polygon
|
||||
points={INNER}
|
||||
fill="none"
|
||||
stroke={ACCENT}
|
||||
strokeWidth="2.4"
|
||||
pathLength={100}
|
||||
strokeDasharray={`${Math.round(progress * 100)} 100`}
|
||||
strokeLinecap="round"
|
||||
filter={`url(#${g}-g)`}
|
||||
/>
|
||||
)}
|
||||
<g opacity={earned ? 1 : 0.38} filter={`url(#${g}-g)`}>
|
||||
{back ?? <Motif motif={motif} label={label} />}
|
||||
</g>
|
||||
<path d="M10 28 L46 8 L82 28" fill="none" stroke="rgb(255 255 255 / 0.35)" strokeWidth="1.2" />
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
import React from 'react';
|
||||
import DawarichIcon from '../shared/DawarichIcon';
|
||||
|
||||
/** Dawarich's mark at an icon's size, round like the symbols beside it. */
|
||||
export default function DawarichMark({ size = 16 }: { size?: number }): React.ReactElement {
|
||||
return (
|
||||
<span className="flex flex-none overflow-hidden rounded-full" style={{ width: size + 2, height: size + 2 }}>
|
||||
<DawarichIcon size={size + 2} />
|
||||
</span>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,803 @@
|
||||
/**
|
||||
* Drives the Atlas globe: camera with inertia and a zoom spring, gestures,
|
||||
* loading the right level of detail and the regions in view, picking, and one
|
||||
* animation loop that only runs while something moves.
|
||||
*
|
||||
* Framework free. AtlasGlobe.tsx mounts it and feeds it data; it reports back
|
||||
* through the callbacks in GlobeEngineOptions.
|
||||
*/
|
||||
import type { Topology } from 'topojson-specification';
|
||||
import { GlobeRenderer, MAX_FEATURES, type ArcLayer, type GlobeTheme } from './GlobeRenderer';
|
||||
import {
|
||||
frameParams,
|
||||
MAX_ZOOM,
|
||||
MIN_ZOOM,
|
||||
morphOf,
|
||||
projectPoint,
|
||||
RAD,
|
||||
sunVector,
|
||||
xSqueeze,
|
||||
type FrameParams,
|
||||
type GlobeCamera,
|
||||
type GlobeViewport,
|
||||
} from './globeMath';
|
||||
import { buildOcean, type BuiltLayer, type LineMesh } from './globeMesh';
|
||||
import type { MeshRequest, MeshResponse } from './globeMesh.worker';
|
||||
|
||||
export interface AtlasMeshManifest {
|
||||
version: number;
|
||||
lods: string[];
|
||||
regionLods: string[];
|
||||
world: Record<string, string>;
|
||||
countries: Array<{
|
||||
a2: string | null;
|
||||
a3: string;
|
||||
name: string;
|
||||
anchor: [number, number] | null;
|
||||
bbox: number[];
|
||||
area: number;
|
||||
}>;
|
||||
regions: Record<string, { bbox: number[]; counted: number; total: number; index: string }>;
|
||||
/** [a2, code, name, nameEn, lon, lat] per region */
|
||||
regionSearch?: string;
|
||||
attribution: string[];
|
||||
}
|
||||
|
||||
export interface RegionIndex {
|
||||
bbox: number[];
|
||||
counted: number;
|
||||
features: Array<{
|
||||
code: string | null;
|
||||
name: string | null;
|
||||
nameEn: string | null;
|
||||
anchor: [number, number] | null;
|
||||
counted: boolean;
|
||||
}>;
|
||||
files: Record<string, string>;
|
||||
}
|
||||
|
||||
export interface GlobeEngineOptions {
|
||||
canvas: HTMLCanvasElement;
|
||||
/** Fetches a JSON file below /api/addons/atlas/mesh/ (auth and API base are the caller's). */
|
||||
fetchJson: (path: string) => Promise<unknown>;
|
||||
theme: GlobeTheme;
|
||||
initial?: Partial<GlobeCamera>;
|
||||
onFrame?: (engine: GlobeEngine) => void;
|
||||
onHover?: (hit: GlobeHit | null, x: number, y: number) => void;
|
||||
onSelect?: (hit: GlobeHit | null, x: number, y: number) => void;
|
||||
onReady?: () => void;
|
||||
onError?: (err: unknown) => void;
|
||||
}
|
||||
|
||||
export type GlobeHit =
|
||||
| { kind: 'country'; index: number; a2: string | null }
|
||||
| { kind: 'region'; a2: string; code: string | null; name: string | null };
|
||||
|
||||
/** Zoom from which regions crossfade in, and from which the finer region files load. */
|
||||
export const REGION_FADE_START = 5;
|
||||
export const REGION_FADE_END = 6;
|
||||
/**
|
||||
* From here on the regions in view are fetched ahead, while the zoom is still
|
||||
* on its way, so they are drawn by the time they fade in instead of a beat later.
|
||||
*/
|
||||
const REGION_PREFETCH_ZOOM = 3;
|
||||
/** How often the view is checked for regions to fetch, in seconds. */
|
||||
const REGION_SCAN_EVERY = 0.2;
|
||||
/** A region file that failed is asked for again after this long, not every frame. */
|
||||
const REGION_RETRY_AFTER = 20;
|
||||
const REGION_FINE_ZOOM = 8;
|
||||
const WORLD_LOD_ZOOM: Array<[string, number]> = [
|
||||
['l2', 4.2],
|
||||
['l1', 2.0],
|
||||
['l0', 0],
|
||||
];
|
||||
const MAX_EDGE: Record<string, number> = { l0: 8, l1: 4, l2: 2, r0: 3, r1: 1.5 };
|
||||
const FIRST_REGION_ID = 512;
|
||||
|
||||
export class GlobeEngine {
|
||||
readonly renderer: GlobeRenderer;
|
||||
readonly cam: GlobeCamera = { lon: 10, lat: 30, zoom: 1 };
|
||||
manifest: AtlasMeshManifest | null = null;
|
||||
readonly regionIndex = new Map<string, RegionIndex>();
|
||||
/** Status-texture id of each country's first region. */
|
||||
readonly regionBase = new Map<string, number>();
|
||||
vp: GlobeViewport = { width: 1, height: 1, baseRadius: 1, globeY: 0, flatY: 0 };
|
||||
frame: FrameParams;
|
||||
theme: GlobeTheme;
|
||||
hover = -1;
|
||||
selected = -1;
|
||||
selectedOutline: LineMesh | null = null;
|
||||
arcs: ArcLayer[] = [];
|
||||
arcStart = 0;
|
||||
revealStart = 0;
|
||||
/** Set while something orbits the globe and needs every frame. */
|
||||
ambient = false;
|
||||
private reducedMotion =
|
||||
typeof window !== 'undefined' && window.matchMedia('(prefers-reduced-motion: reduce)').matches;
|
||||
private idleTimer = 0;
|
||||
/** Extra px at the bottom the map should keep clear (sheets, docks). */
|
||||
insetBottom = 0;
|
||||
|
||||
private opts: GlobeEngineOptions;
|
||||
private dpr = 1;
|
||||
private targetZoom = 1;
|
||||
private vx = 0;
|
||||
private vy = 0;
|
||||
private dragging = false;
|
||||
private pointers = new Map<number, { x: number; y: number }>();
|
||||
private pinch: { d: number; z: number } | null = null;
|
||||
private down: { x: number; y: number; t: number } | null = null;
|
||||
private fly: { from: GlobeCamera; to: GlobeCamera; t0: number; dur: number } | null = null;
|
||||
private raf = 0;
|
||||
private idleFrames = 0;
|
||||
private alive = true;
|
||||
private worker: Worker;
|
||||
private job = 0;
|
||||
private pending = new Map<number, { resolve: (l: BuiltLayer) => void; reject: (err: Error) => void }>();
|
||||
private worldLoading = new Set<string>();
|
||||
private regionLoading = new Set<string>();
|
||||
private regionFailedAt = new Map<string, number>();
|
||||
private regionScanAt = -1;
|
||||
private inViewRegionKeys: ReadonlySet<string> = new Set();
|
||||
private prefetchQueue: string[] = [];
|
||||
private prefetchTimer = 0;
|
||||
private nextRegionId = FIRST_REGION_ID;
|
||||
private ink: { id: number; lon: number; lat: number; t0: number } | null = null;
|
||||
private t0 = performance.now();
|
||||
private lastHoverAt = 0;
|
||||
private resizeObs: ResizeObserver;
|
||||
private regionKeys: string[] = [];
|
||||
private zoomAnchor: { x: number; y: number; lon: number; lat: number } | null = null;
|
||||
private sun: [number, number, number] = sunVector(new Date());
|
||||
private sunAt = 0;
|
||||
|
||||
constructor(opts: GlobeEngineOptions) {
|
||||
this.opts = opts;
|
||||
this.theme = opts.theme;
|
||||
Object.assign(this.cam, opts.initial ?? {});
|
||||
this.targetZoom = this.cam.zoom;
|
||||
this.renderer = new GlobeRenderer(opts.canvas);
|
||||
this.renderer.setOcean(buildOcean());
|
||||
this.frame = frameParams(this.cam, this.vp);
|
||||
this.worker = new Worker(new URL('./globeMesh.worker.ts', import.meta.url), { type: 'module' });
|
||||
// A build that fails rejects its own job only: the caller decides what that
|
||||
// means (a region stays plain, a missing world level keeps the coarser one).
|
||||
this.worker.onmessage = (e: MessageEvent<MeshResponse>) => {
|
||||
const job = this.pending.get(e.data.job);
|
||||
this.pending.delete(e.data.job);
|
||||
if (!job) return;
|
||||
if (e.data.layer) job.resolve(e.data.layer);
|
||||
else job.reject(new Error(e.data.error ?? 'Atlas mesh build failed'));
|
||||
};
|
||||
this.bindInput(opts.canvas);
|
||||
this.resizeObs = new ResizeObserver(() => this.resize());
|
||||
this.resizeObs.observe(opts.canvas);
|
||||
opts.canvas.addEventListener('webglcontextlost', this.onContextLost);
|
||||
this.resize();
|
||||
void this.boot();
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- loading
|
||||
|
||||
private build(topo: Topology, object: string, maxEdge: number, idBase: number): Promise<BuiltLayer> {
|
||||
const job = ++this.job;
|
||||
return new Promise((resolve, reject) => {
|
||||
this.pending.set(job, { resolve, reject });
|
||||
this.worker.postMessage({ job, topo, object, maxEdge, idBase } satisfies MeshRequest);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* A fetch tried again with growing pauses (1, 2, 4, 8 s): a server that is
|
||||
* restarting or a connection that drops for a moment must not leave the
|
||||
* globe empty for good.
|
||||
*/
|
||||
private async fetchRetrying(path: string): Promise<unknown> {
|
||||
for (let n = 0; ; n++) {
|
||||
try {
|
||||
return await this.opts.fetchJson(path);
|
||||
} catch (err) {
|
||||
if (n >= 4 || !this.alive) throw err;
|
||||
await new Promise((r) => window.setTimeout(r, 1000 * 2 ** n));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private async boot(): Promise<void> {
|
||||
try {
|
||||
this.manifest = (await this.fetchRetrying('manifest')) as AtlasMeshManifest;
|
||||
await this.loadWorld('l0');
|
||||
this.revealStart = this.now();
|
||||
this.opts.onReady?.();
|
||||
this.kick();
|
||||
} catch (err) {
|
||||
this.opts.onError?.(err);
|
||||
}
|
||||
}
|
||||
|
||||
private async loadWorld(lod: string): Promise<void> {
|
||||
if (!this.manifest || this.renderer.hasWorld(lod) || this.worldLoading.has(lod)) return;
|
||||
this.worldLoading.add(lod);
|
||||
try {
|
||||
const topo = (await this.fetchRetrying(`world/${this.manifest.world[lod]}`)) as Topology;
|
||||
const layer = await this.build(topo, 'countries', MAX_EDGE[lod], 0);
|
||||
if (!this.alive) return;
|
||||
this.renderer.setWorld(lod, layer);
|
||||
this.kick();
|
||||
} finally {
|
||||
this.worldLoading.delete(lod);
|
||||
}
|
||||
}
|
||||
|
||||
async loadRegionIndex(a2: string): Promise<RegionIndex | null> {
|
||||
const have = this.regionIndex.get(a2);
|
||||
if (have) return have;
|
||||
const entry = this.manifest?.regions[a2];
|
||||
if (!entry) return null;
|
||||
const idx = (await this.opts.fetchJson(entry.index)) as RegionIndex;
|
||||
if (!this.regionIndex.has(a2)) {
|
||||
this.regionIndex.set(a2, idx);
|
||||
if (this.nextRegionId + idx.features.length < MAX_FEATURES) {
|
||||
this.regionBase.set(a2, this.nextRegionId);
|
||||
this.nextRegionId += idx.features.length;
|
||||
}
|
||||
}
|
||||
return this.regionIndex.get(a2) ?? null;
|
||||
}
|
||||
|
||||
private async loadRegion(a2: string, lod: string): Promise<void> {
|
||||
const key = `${a2}:${lod}`;
|
||||
if (this.renderer.hasRegion(key) || this.regionLoading.has(key)) return;
|
||||
const failedAt = this.regionFailedAt.get(key);
|
||||
if (failedAt !== undefined && this.now() - failedAt < REGION_RETRY_AFTER) return;
|
||||
this.regionLoading.add(key);
|
||||
try {
|
||||
const idx = await this.loadRegionIndex(a2);
|
||||
const base = this.regionBase.get(a2);
|
||||
if (!idx || base === undefined) return;
|
||||
const topo = (await this.opts.fetchJson(idx.files[lod])) as Topology;
|
||||
const layer = await this.build(topo, 'regions', MAX_EDGE[lod], base);
|
||||
if (!this.alive) return;
|
||||
this.renderer.setRegion(key, layer, this.inViewRegionKeys);
|
||||
this.onRegionLoaded?.(a2);
|
||||
this.kick();
|
||||
} catch {
|
||||
// A country's regions are detail on top of a working globe: one that does
|
||||
// not load leaves the country plain and is asked for again later, it does
|
||||
// not turn the whole Atlas into an error.
|
||||
this.regionFailedAt.set(key, this.now());
|
||||
} finally {
|
||||
this.regionLoading.delete(key);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetches the coarse regions of these countries in the background, one at a
|
||||
* time while the browser is idle (the owner passes the countries the user is
|
||||
* most likely to zoom into), so their first zoom finds them ready.
|
||||
*/
|
||||
prefetchRegions(codes: string[]): void {
|
||||
const known = new Set(this.prefetchQueue);
|
||||
for (const a2 of codes) if (this.manifest?.regions[a2] && !known.has(a2)) this.prefetchQueue.push(a2);
|
||||
this.schedulePrefetch();
|
||||
}
|
||||
|
||||
private schedulePrefetch(): void {
|
||||
if (this.prefetchTimer || !this.prefetchQueue.length || !this.alive) return;
|
||||
const next = () => {
|
||||
this.prefetchTimer = 0;
|
||||
const a2 = this.prefetchQueue.shift();
|
||||
if (!a2 || !this.alive) return;
|
||||
void this.loadRegion(a2, 'r0').finally(() => this.schedulePrefetch());
|
||||
};
|
||||
const idle = (window as Window & { requestIdleCallback?: (cb: () => void, o?: { timeout: number }) => number })
|
||||
.requestIdleCallback;
|
||||
this.prefetchTimer = idle ? idle(next, { timeout: 1500 }) : window.setTimeout(next, 120);
|
||||
}
|
||||
|
||||
/** Called after a country's regions arrived, so the owner can colour them. */
|
||||
onRegionLoaded: ((a2: string) => void) | null = null;
|
||||
|
||||
private worldKey(): string {
|
||||
for (const [lod, z] of WORLD_LOD_ZOOM) if (this.cam.zoom >= z && this.renderer.hasWorld(lod)) return lod;
|
||||
for (const [lod] of WORLD_LOD_ZOOM.slice().reverse()) if (this.renderer.hasWorld(lod)) return lod;
|
||||
return 'l0';
|
||||
}
|
||||
|
||||
private wantedWorld(): string {
|
||||
for (const [lod, z] of WORLD_LOD_ZOOM) if (this.cam.zoom >= z) return lod;
|
||||
return 'l0';
|
||||
}
|
||||
|
||||
/** Countries with regions whose box overlaps the view, nearest first. */
|
||||
private countriesInView(): string[] {
|
||||
const m = this.manifest;
|
||||
if (!m) return [];
|
||||
const out: Array<[string, number]> = [];
|
||||
const { width, height } = this.vp;
|
||||
for (const c of m.countries) {
|
||||
if (!c.a2 || !m.regions[c.a2]) continue;
|
||||
const [w, s, e, n] = c.bbox;
|
||||
let best = Infinity;
|
||||
let inView = false;
|
||||
for (const [lon, lat] of [
|
||||
[(w + e) / 2, (s + n) / 2],
|
||||
[w, s],
|
||||
[e, n],
|
||||
[w, n],
|
||||
[e, s],
|
||||
c.anchor ?? [(w + e) / 2, (s + n) / 2],
|
||||
]) {
|
||||
const p = projectPoint(lon, lat, this.frame);
|
||||
if (p.visible < 0) continue;
|
||||
if (p.x > -200 && p.x < width + 200 && p.y > -200 && p.y < height + 200) inView = true;
|
||||
best = Math.min(best, Math.hypot(p.x - width / 2, p.y - height / 2));
|
||||
}
|
||||
if (inView) out.push([c.a2, best]);
|
||||
}
|
||||
return out
|
||||
.sort((a, b) => a[1] - b[1])
|
||||
.slice(0, 10)
|
||||
.map((x) => x[0]);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- camera
|
||||
|
||||
private now(): number {
|
||||
return (performance.now() - this.t0) / 1000;
|
||||
}
|
||||
|
||||
resize(): void {
|
||||
const c = this.opts.canvas;
|
||||
const r = c.getBoundingClientRect();
|
||||
this.dpr = Math.min(2, window.devicePixelRatio || 1);
|
||||
c.width = Math.max(1, Math.round(r.width * this.dpr));
|
||||
c.height = Math.max(1, Math.round(r.height * this.dpr));
|
||||
const narrow = r.width < 640;
|
||||
const usable = r.height - this.insetBottom;
|
||||
this.vp = {
|
||||
width: r.width,
|
||||
height: r.height,
|
||||
baseRadius: narrow ? r.width * 0.42 : Math.min(r.width, usable) * 0.31,
|
||||
// On a phone the globe sits a little lower, clear of the search and buttons on top.
|
||||
globeY: narrow ? usable * 0.54 : usable * 0.5,
|
||||
flatY: usable * 0.5,
|
||||
};
|
||||
this.kick();
|
||||
}
|
||||
|
||||
setInsetBottom(px: number): void {
|
||||
if (Math.abs(px - this.insetBottom) < 1) return;
|
||||
this.insetBottom = px;
|
||||
this.resize();
|
||||
}
|
||||
|
||||
setTheme(theme: GlobeTheme): void {
|
||||
this.theme = theme;
|
||||
this.kick();
|
||||
}
|
||||
|
||||
flyTo(lon: number, lat: number, zoom = Math.max(this.cam.zoom, 1), dur = 1100): void {
|
||||
let dl = lon - this.cam.lon;
|
||||
dl = ((dl + 540) % 360) - 180;
|
||||
this.fly = {
|
||||
from: { ...this.cam },
|
||||
to: { lon: this.cam.lon + dl, lat: Math.max(-70, Math.min(70, lat)), zoom },
|
||||
t0: performance.now(),
|
||||
dur,
|
||||
};
|
||||
this.vx = this.vy = 0;
|
||||
this.kick();
|
||||
}
|
||||
|
||||
/** Flies so a country's box fills the view. */
|
||||
flyToBox(bbox: number[], minZoom = 1, maxZoom = 7): void {
|
||||
const [w, s, e, n] = bbox;
|
||||
const span = Math.max(e - w, (n - s) * 1.6, 0.5);
|
||||
const zoom = Math.max(minZoom, Math.min(maxZoom, (110 / span) ** 0.85));
|
||||
this.flyTo((w + e) / 2, (s + n) / 2, zoom);
|
||||
}
|
||||
|
||||
zoomBy(f: number): void {
|
||||
this.targetZoom = Math.max(MIN_ZOOM, Math.min(MAX_ZOOM, this.targetZoom * f));
|
||||
this.kick();
|
||||
}
|
||||
|
||||
startInk(id: number, lon: number, lat: number): void {
|
||||
this.ink = { id, lon, lat, t0: this.now() };
|
||||
this.kick();
|
||||
}
|
||||
|
||||
setSelected(id: number, outline: LineMesh | null): void {
|
||||
this.selected = id;
|
||||
this.selectedOutline = outline;
|
||||
this.kick();
|
||||
}
|
||||
|
||||
setArcs(arcs: ArcLayer[]): void {
|
||||
this.arcs = arcs;
|
||||
this.arcStart = this.now();
|
||||
this.kick();
|
||||
}
|
||||
|
||||
project(lon: number, lat: number): ReturnType<typeof projectPoint> {
|
||||
return projectPoint(lon, lat, this.frame);
|
||||
}
|
||||
|
||||
get morph(): number {
|
||||
return this.frame.t;
|
||||
}
|
||||
|
||||
get regionAlpha(): number {
|
||||
const z = this.cam.zoom;
|
||||
return Math.max(0, Math.min(1, (z - REGION_FADE_START) / (REGION_FADE_END - REGION_FADE_START)));
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- input
|
||||
|
||||
private bindInput(c: HTMLCanvasElement): void {
|
||||
c.addEventListener('pointerdown', this.onDown);
|
||||
c.addEventListener('pointermove', this.onMove);
|
||||
c.addEventListener('pointerup', this.onUp);
|
||||
c.addEventListener('pointercancel', this.onUp);
|
||||
c.addEventListener('pointerleave', this.onLeave);
|
||||
c.addEventListener('wheel', this.onWheel, { passive: false });
|
||||
c.addEventListener('dblclick', this.onDbl);
|
||||
}
|
||||
|
||||
private local(e: PointerEvent | WheelEvent | MouseEvent): { x: number; y: number } {
|
||||
const r = this.opts.canvas.getBoundingClientRect();
|
||||
return { x: e.clientX - r.left, y: e.clientY - r.top };
|
||||
}
|
||||
|
||||
private onDown = (e: PointerEvent): void => {
|
||||
this.opts.canvas.setPointerCapture(e.pointerId);
|
||||
const p = this.local(e);
|
||||
this.pointers.set(e.pointerId, p);
|
||||
this.down = { ...p, t: performance.now() };
|
||||
this.vx = this.vy = 0;
|
||||
this.fly = null;
|
||||
this.zoomAnchor = null;
|
||||
this.dragging = true;
|
||||
this.clearHover();
|
||||
if (this.pointers.size === 2) {
|
||||
const [a, b] = [...this.pointers.values()];
|
||||
this.pinch = { d: Math.hypot(a.x - b.x, a.y - b.y), z: this.targetZoom };
|
||||
}
|
||||
this.kick();
|
||||
};
|
||||
|
||||
private onMove = (e: PointerEvent): void => {
|
||||
const p = this.local(e);
|
||||
const prev = this.pointers.get(e.pointerId);
|
||||
if (prev) {
|
||||
this.pointers.set(e.pointerId, p);
|
||||
if (this.pointers.size === 2 && this.pinch) {
|
||||
const [a, b] = [...this.pointers.values()];
|
||||
const d = Math.hypot(a.x - b.x, a.y - b.y);
|
||||
this.targetZoom = Math.max(MIN_ZOOM * 0.85, Math.min(MAX_ZOOM * 1.1, (this.pinch.z * d) / this.pinch.d));
|
||||
this.cam.zoom = this.targetZoom;
|
||||
this.kick();
|
||||
return;
|
||||
}
|
||||
if (this.pointers.size > 1) return;
|
||||
const k = 1 / (this.frame.scale * RAD);
|
||||
const kx = k / xSqueeze(this.frame);
|
||||
const dx = p.x - prev.x;
|
||||
const dy = p.y - prev.y;
|
||||
this.cam.lon -= dx * kx;
|
||||
this.cam.lat = Math.max(-80, Math.min(80, this.cam.lat + dy * k));
|
||||
this.vx = dx * kx * 0.85 + this.vx * 0.15;
|
||||
this.vy = dy * k * 0.85 + this.vy * 0.15;
|
||||
this.kick();
|
||||
return;
|
||||
}
|
||||
const now = performance.now();
|
||||
if (now - this.lastHoverAt < 45) return;
|
||||
this.lastHoverAt = now;
|
||||
const hit = this.hitAt(p.x, p.y);
|
||||
const id = hit ? this.idOf(hit) : -1;
|
||||
if (id !== this.hover) {
|
||||
this.hover = id;
|
||||
this.kick();
|
||||
}
|
||||
this.opts.onHover?.(hit, p.x, p.y);
|
||||
};
|
||||
|
||||
private onUp = (e: PointerEvent): void => {
|
||||
if (!this.pointers.has(e.pointerId)) return;
|
||||
this.pointers.delete(e.pointerId);
|
||||
if (this.pointers.size < 2) this.pinch = null;
|
||||
if (this.pointers.size > 0) return;
|
||||
this.dragging = false;
|
||||
const p = this.local(e);
|
||||
if (this.down && Math.hypot(p.x - this.down.x, p.y - this.down.y) < 6 && performance.now() - this.down.t < 400) {
|
||||
this.vx = this.vy = 0;
|
||||
this.opts.onSelect?.(this.hitAt(p.x, p.y), p.x, p.y);
|
||||
}
|
||||
this.down = null;
|
||||
this.kick();
|
||||
};
|
||||
|
||||
private onLeave = (): void => {
|
||||
if (this.dragging) return;
|
||||
this.hover = -1;
|
||||
this.opts.onHover?.(null, 0, 0);
|
||||
this.kick();
|
||||
};
|
||||
|
||||
/** Drops the hover while the camera moves; the next pointer move picks again. */
|
||||
private clearHover(): void {
|
||||
if (this.hover === -1) return;
|
||||
this.hover = -1;
|
||||
this.opts.onHover?.(null, 0, 0);
|
||||
}
|
||||
|
||||
private onWheel = (e: WheelEvent): void => {
|
||||
e.preventDefault();
|
||||
this.clearHover();
|
||||
const before = this.targetZoom;
|
||||
const f = Math.exp(-e.deltaY * (e.deltaMode === 1 ? 0.05 : 0.0016));
|
||||
this.targetZoom = Math.max(MIN_ZOOM * 0.9, Math.min(MAX_ZOOM, before * f));
|
||||
// On the flat map the place under the cursor stays under the cursor while the
|
||||
// zoom glides; tick() moves the centre to keep it there, frame by frame.
|
||||
if (this.frame.t > 0.5 && this.targetZoom !== before) {
|
||||
const p = this.local(e);
|
||||
const geo = this.unprojectFlat(p.x, p.y);
|
||||
this.zoomAnchor = { x: p.x, y: p.y, lon: geo[0], lat: geo[1] };
|
||||
}
|
||||
this.fly = null;
|
||||
this.kick();
|
||||
};
|
||||
|
||||
/** Screen point to lon/lat on the flat map (t = 1); close enough while t > 0.5. */
|
||||
private unprojectFlat(x: number, y: number): [number, number] {
|
||||
const f = this.frame;
|
||||
const k = 1 / (f.scale * RAD);
|
||||
return [this.cam.lon + ((x - f.originX) * k) / xSqueeze(f), this.cam.lat - (y - f.originY) * k];
|
||||
}
|
||||
|
||||
/** Moves the centre so the anchored place sits under its screen point again. */
|
||||
private holdAnchor(): void {
|
||||
const a = this.zoomAnchor;
|
||||
if (!a) return;
|
||||
for (let i = 0; i < 2; i++) {
|
||||
const f = frameParams(this.cam, this.vp);
|
||||
const k = 1 / (f.scale * RAD);
|
||||
this.cam.lat = Math.max(-80, Math.min(80, a.lat + (a.y - f.originY) * k));
|
||||
this.cam.lon = a.lon - ((a.x - f.originX) * k) / xSqueeze(f);
|
||||
}
|
||||
}
|
||||
|
||||
private onDbl = (e: MouseEvent): void => {
|
||||
const p = this.local(e);
|
||||
const hit = this.hitAt(p.x, p.y);
|
||||
if (!hit) this.zoomBy(1.8);
|
||||
};
|
||||
|
||||
private onContextLost = (e: Event): void => {
|
||||
e.preventDefault();
|
||||
this.opts.onError?.(new Error('WebGL context lost'));
|
||||
};
|
||||
|
||||
// ---------------------------------------------------------------- picking
|
||||
|
||||
idOf(hit: GlobeHit): number {
|
||||
if (hit.kind === 'country') return hit.index;
|
||||
const idx = this.regionIndex.get(hit.a2);
|
||||
const base = this.regionBase.get(hit.a2);
|
||||
if (!idx || base === undefined) return -1;
|
||||
const i = idx.features.findIndex((f) => f.code === hit.code);
|
||||
return i < 0 ? -1 : base + i;
|
||||
}
|
||||
|
||||
/**
|
||||
* The country under the middle of the view, the one whose regions get their
|
||||
* names. Read from the pick buffer, so it is the country really there and not
|
||||
* the first whose bounding box holds the point (France's box spans half the
|
||||
* world with its overseas parts). The read-back is not free, so it is only
|
||||
* redone when the camera moved, at most every 150 ms.
|
||||
*/
|
||||
focusCountry(): string | null {
|
||||
const now = this.now();
|
||||
const cam = `${this.cam.lon.toFixed(3)},${this.cam.lat.toFixed(3)},${this.cam.zoom.toFixed(2)}`;
|
||||
if (cam === this.focusCam || now - this.focusAt < 0.15) return this.focus;
|
||||
this.focusAt = now;
|
||||
this.focusCam = cam;
|
||||
const hit = this.hitAt(this.vp.width / 2, this.vp.height / 2);
|
||||
this.focus = hit?.a2 ?? null;
|
||||
return this.focus;
|
||||
}
|
||||
|
||||
private focus: string | null = null;
|
||||
private focusAt = -1;
|
||||
private focusCam = '';
|
||||
|
||||
hitAt(x: number, y: number): GlobeHit | null {
|
||||
const id = this.renderer.pick(x, y, this.regionAlpha > 0.5);
|
||||
if (id < 0) return null;
|
||||
if (id < FIRST_REGION_ID) {
|
||||
const c = this.manifest?.countries[id];
|
||||
return c ? { kind: 'country', index: id, a2: c.a2 } : null;
|
||||
}
|
||||
for (const [a2, base] of this.regionBase) {
|
||||
const idx = this.regionIndex.get(a2);
|
||||
if (idx && id >= base && id < base + idx.features.length) {
|
||||
const f = idx.features[id - base];
|
||||
return { kind: 'region', a2, code: f.code, name: f.nameEn ?? f.name };
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- loop
|
||||
|
||||
/** Starts the loop if it sleeps. */
|
||||
kick(): void {
|
||||
this.idleFrames = 0;
|
||||
if (this.idleTimer) {
|
||||
window.clearTimeout(this.idleTimer);
|
||||
this.idleTimer = 0;
|
||||
}
|
||||
if (!this.raf && this.alive) this.raf = requestAnimationFrame(this.tick);
|
||||
}
|
||||
|
||||
private tick = (): void => {
|
||||
this.raf = 0;
|
||||
if (!this.alive) return;
|
||||
let moving = false;
|
||||
const now = performance.now();
|
||||
if (this.fly) {
|
||||
const p = Math.min(1, (now - this.fly.t0) / this.fly.dur);
|
||||
const e = p < 0.5 ? 4 * p * p * p : 1 - Math.pow(-2 * p + 2, 3) / 2;
|
||||
const { from, to } = this.fly;
|
||||
this.cam.lon = from.lon + (to.lon - from.lon) * e;
|
||||
this.cam.lat = from.lat + (to.lat - from.lat) * e;
|
||||
// Pull back a little mid-flight, so long hops read as travel.
|
||||
const hop = Math.min(1, Math.abs(to.lon - from.lon) / 120) * Math.sin(Math.PI * e) * 0.35;
|
||||
this.cam.zoom = Math.max(MIN_ZOOM, from.zoom + (to.zoom - from.zoom) * e - hop * from.zoom);
|
||||
this.targetZoom = this.cam.zoom;
|
||||
if (p >= 1) {
|
||||
this.fly = null;
|
||||
this.targetZoom = to.zoom;
|
||||
}
|
||||
moving = true;
|
||||
}
|
||||
if (!this.dragging && !this.fly && (Math.abs(this.vx) > 1e-3 || Math.abs(this.vy) > 1e-3)) {
|
||||
this.cam.lon -= this.vx;
|
||||
this.cam.lat = Math.max(-80, Math.min(80, this.cam.lat + this.vy));
|
||||
this.vx *= 0.93;
|
||||
this.vy *= 0.93;
|
||||
moving = true;
|
||||
}
|
||||
if (!this.pinch) {
|
||||
if (this.targetZoom < MIN_ZOOM) this.targetZoom += (MIN_ZOOM - this.targetZoom) * 0.18;
|
||||
if (this.targetZoom > MAX_ZOOM) this.targetZoom += (MAX_ZOOM - this.targetZoom) * 0.18;
|
||||
}
|
||||
const dz = (this.targetZoom - this.cam.zoom) * 0.2;
|
||||
if (Math.abs(dz) > 1e-4) {
|
||||
this.cam.zoom += dz;
|
||||
moving = true;
|
||||
if (this.zoomAnchor && morphOf(this.cam.zoom) > 0.5) this.holdAnchor();
|
||||
} else {
|
||||
this.zoomAnchor = null;
|
||||
}
|
||||
this.cam.lon = ((this.cam.lon + 540) % 360) - 180;
|
||||
|
||||
this.frame = frameParams(this.cam, this.vp);
|
||||
const want = this.wantedWorld();
|
||||
// A finer level that cannot load leaves the coarser one on screen.
|
||||
if (!this.renderer.hasWorld(want)) this.loadWorld(want).catch(() => undefined);
|
||||
// Fetch ahead, by where the zoom is heading and not only where it is, and
|
||||
// during the motion too: the coarse regions well before they fade in, the
|
||||
// fine ones a step before they are drawn.
|
||||
const heading = Math.max(this.cam.zoom, this.targetZoom);
|
||||
const scanNow = this.now();
|
||||
if (heading >= REGION_PREFETCH_ZOOM && scanNow - this.regionScanAt >= REGION_SCAN_EVERY) {
|
||||
this.regionScanAt = scanNow;
|
||||
const fine = heading >= REGION_FINE_ZOOM - 1;
|
||||
const inView = this.countriesInView();
|
||||
// What is in view now is what must not be dropped, and the last to go.
|
||||
this.inViewRegionKeys = new Set(inView.flatMap((a2) => [`${a2}:r0`, `${a2}:r1`]));
|
||||
for (const k of this.inViewRegionKeys) this.renderer.touchRegion(k);
|
||||
for (const a2 of inView) {
|
||||
void this.loadRegion(a2, 'r0');
|
||||
if (fine) void this.loadRegion(a2, 'r1');
|
||||
}
|
||||
}
|
||||
this.regionKeys = this.collectRegionKeys();
|
||||
|
||||
const time = this.now();
|
||||
if (time - this.sunAt > 30) {
|
||||
this.sun = sunVector(new Date());
|
||||
this.sunAt = time;
|
||||
}
|
||||
let inkActive = false;
|
||||
let ink: { id: number; lon: number; lat: number; radius: number } | null = null;
|
||||
if (this.ink) {
|
||||
const p = (time - this.ink.t0) / 0.75;
|
||||
inkActive = p < 1;
|
||||
ink = {
|
||||
id: this.ink.id,
|
||||
lon: this.ink.lon,
|
||||
lat: this.ink.lat,
|
||||
radius: (1 - Math.pow(1 - Math.min(1, p), 3)) * Math.PI,
|
||||
};
|
||||
if (!inkActive) this.ink = null;
|
||||
}
|
||||
const arcProgress = Math.min(1.001, (time - this.arcStart) / 1.6);
|
||||
this.renderer.draw({
|
||||
frame: this.frame,
|
||||
dpr: this.dpr,
|
||||
width: this.vp.width,
|
||||
height: this.vp.height,
|
||||
time,
|
||||
revealStart: this.revealStart,
|
||||
hover: this.hover,
|
||||
selected: this.selected,
|
||||
ink,
|
||||
regionAlpha: this.regionAlpha,
|
||||
theme: this.theme,
|
||||
arcs: this.arcs,
|
||||
arcProgress,
|
||||
regionKeys: this.regionKeys,
|
||||
worldKey: this.worldKey(),
|
||||
selectedOutline: this.selectedOutline,
|
||||
sun: this.sun,
|
||||
night: this.theme.dark ? 0.34 : 0.1,
|
||||
});
|
||||
this.opts.onFrame?.(this);
|
||||
|
||||
const revealing = time - this.revealStart < 3.2;
|
||||
const twinkle = this.theme.dark && this.frame.t < 0.9;
|
||||
if (moving || inkActive || revealing || arcProgress < 1 || this.dragging) this.idleFrames = 0;
|
||||
else this.idleFrames++;
|
||||
// Things that orbit (moon, satellites) need every frame while the globe shows;
|
||||
// otherwise keep only the stars alive at a low rate once everything rests.
|
||||
const ambient = this.ambient && this.frame.t < 0.6 && !document.hidden && !this.reducedMotion;
|
||||
if (this.idleFrames < 3 || ambient) this.raf = requestAnimationFrame(this.tick);
|
||||
else if (twinkle) this.idleTimer = window.setTimeout(() => this.kick(), 90);
|
||||
};
|
||||
|
||||
private collectRegionKeys(): string[] {
|
||||
if (this.regionAlpha <= 0) return [];
|
||||
const fine = this.cam.zoom >= REGION_FINE_ZOOM;
|
||||
const out: string[] = [];
|
||||
for (const a2 of this.regionIndex.keys()) {
|
||||
const k1 = `${a2}:r1`;
|
||||
const k0 = `${a2}:r0`;
|
||||
if (fine && this.renderer.hasRegion(k1)) out.push(k1);
|
||||
else if (this.renderer.hasRegion(k0)) out.push(k0);
|
||||
else if (this.renderer.hasRegion(k1)) out.push(k1);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
get zoom(): number {
|
||||
return this.cam.zoom;
|
||||
}
|
||||
|
||||
isMorphing(): boolean {
|
||||
const t = morphOf(this.cam.zoom);
|
||||
return t > 0 && t < 1;
|
||||
}
|
||||
|
||||
dispose(): void {
|
||||
this.alive = false;
|
||||
this.prefetchQueue = [];
|
||||
window.clearTimeout(this.idleTimer);
|
||||
cancelAnimationFrame(this.raf);
|
||||
this.resizeObs.disconnect();
|
||||
this.worker.terminate();
|
||||
const c = this.opts.canvas;
|
||||
c.removeEventListener('pointerdown', this.onDown);
|
||||
c.removeEventListener('pointermove', this.onMove);
|
||||
c.removeEventListener('pointerup', this.onUp);
|
||||
c.removeEventListener('pointercancel', this.onUp);
|
||||
c.removeEventListener('pointerleave', this.onLeave);
|
||||
c.removeEventListener('wheel', this.onWheel);
|
||||
c.removeEventListener('dblclick', this.onDbl);
|
||||
c.removeEventListener('webglcontextlost', this.onContextLost);
|
||||
this.renderer.dispose();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
import { Star } from 'lucide-react';
|
||||
import { forwardRef, useImperativeHandle, useRef } from 'react';
|
||||
import type { GlobeEngine } from './GlobeEngine';
|
||||
|
||||
export interface GlobePin {
|
||||
key: string;
|
||||
lon: number;
|
||||
lat: number;
|
||||
title: string;
|
||||
/** A wish that was reached (ticked off by hand or by a recording). */
|
||||
reached?: boolean;
|
||||
onClick?: () => void;
|
||||
}
|
||||
|
||||
export interface GlobePinsHandle {
|
||||
layout: (engine: GlobeEngine) => void;
|
||||
}
|
||||
|
||||
/**
|
||||
* Places pinned on the globe, the bucket list's wishes with coordinates. Small
|
||||
* star buttons moved per frame with transform; hidden behind the horizon.
|
||||
*/
|
||||
const GlobePins = forwardRef<GlobePinsHandle, { pins: GlobePin[] }>(function GlobePins({ pins }, ref) {
|
||||
const refs = useRef<Array<HTMLButtonElement | null>>([]);
|
||||
useImperativeHandle(
|
||||
ref,
|
||||
() => ({
|
||||
layout(engine: GlobeEngine) {
|
||||
const { width, height } = engine.vp;
|
||||
pins.forEach((p, i) => {
|
||||
const el = refs.current[i];
|
||||
if (!el) return;
|
||||
const s = engine.project(p.lon, p.lat);
|
||||
const show = s.visible > 0.02 && s.x > -20 && s.x < width + 20 && s.y > -20 && s.y < height + 20;
|
||||
el.style.transform = `translate3d(${s.x.toFixed(1)}px, ${s.y.toFixed(1)}px, 0) translate(-50%, -50%)`;
|
||||
el.style.opacity = show ? String(Math.min(1, s.visible * 6)) : '0';
|
||||
el.style.pointerEvents = show ? 'auto' : 'none';
|
||||
});
|
||||
},
|
||||
}),
|
||||
[pins]
|
||||
);
|
||||
return (
|
||||
<>
|
||||
{pins.map((p, i) => (
|
||||
<button
|
||||
key={p.key}
|
||||
ref={(el) => {
|
||||
refs.current[i] = el;
|
||||
}}
|
||||
type="button"
|
||||
onClick={p.onClick}
|
||||
title={p.title}
|
||||
aria-label={p.title}
|
||||
// No press transition: the global one animates transform, and a pin moved
|
||||
// every frame would trail the globe and spring back to its place.
|
||||
data-no-press
|
||||
className="ag-pin absolute start-0 top-0"
|
||||
data-reached={p.reached ? '1' : '0'}
|
||||
>
|
||||
<Star size={11} strokeWidth={2.4} />
|
||||
</button>
|
||||
))}
|
||||
</>
|
||||
);
|
||||
});
|
||||
|
||||
export default GlobePins;
|
||||
@@ -0,0 +1,592 @@
|
||||
/**
|
||||
* WebGL2 renderer of the Atlas globe. Owns the GPU state only: programs,
|
||||
* layer buffers, the status textures and the picking target. What to show
|
||||
* comes in through setStatus()/setLayer() and one draw() per frame.
|
||||
*
|
||||
* Colours live in two small textures indexed by feature id, so marking a
|
||||
* country rewrites four bytes instead of rebuilding geometry.
|
||||
*/
|
||||
import type { FrameParams } from './globeMath';
|
||||
import type { BuiltLayer, FillMesh, LineMesh } from './globeMesh';
|
||||
import { FILL_FS, FILL_VS, LINE_FS, LINE_VS, PICK_FS, RIM_FS, SKY_FS, SKY_VS } from './globeShaders';
|
||||
|
||||
export const STATUS_TEX_W = 256;
|
||||
export const STATUS_TEX_H = 64;
|
||||
export const MAX_FEATURES = STATUS_TEX_W * STATUS_TEX_H;
|
||||
|
||||
export type Rgb = [number, number, number];
|
||||
|
||||
export interface GlobeTheme {
|
||||
land: Rgb;
|
||||
ocean: Rgb;
|
||||
oceanDeep: Rgb;
|
||||
space0: Rgb;
|
||||
space1: Rgb;
|
||||
glow: Rgb;
|
||||
border: [number, number, number, number];
|
||||
coast: [number, number, number, number];
|
||||
regionBorder: [number, number, number, number];
|
||||
selection: [number, number, number, number];
|
||||
arc: [number, number, number, number];
|
||||
dark: boolean;
|
||||
}
|
||||
|
||||
export interface ArcLayer {
|
||||
/** per segment: a.lon, a.lat, b.lon, b.lat, hA, hB, sA, sB */
|
||||
data: Float32Array;
|
||||
count: number;
|
||||
width: number;
|
||||
}
|
||||
|
||||
export interface DrawState {
|
||||
frame: FrameParams;
|
||||
dpr: number;
|
||||
width: number;
|
||||
height: number;
|
||||
time: number;
|
||||
revealStart: number;
|
||||
hover: number;
|
||||
selected: number;
|
||||
ink: { id: number; lon: number; lat: number; radius: number } | null;
|
||||
regionAlpha: number;
|
||||
theme: GlobeTheme;
|
||||
arcs: ArcLayer[];
|
||||
arcProgress: number;
|
||||
/** Region layers to draw, by key. */
|
||||
regionKeys: string[];
|
||||
worldKey: string;
|
||||
selectedOutline: LineMesh | null;
|
||||
/** Unit vector to the sun in earth-fixed coordinates. */
|
||||
sun: [number, number, number];
|
||||
night: number;
|
||||
}
|
||||
|
||||
interface Program {
|
||||
prog: WebGLProgram;
|
||||
u: Record<string, WebGLUniformLocation | null>;
|
||||
a: Record<string, number>;
|
||||
}
|
||||
|
||||
interface GpuFill {
|
||||
vao: WebGLVertexArrayObject;
|
||||
pickVao: WebGLVertexArrayObject;
|
||||
count: number;
|
||||
buffers: WebGLBuffer[];
|
||||
}
|
||||
|
||||
interface GpuLines {
|
||||
vao: WebGLVertexArrayObject;
|
||||
count: number;
|
||||
buffers: WebGLBuffer[];
|
||||
}
|
||||
|
||||
interface GpuLayer {
|
||||
fill: GpuFill;
|
||||
coast: GpuLines;
|
||||
borders: GpuLines;
|
||||
}
|
||||
|
||||
function compile(gl: WebGL2RenderingContext, type: number, src: string): WebGLShader {
|
||||
const s = gl.createShader(type) as WebGLShader;
|
||||
gl.shaderSource(s, src);
|
||||
gl.compileShader(s);
|
||||
if (!gl.getShaderParameter(s, gl.COMPILE_STATUS)) {
|
||||
const log = gl.getShaderInfoLog(s);
|
||||
gl.deleteShader(s);
|
||||
throw new Error(`Atlas globe shader failed: ${log ?? 'unknown'}`);
|
||||
}
|
||||
return s;
|
||||
}
|
||||
|
||||
function link(gl: WebGL2RenderingContext, vs: string, fs: string): Program {
|
||||
const prog = gl.createProgram() as WebGLProgram;
|
||||
gl.attachShader(prog, compile(gl, gl.VERTEX_SHADER, vs));
|
||||
gl.attachShader(prog, compile(gl, gl.FRAGMENT_SHADER, fs));
|
||||
gl.linkProgram(prog);
|
||||
if (!gl.getProgramParameter(prog, gl.LINK_STATUS)) {
|
||||
throw new Error(`Atlas globe program failed: ${gl.getProgramInfoLog(prog) ?? 'unknown'}`);
|
||||
}
|
||||
const u: Program['u'] = {};
|
||||
const n = gl.getProgramParameter(prog, gl.ACTIVE_UNIFORMS) as number;
|
||||
for (let i = 0; i < n; i++) {
|
||||
const info = gl.getActiveUniform(prog, i);
|
||||
if (info) u[info.name] = gl.getUniformLocation(prog, info.name);
|
||||
}
|
||||
const a: Program['a'] = {};
|
||||
const m = gl.getProgramParameter(prog, gl.ACTIVE_ATTRIBUTES) as number;
|
||||
for (let i = 0; i < m; i++) {
|
||||
const info = gl.getActiveAttrib(prog, i);
|
||||
if (info) a[info.name] = gl.getAttribLocation(prog, info.name);
|
||||
}
|
||||
return { prog, u, a };
|
||||
}
|
||||
|
||||
/** How many region layers (a country at one detail) stay on the GPU at most. */
|
||||
const MAX_REGION_LAYERS = 64;
|
||||
|
||||
export class GlobeRenderer {
|
||||
readonly gl: WebGL2RenderingContext;
|
||||
private fillP: Program;
|
||||
private pickP: Program;
|
||||
private lineP: Program;
|
||||
private skyP: Program;
|
||||
private rimP: Program;
|
||||
private quad: WebGLVertexArrayObject;
|
||||
private cornerBuf: WebGLBuffer;
|
||||
private statusTex: WebGLTexture;
|
||||
private fxTex: WebGLTexture;
|
||||
private status = new Uint8Array(MAX_FEATURES * 4);
|
||||
private fx = new Uint8Array(MAX_FEATURES * 4);
|
||||
private statusDirty = true;
|
||||
private ocean: GpuFill | null = null;
|
||||
private worlds = new Map<string, GpuLayer>();
|
||||
private regions = new Map<string, GpuLayer>();
|
||||
private arcs = new Map<ArcLayer, GpuLines>();
|
||||
private outline: { src: LineMesh; gpu: GpuLines } | null = null;
|
||||
private pickFbo: WebGLFramebuffer | null = null;
|
||||
private pickTex: WebGLTexture | null = null;
|
||||
private pickSize = [0, 0];
|
||||
private last: DrawState | null = null;
|
||||
|
||||
constructor(canvas: HTMLCanvasElement) {
|
||||
const gl = canvas.getContext('webgl2', {
|
||||
antialias: true,
|
||||
alpha: false,
|
||||
premultipliedAlpha: false,
|
||||
preserveDrawingBuffer: false,
|
||||
});
|
||||
if (!gl) throw new Error('WebGL2 unavailable');
|
||||
this.gl = gl;
|
||||
this.fillP = link(gl, FILL_VS, FILL_FS);
|
||||
this.pickP = link(gl, FILL_VS, PICK_FS);
|
||||
this.lineP = link(gl, LINE_VS, LINE_FS);
|
||||
this.skyP = link(gl, SKY_VS, SKY_FS);
|
||||
this.rimP = link(gl, SKY_VS, RIM_FS);
|
||||
this.quad = this.makeQuad();
|
||||
this.cornerBuf = gl.createBuffer() as WebGLBuffer;
|
||||
gl.bindBuffer(gl.ARRAY_BUFFER, this.cornerBuf);
|
||||
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([0, -1, 1, -1, 0, 1, 0, 1, 1, -1, 1, 1]), gl.STATIC_DRAW);
|
||||
this.statusTex = this.makeTex();
|
||||
this.fxTex = this.makeTex();
|
||||
}
|
||||
|
||||
private makeTex(): WebGLTexture {
|
||||
const gl = this.gl;
|
||||
const t = gl.createTexture() as WebGLTexture;
|
||||
gl.bindTexture(gl.TEXTURE_2D, t);
|
||||
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA8, STATUS_TEX_W, STATUS_TEX_H, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
|
||||
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
|
||||
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
|
||||
return t;
|
||||
}
|
||||
|
||||
private makeQuad(): WebGLVertexArrayObject {
|
||||
const gl = this.gl;
|
||||
const vao = gl.createVertexArray() as WebGLVertexArrayObject;
|
||||
gl.bindVertexArray(vao);
|
||||
const b = gl.createBuffer();
|
||||
gl.bindBuffer(gl.ARRAY_BUFFER, b);
|
||||
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([-1, -1, 1, -1, -1, 1, 1, 1]), gl.STATIC_DRAW);
|
||||
for (const p of [this.skyP, this.rimP]) {
|
||||
const loc = p.a.a_pos;
|
||||
if (loc === undefined) continue;
|
||||
gl.enableVertexAttribArray(loc);
|
||||
gl.vertexAttribPointer(loc, 2, gl.FLOAT, false, 0, 0);
|
||||
}
|
||||
gl.bindVertexArray(null);
|
||||
return vao;
|
||||
}
|
||||
|
||||
/** rgba: colour + fill strength. fx: hatch, reveal order (0..255), outline, spare. */
|
||||
setStatus(
|
||||
id: number,
|
||||
rgba: [number, number, number, number],
|
||||
fx: [number, number, number, number] = [0, 0, 0, 0]
|
||||
): void {
|
||||
if (id < 0 || id >= MAX_FEATURES) return;
|
||||
this.status.set(rgba, id * 4);
|
||||
this.fx.set(fx, id * 4);
|
||||
this.statusDirty = true;
|
||||
}
|
||||
|
||||
clearStatus(from: number, to: number): void {
|
||||
this.status.fill(0, from * 4, to * 4);
|
||||
this.fx.fill(0, from * 4, to * 4);
|
||||
this.statusDirty = true;
|
||||
}
|
||||
|
||||
private uploadFill(m: FillMesh): GpuFill {
|
||||
const gl = this.gl;
|
||||
const buffers: WebGLBuffer[] = [];
|
||||
const make = (data: Float32Array | Uint32Array, target: number): WebGLBuffer => {
|
||||
const b = gl.createBuffer() as WebGLBuffer;
|
||||
gl.bindBuffer(target, b);
|
||||
gl.bufferData(target, data, gl.STATIC_DRAW);
|
||||
buffers.push(b);
|
||||
return b;
|
||||
};
|
||||
const llB = make(m.ll, gl.ARRAY_BUFFER);
|
||||
const refB = make(m.ref, gl.ARRAY_BUFFER);
|
||||
const fidB = make(m.fid, gl.ARRAY_BUFFER);
|
||||
const idxB = make(m.index, gl.ELEMENT_ARRAY_BUFFER);
|
||||
const vaoFor = (p: Program): WebGLVertexArrayObject => {
|
||||
const vao = gl.createVertexArray() as WebGLVertexArrayObject;
|
||||
gl.bindVertexArray(vao);
|
||||
const bind = (name: string, buf: WebGLBuffer, size: number): void => {
|
||||
const loc = p.a[name];
|
||||
if (loc === undefined || loc < 0) return;
|
||||
gl.bindBuffer(gl.ARRAY_BUFFER, buf);
|
||||
gl.enableVertexAttribArray(loc);
|
||||
gl.vertexAttribPointer(loc, size, gl.FLOAT, false, 0, 0);
|
||||
};
|
||||
bind('a_ll', llB, 2);
|
||||
bind('a_ref', refB, 2);
|
||||
bind('a_fid', fidB, 1);
|
||||
gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, idxB);
|
||||
gl.bindVertexArray(null);
|
||||
return vao;
|
||||
};
|
||||
return { vao: vaoFor(this.fillP), pickVao: vaoFor(this.pickP), count: m.index.length, buffers };
|
||||
}
|
||||
|
||||
private uploadLines(seg: Float32Array, count: number, stride: 4 | 8): GpuLines {
|
||||
const gl = this.gl;
|
||||
const p = this.lineP;
|
||||
const vao = gl.createVertexArray() as WebGLVertexArrayObject;
|
||||
gl.bindVertexArray(vao);
|
||||
gl.bindBuffer(gl.ARRAY_BUFFER, this.cornerBuf);
|
||||
gl.enableVertexAttribArray(p.a.a_corner);
|
||||
gl.vertexAttribPointer(p.a.a_corner, 2, gl.FLOAT, false, 0, 0);
|
||||
const b = gl.createBuffer() as WebGLBuffer;
|
||||
gl.bindBuffer(gl.ARRAY_BUFFER, b);
|
||||
gl.bufferData(gl.ARRAY_BUFFER, seg, gl.STATIC_DRAW);
|
||||
const bytes = stride * 4;
|
||||
const attr = (name: string, offset: number): void => {
|
||||
const loc = p.a[name];
|
||||
if (loc === undefined || loc < 0) return;
|
||||
gl.enableVertexAttribArray(loc);
|
||||
gl.vertexAttribPointer(loc, 2, gl.FLOAT, false, bytes, offset);
|
||||
gl.vertexAttribDivisor(loc, 1);
|
||||
};
|
||||
attr('a_a', 0);
|
||||
attr('a_b', 8);
|
||||
if (stride === 8) {
|
||||
attr('a_h', 16);
|
||||
attr('a_s', 24);
|
||||
}
|
||||
gl.bindVertexArray(null);
|
||||
return { vao, count, buffers: [b] };
|
||||
}
|
||||
|
||||
private uploadLayer(l: BuiltLayer): GpuLayer {
|
||||
return {
|
||||
fill: this.uploadFill(l.fill),
|
||||
coast: this.uploadLines(l.coast.seg, l.coast.count, 4),
|
||||
borders: this.uploadLines(l.borders.seg, l.borders.count, 4),
|
||||
};
|
||||
}
|
||||
|
||||
private freeLayer(g: GpuLayer | null): void {
|
||||
if (!g) return;
|
||||
const gl = this.gl;
|
||||
for (const part of [g.fill, g.coast, g.borders]) {
|
||||
for (const b of part.buffers) gl.deleteBuffer(b);
|
||||
gl.deleteVertexArray(part.vao);
|
||||
}
|
||||
gl.deleteVertexArray(g.fill.pickVao);
|
||||
}
|
||||
|
||||
setOcean(m: FillMesh): void {
|
||||
this.ocean = this.uploadFill(m);
|
||||
}
|
||||
|
||||
setWorld(key: string, l: BuiltLayer): void {
|
||||
const next = this.uploadLayer(l);
|
||||
this.freeLayer(this.worlds.get(key) ?? null);
|
||||
this.worlds.set(key, next);
|
||||
}
|
||||
|
||||
hasWorld(key: string): boolean {
|
||||
return this.worlds.has(key);
|
||||
}
|
||||
|
||||
/**
|
||||
* Keeps a country's regions on the GPU. Past MAX_REGION_LAYERS the ones held
|
||||
* longest go (never one of `inUse`, the layers drawn now): a long session
|
||||
* over many countries would otherwise keep every region it ever touched.
|
||||
* Gone ones come back from the browser cache when they are wanted again.
|
||||
*/
|
||||
setRegion(key: string, l: BuiltLayer, inUse: ReadonlySet<string> = new Set()): void {
|
||||
const next = this.uploadLayer(l);
|
||||
this.freeLayer(this.regions.get(key) ?? null);
|
||||
this.regions.delete(key);
|
||||
this.regions.set(key, next);
|
||||
for (const old of [...this.regions.keys()]) {
|
||||
if (this.regions.size <= MAX_REGION_LAYERS) break;
|
||||
if (old === key || inUse.has(old)) continue;
|
||||
this.freeLayer(this.regions.get(old) ?? null);
|
||||
this.regions.delete(old);
|
||||
}
|
||||
}
|
||||
|
||||
/** Marks a region layer as just used, so it is the last to go. */
|
||||
touchRegion(key: string): void {
|
||||
const layer = this.regions.get(key);
|
||||
if (!layer) return;
|
||||
this.regions.delete(key);
|
||||
this.regions.set(key, layer);
|
||||
}
|
||||
|
||||
hasRegion(key: string): boolean {
|
||||
return this.regions.has(key);
|
||||
}
|
||||
|
||||
private arcGpu(a: ArcLayer): GpuLines {
|
||||
let g = this.arcs.get(a);
|
||||
if (!g) {
|
||||
g = this.uploadLines(a.data, a.count, 8);
|
||||
this.arcs.set(a, g);
|
||||
}
|
||||
return g;
|
||||
}
|
||||
|
||||
/** Frees the arc buffers of layers no longer drawn. */
|
||||
private pruneArcs(keep: ArcLayer[]): void {
|
||||
for (const [k, v] of this.arcs) {
|
||||
if (keep.includes(k)) continue;
|
||||
for (const b of v.buffers) this.gl.deleteBuffer(b);
|
||||
this.gl.deleteVertexArray(v.vao);
|
||||
this.arcs.delete(k);
|
||||
}
|
||||
}
|
||||
|
||||
private outlineGpu(m: LineMesh): GpuLines {
|
||||
if (this.outline?.src === m) return this.outline.gpu;
|
||||
if (this.outline) {
|
||||
for (const b of this.outline.gpu.buffers) this.gl.deleteBuffer(b);
|
||||
this.gl.deleteVertexArray(this.outline.gpu.vao);
|
||||
}
|
||||
const gpu = this.uploadLines(m.seg, m.count, 4);
|
||||
this.outline = { src: m, gpu };
|
||||
return gpu;
|
||||
}
|
||||
|
||||
private setProjection(p: Program, s: DrawState): void {
|
||||
const gl = this.gl;
|
||||
const f = s.frame;
|
||||
gl.uniform2f(p.u.u_center, f.centerLon, f.centerLat);
|
||||
gl.uniform1f(p.u.u_t, f.t);
|
||||
gl.uniform1f(p.u.u_scale, f.scale * s.dpr);
|
||||
gl.uniform2f(p.u.u_origin, f.originX * s.dpr, f.originY * s.dpr);
|
||||
gl.uniform2f(p.u.u_viewport, s.width * s.dpr, s.height * s.dpr);
|
||||
}
|
||||
|
||||
private get world(): GpuLayer | null {
|
||||
return this.last ? (this.worlds.get(this.last.worldKey) ?? null) : null;
|
||||
}
|
||||
|
||||
draw(s: DrawState): void {
|
||||
const gl = this.gl;
|
||||
this.last = s;
|
||||
const W = Math.round(s.width * s.dpr);
|
||||
const H = Math.round(s.height * s.dpr);
|
||||
gl.viewport(0, 0, W, H);
|
||||
gl.disable(gl.DEPTH_TEST);
|
||||
gl.enable(gl.BLEND);
|
||||
gl.blendFuncSeparate(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA);
|
||||
const th = s.theme;
|
||||
const f = s.frame;
|
||||
|
||||
// Sky
|
||||
gl.useProgram(this.skyP.prog);
|
||||
gl.uniform2f(this.skyP.u.u_viewport, W, H);
|
||||
gl.uniform2f(this.skyP.u.u_globe, f.originX * s.dpr, f.originY * s.dpr);
|
||||
gl.uniform1f(this.skyP.u.u_radius, f.scale * s.dpr);
|
||||
gl.uniform1f(this.skyP.u.u_t, f.t);
|
||||
gl.uniform1f(this.skyP.u.u_time, s.time);
|
||||
gl.uniform2f(this.skyP.u.u_drift, f.centerLon, f.centerLat);
|
||||
gl.uniform3fv(this.skyP.u.u_space0, th.space0);
|
||||
gl.uniform3fv(this.skyP.u.u_space1, th.space1);
|
||||
gl.uniform3fv(this.skyP.u.u_glow, th.glow);
|
||||
gl.uniform1f(this.skyP.u.u_dark, th.dark ? 1 : 0);
|
||||
gl.bindVertexArray(this.quad);
|
||||
gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4);
|
||||
|
||||
if (this.statusDirty) {
|
||||
gl.bindTexture(gl.TEXTURE_2D, this.statusTex);
|
||||
gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, 0, STATUS_TEX_W, STATUS_TEX_H, gl.RGBA, gl.UNSIGNED_BYTE, this.status);
|
||||
gl.bindTexture(gl.TEXTURE_2D, this.fxTex);
|
||||
gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, 0, STATUS_TEX_W, STATUS_TEX_H, gl.RGBA, gl.UNSIGNED_BYTE, this.fx);
|
||||
this.statusDirty = false;
|
||||
}
|
||||
|
||||
// Fills
|
||||
const p = this.fillP;
|
||||
gl.useProgram(p.prog);
|
||||
this.setProjection(p, s);
|
||||
gl.activeTexture(gl.TEXTURE0);
|
||||
gl.bindTexture(gl.TEXTURE_2D, this.statusTex);
|
||||
gl.uniform1i(p.u.u_status, 0);
|
||||
gl.activeTexture(gl.TEXTURE1);
|
||||
gl.bindTexture(gl.TEXTURE_2D, this.fxTex);
|
||||
gl.uniform1i(p.u.u_fx, 1);
|
||||
gl.uniform3fv(p.u.u_land, th.land);
|
||||
gl.uniform3fv(p.u.u_ocean, th.ocean);
|
||||
gl.uniform3fv(p.u.u_oceanDeep, th.oceanDeep);
|
||||
gl.uniform1f(p.u.u_time, s.time);
|
||||
gl.uniform1f(p.u.u_revealStart, s.revealStart);
|
||||
gl.uniform1i(p.u.u_hover, s.hover);
|
||||
gl.uniform1i(p.u.u_selected, s.selected);
|
||||
gl.uniform1i(p.u.u_inkId, s.ink ? s.ink.id : -1);
|
||||
gl.uniform2f(p.u.u_inkLL, s.ink ? (s.ink.lon * Math.PI) / 180 : 0, s.ink ? (s.ink.lat * Math.PI) / 180 : 0);
|
||||
gl.uniform1f(p.u.u_inkR, s.ink ? s.ink.radius : 0);
|
||||
gl.uniform1f(p.u.u_dpr, s.dpr);
|
||||
gl.uniform1f(p.u.u_layerAlpha, 1);
|
||||
gl.uniform3fv(p.u.u_sun, s.sun);
|
||||
gl.uniform1f(p.u.u_night, s.night);
|
||||
gl.uniform1f(p.u.u_shadeMin, th.dark ? 0.42 : 0.82);
|
||||
// Dark mode lights a hovered country up; on near-white land in light mode it tints it blue.
|
||||
if (th.dark) gl.uniform4f(p.u.u_hoverTint, 1, 1, 1, 0.09);
|
||||
else gl.uniform4f(p.u.u_hoverTint, 0.42, 0.56, 0.82, 0.16);
|
||||
if (this.ocean) {
|
||||
gl.uniform1i(p.u.u_mode, 1);
|
||||
gl.bindVertexArray(this.ocean.vao);
|
||||
gl.drawElements(gl.TRIANGLES, this.ocean.count, gl.UNSIGNED_INT, 0);
|
||||
}
|
||||
const regionsOn = s.regionAlpha > 0.001 && s.regionKeys.some((k) => this.regions.has(k));
|
||||
if (this.world) {
|
||||
gl.uniform1i(p.u.u_mode, 0);
|
||||
gl.uniform1f(p.u.u_dimBase, 1);
|
||||
gl.uniform1f(p.u.u_regionFade, s.regionAlpha);
|
||||
gl.bindVertexArray(this.world.fill.vao);
|
||||
gl.drawElements(gl.TRIANGLES, this.world.fill.count, gl.UNSIGNED_INT, 0);
|
||||
}
|
||||
if (regionsOn) {
|
||||
gl.uniform1i(p.u.u_mode, 2);
|
||||
gl.uniform1f(p.u.u_layerAlpha, s.regionAlpha);
|
||||
for (const k of s.regionKeys) {
|
||||
const r = this.regions.get(k);
|
||||
if (!r) continue;
|
||||
gl.bindVertexArray(r.fill.vao);
|
||||
gl.drawElements(gl.TRIANGLES, r.fill.count, gl.UNSIGNED_INT, 0);
|
||||
}
|
||||
}
|
||||
|
||||
// Lines
|
||||
const lp = this.lineP;
|
||||
gl.useProgram(lp.prog);
|
||||
this.setProjection(lp, s);
|
||||
gl.uniform1f(lp.u.u_lift, 0);
|
||||
gl.uniform1f(lp.u.u_progress, 2);
|
||||
gl.uniform1f(lp.u.u_glow, 0);
|
||||
const lines = (g: GpuLines, color: number[], width: number): void => {
|
||||
if (!g.count) return;
|
||||
gl.uniform4fv(lp.u.u_color, color);
|
||||
gl.uniform1f(lp.u.u_width, width * s.dpr);
|
||||
gl.bindVertexArray(g.vao);
|
||||
gl.vertexAttrib2f(lp.a.a_h, 0, 0);
|
||||
gl.vertexAttrib2f(lp.a.a_s, 0, 0);
|
||||
gl.drawArraysInstanced(gl.TRIANGLES, 0, 6, g.count);
|
||||
};
|
||||
if (regionsOn) {
|
||||
const c = [...th.regionBorder];
|
||||
c[3] *= s.regionAlpha;
|
||||
for (const k of s.regionKeys) {
|
||||
const r = this.regions.get(k);
|
||||
if (r) lines(r.borders, c, 0.7);
|
||||
}
|
||||
}
|
||||
if (this.world) {
|
||||
lines(this.world.borders, th.border, 0.8);
|
||||
lines(this.world.coast, th.coast, 0.9);
|
||||
}
|
||||
if (s.selectedOutline) {
|
||||
gl.uniform1f(lp.u.u_glow, 0.55);
|
||||
lines(this.outlineGpu(s.selectedOutline), th.selection, 1.8);
|
||||
gl.uniform1f(lp.u.u_glow, 0);
|
||||
}
|
||||
if (this.arcs.size > s.arcs.length) this.pruneArcs(s.arcs);
|
||||
if (s.arcs.length) {
|
||||
gl.uniform1f(lp.u.u_lift, 1);
|
||||
gl.uniform1f(lp.u.u_progress, s.arcProgress);
|
||||
for (const a of s.arcs) {
|
||||
const g = this.arcGpu(a);
|
||||
gl.uniform4fv(lp.u.u_color, th.arc);
|
||||
gl.uniform1f(lp.u.u_width, a.width * s.dpr);
|
||||
gl.uniform1f(lp.u.u_glow, 0.35);
|
||||
gl.bindVertexArray(g.vao);
|
||||
gl.drawArraysInstanced(gl.TRIANGLES, 0, 6, g.count);
|
||||
}
|
||||
gl.uniform1f(lp.u.u_lift, 0);
|
||||
}
|
||||
|
||||
// Rim light over the limb
|
||||
gl.useProgram(this.rimP.prog);
|
||||
gl.uniform2f(this.rimP.u.u_viewport, W, H);
|
||||
gl.uniform2f(this.rimP.u.u_globe, f.originX * s.dpr, f.originY * s.dpr);
|
||||
gl.uniform1f(this.rimP.u.u_radius, f.scale * s.dpr);
|
||||
gl.uniform1f(this.rimP.u.u_t, f.t);
|
||||
gl.uniform3fv(this.rimP.u.u_glow, th.glow);
|
||||
gl.bindVertexArray(this.quad);
|
||||
gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4);
|
||||
gl.bindVertexArray(null);
|
||||
}
|
||||
|
||||
/** Feature id under a CSS-pixel position, or -1. Renders an id pass of the last frame. */
|
||||
pick(x: number, y: number, includeRegions: boolean): number {
|
||||
const s = this.last;
|
||||
if (!s) return -1;
|
||||
const gl = this.gl;
|
||||
const W = Math.round(s.width * s.dpr);
|
||||
const H = Math.round(s.height * s.dpr);
|
||||
if (!this.pickFbo || this.pickSize[0] !== W || this.pickSize[1] !== H) {
|
||||
if (this.pickTex) gl.deleteTexture(this.pickTex);
|
||||
if (this.pickFbo) gl.deleteFramebuffer(this.pickFbo);
|
||||
this.pickTex = gl.createTexture();
|
||||
gl.bindTexture(gl.TEXTURE_2D, this.pickTex);
|
||||
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA8, W, H, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
|
||||
this.pickFbo = gl.createFramebuffer();
|
||||
gl.bindFramebuffer(gl.FRAMEBUFFER, this.pickFbo);
|
||||
gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, this.pickTex, 0);
|
||||
this.pickSize = [W, H];
|
||||
}
|
||||
gl.bindFramebuffer(gl.FRAMEBUFFER, this.pickFbo);
|
||||
gl.viewport(0, 0, W, H);
|
||||
gl.disable(gl.BLEND);
|
||||
gl.clearColor(0, 0, 0, 0);
|
||||
gl.clear(gl.COLOR_BUFFER_BIT);
|
||||
const p = this.pickP;
|
||||
gl.useProgram(p.prog);
|
||||
this.setProjection(p, s);
|
||||
if (this.world) {
|
||||
gl.bindVertexArray(this.world.fill.pickVao);
|
||||
gl.drawElements(gl.TRIANGLES, this.world.fill.count, gl.UNSIGNED_INT, 0);
|
||||
}
|
||||
if (includeRegions) {
|
||||
for (const k of s.regionKeys) {
|
||||
const r = this.regions.get(k);
|
||||
if (!r) continue;
|
||||
gl.bindVertexArray(r.fill.pickVao);
|
||||
gl.drawElements(gl.TRIANGLES, r.fill.count, gl.UNSIGNED_INT, 0);
|
||||
}
|
||||
}
|
||||
const px = new Uint8Array(4);
|
||||
gl.readPixels(Math.round(x * s.dpr), H - Math.round(y * s.dpr) - 1, 1, 1, gl.RGBA, gl.UNSIGNED_BYTE, px);
|
||||
gl.bindFramebuffer(gl.FRAMEBUFFER, null);
|
||||
gl.bindVertexArray(null);
|
||||
gl.enable(gl.BLEND);
|
||||
const id = px[0] + (px[1] << 8) + (px[2] << 16);
|
||||
return id - 1;
|
||||
}
|
||||
|
||||
dispose(): void {
|
||||
const gl = this.gl;
|
||||
for (const w of this.worlds.values()) this.freeLayer(w);
|
||||
this.worlds.clear();
|
||||
for (const r of this.regions.values()) this.freeLayer(r);
|
||||
this.regions.clear();
|
||||
// The context is left alive: React mounts twice in development and the
|
||||
// second engine takes over the same canvas.
|
||||
void gl;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
import { forwardRef, useImperativeHandle, useMemo, useRef } from 'react';
|
||||
import type { GlobeEngine } from './GlobeEngine';
|
||||
import { moonPhase, smoothstep } from './globeMath';
|
||||
|
||||
export interface GlobeSkyHandle {
|
||||
layout: (engine: GlobeEngine) => void;
|
||||
/** A shooting star across the sky, for the moment something is marked. */
|
||||
shootingStar: () => void;
|
||||
}
|
||||
|
||||
/**
|
||||
* What hangs in the sky around the globe: the moon in its real phase, and the
|
||||
* shooting star that crosses when a country is marked. The moon is placed per
|
||||
* frame without React rendering.
|
||||
*/
|
||||
const GlobeSky = forwardRef<GlobeSkyHandle, { dark: boolean }>(function GlobeSky({ dark }, ref) {
|
||||
const moonRef = useRef<HTMLDivElement>(null);
|
||||
const starHost = useRef<HTMLDivElement>(null);
|
||||
const phase = useMemo(() => moonPhase(new Date()), []);
|
||||
|
||||
useImperativeHandle(
|
||||
ref,
|
||||
() => ({
|
||||
layout(engine: GlobeEngine) {
|
||||
const f = engine.frame;
|
||||
const { width, height } = engine.vp;
|
||||
const fade = 1 - smoothstep(0.05, 0.6, f.t);
|
||||
if (!moonRef.current) return;
|
||||
if (!dark) {
|
||||
moonRef.current.style.opacity = '0';
|
||||
return;
|
||||
}
|
||||
const d = Math.max(f.scale * 1.75, Math.min(width, height) * 0.42);
|
||||
const x = f.originX + Math.cos(-0.65) * d * 1.25;
|
||||
const y = f.originY + Math.sin(-0.65) * d * 0.62;
|
||||
moonRef.current.style.transform = `translate3d(${x.toFixed(1)}px, ${y.toFixed(1)}px, 0) translate(-50%, -50%)`;
|
||||
moonRef.current.style.opacity = String(fade * 0.95);
|
||||
},
|
||||
shootingStar() {
|
||||
const host = starHost.current;
|
||||
if (!host || !dark || window.matchMedia('(prefers-reduced-motion: reduce)').matches) return;
|
||||
const el = document.createElement('div');
|
||||
el.className = 'ag-shooting-star';
|
||||
el.style.left = `${host.clientWidth * (0.55 + Math.random() * 0.35)}px`;
|
||||
el.style.top = `${host.clientHeight * (0.05 + Math.random() * 0.25)}px`;
|
||||
host.appendChild(el);
|
||||
el.animate(
|
||||
[
|
||||
{ transform: 'rotate(-28deg) translateX(0) scaleX(0.2)', opacity: 0 },
|
||||
{ transform: 'rotate(-28deg) translateX(-90px) scaleX(1)', opacity: 1, offset: 0.25 },
|
||||
{ transform: 'rotate(-28deg) translateX(-420px) scaleX(0.6)', opacity: 0 },
|
||||
],
|
||||
{ duration: 1100, easing: 'cubic-bezier(.2,.6,.3,1)' }
|
||||
).onfinish = () => el.remove();
|
||||
},
|
||||
}),
|
||||
[dark]
|
||||
);
|
||||
|
||||
// The lit part of the moon: the disc with an ellipse carving the shadow.
|
||||
const lit = phase.lit;
|
||||
const waxing = phase.phase < 0.5;
|
||||
const k = Math.abs(1 - 2 * lit);
|
||||
const shadowPath = `M 14 1 A 13 13 0 0 ${waxing ? 0 : 1} 14 27 A ${(13 * k).toFixed(2)} 13 0 0 ${lit > 0.5 === waxing ? 1 : 0} 14 1 Z`;
|
||||
|
||||
return (
|
||||
<>
|
||||
<div ref={starHost} aria-hidden="true" className="pointer-events-none absolute inset-0 overflow-hidden" />
|
||||
<div
|
||||
ref={moonRef}
|
||||
aria-hidden="true"
|
||||
className="pointer-events-none absolute start-0 top-0"
|
||||
style={{ filter: 'drop-shadow(0 0 14px rgb(220 230 255 / 0.35))' }}
|
||||
>
|
||||
<svg width="28" height="28" viewBox="0 0 28 28">
|
||||
<defs>
|
||||
<radialGradient id="ag-moon" cx="0.4" cy="0.35" r="0.75">
|
||||
<stop offset="0" stopColor="rgb(244 246 251)" />
|
||||
<stop offset="1" stopColor="rgb(170 179 197)" />
|
||||
</radialGradient>
|
||||
</defs>
|
||||
<circle cx="14" cy="14" r="13" fill="url(#ag-moon)" />
|
||||
<circle cx="10" cy="10" r="2.4" fill="rgb(0 0 0)" opacity="0.07" />
|
||||
<circle cx="17" cy="17" r="3.2" fill="rgb(0 0 0)" opacity="0.06" />
|
||||
<path d={shadowPath} fill="rgb(7 10 20)" opacity="0.88" />
|
||||
</svg>
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
});
|
||||
|
||||
export default GlobeSky;
|
||||
@@ -0,0 +1,55 @@
|
||||
import type { LucideIcon } from 'lucide-react';
|
||||
import React from 'react';
|
||||
|
||||
export interface GlobeStat {
|
||||
key: string;
|
||||
icon: LucideIcon;
|
||||
value: React.ReactNode;
|
||||
label: string;
|
||||
onClick?: () => void;
|
||||
}
|
||||
|
||||
const CARD =
|
||||
'ag-liquid-card flex w-[132px] flex-none flex-col justify-between gap-2 rounded-[14px] px-3 py-2.5 text-start transition-colors';
|
||||
|
||||
/**
|
||||
* The Atlas numbers in the bottom corner: the frosted card every floating map
|
||||
* control in TREK uses, holding one small card per number (badge in badge).
|
||||
* A number with an action is a button.
|
||||
*/
|
||||
export default function GlobeStatsBar({
|
||||
stats,
|
||||
className = 'bottom-[22px] start-[22px] max-w-[calc(100%-120px)]',
|
||||
}: {
|
||||
stats: GlobeStat[];
|
||||
className?: string;
|
||||
}): React.ReactElement {
|
||||
return (
|
||||
<div
|
||||
className={`ag-liquid pointer-events-auto absolute flex gap-1.5 overflow-x-auto rounded-[20px] p-1.5 ${className}`}
|
||||
style={{ scrollbarWidth: 'none' }}
|
||||
>
|
||||
{stats.map((s) => {
|
||||
const Icon = s.icon;
|
||||
const body = (
|
||||
<>
|
||||
<span className="flex items-start justify-between gap-2">
|
||||
<span className="text-title font-semibold tabular-nums leading-none text-content">{s.value}</span>
|
||||
<Icon size={16} strokeWidth={1.9} className="mt-0.5 flex-none text-content-muted" />
|
||||
</span>
|
||||
<span className="whitespace-nowrap text-caption text-content-muted">{s.label}</span>
|
||||
</>
|
||||
);
|
||||
return s.onClick ? (
|
||||
<button key={s.key} type="button" onClick={s.onClick} className={CARD}>
|
||||
{body}
|
||||
</button>
|
||||
) : (
|
||||
<div key={s.key} className={CARD}>
|
||||
{body}
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,311 @@
|
||||
/*
|
||||
* The globe Atlas chrome: glass capsules, labels, the country card.
|
||||
* The globe is its own night sky, so the glass is tuned against it rather than
|
||||
* against the app surfaces. The scene is a night sky in both modes; the controls
|
||||
* on top (search, zoom, stats) follow the app's light or dark mode.
|
||||
*/
|
||||
.atlas-globe {
|
||||
--ag-glass: linear-gradient(180deg, rgb(255 255 255 / 0.11), rgb(255 255 255 / 0.04));
|
||||
--ag-glass-solid: rgb(16 20 34 / 0.9);
|
||||
--ag-edge: rgb(255 255 255 / 0.13);
|
||||
--ag-edge-hi: rgb(255 255 255 / 0.3);
|
||||
--ag-hi: inset 0 1px 0 rgb(255 255 255 / 0.22);
|
||||
--ag-shadow: 0 12px 32px rgb(0 0 0 / 0.38);
|
||||
--ag-ink: rgb(238 242 255);
|
||||
--ag-muted: rgb(150 160 182);
|
||||
--ag-faint: rgb(100 110 132);
|
||||
--ag-accent: rgb(125 211 252);
|
||||
--ag-mint: rgb(94 234 212);
|
||||
--ag-label: rgb(226 232 245 / 0.92);
|
||||
--ag-label-shadow: 0 1px 2px rgb(0 0 0 / 0.85), 0 0 10px rgb(0 0 0 / 0.55);
|
||||
position: relative;
|
||||
color: var(--ag-ink);
|
||||
background: rgb(3 5 12);
|
||||
}
|
||||
|
||||
html:not(.dark) .ag-btn {
|
||||
background: rgb(15 23 42 / 0.04);
|
||||
}
|
||||
|
||||
html:not(.dark) .ag-btn[data-on='1'] {
|
||||
background: rgb(37 99 235 / 0.12);
|
||||
border-color: rgb(37 99 235 / 0.4);
|
||||
}
|
||||
|
||||
html:not(.dark) .ag-bar {
|
||||
background: rgb(15 23 42 / 0.08);
|
||||
}
|
||||
|
||||
.ag-glass {
|
||||
background: var(--ag-glass);
|
||||
border: 1px solid var(--ag-edge);
|
||||
box-shadow: var(--ag-hi), var(--ag-shadow);
|
||||
backdrop-filter: blur(18px) saturate(150%);
|
||||
-webkit-backdrop-filter: blur(18px) saturate(150%);
|
||||
}
|
||||
|
||||
[data-no-transparency] .ag-glass,
|
||||
.atlas-globe[data-moving='1'] .ag-glass-big {
|
||||
backdrop-filter: none;
|
||||
-webkit-backdrop-filter: none;
|
||||
background: var(--ag-glass-solid);
|
||||
}
|
||||
|
||||
.atlas-globe-label {
|
||||
position: absolute;
|
||||
left: 0; /* rtl-lint-disable: placed by a measured x on the canvas, physical on purpose */
|
||||
top: 0;
|
||||
white-space: nowrap;
|
||||
font-weight: 500;
|
||||
letter-spacing: 0.01em;
|
||||
color: var(--ag-label);
|
||||
text-shadow: var(--ag-label-shadow);
|
||||
will-change: transform, opacity;
|
||||
transition: opacity 0.25s;
|
||||
}
|
||||
|
||||
.atlas-globe-label[data-region='1'] {
|
||||
font-weight: 400;
|
||||
opacity: 0.85;
|
||||
letter-spacing: 0.02em;
|
||||
}
|
||||
|
||||
.ag-num {
|
||||
font-variant-numeric: tabular-nums;
|
||||
letter-spacing: -0.02em;
|
||||
}
|
||||
|
||||
.ag-muted {
|
||||
color: var(--ag-muted);
|
||||
}
|
||||
|
||||
.ag-faint {
|
||||
color: var(--ag-faint);
|
||||
}
|
||||
|
||||
.ag-btn {
|
||||
border: 1px solid var(--ag-edge);
|
||||
background: rgb(255 255 255 / 0.06);
|
||||
transition:
|
||||
border-color 0.2s,
|
||||
background 0.2s;
|
||||
}
|
||||
|
||||
.ag-btn:hover {
|
||||
border-color: var(--ag-edge-hi);
|
||||
}
|
||||
|
||||
.ag-btn[data-on='1'] {
|
||||
background: rgb(125 211 252 / 0.18);
|
||||
border-color: rgb(125 211 252 / 0.5);
|
||||
}
|
||||
|
||||
.ag-bar {
|
||||
height: 6px;
|
||||
border-radius: 99px;
|
||||
background: rgb(255 255 255 / 0.09);
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.ag-bar > i {
|
||||
display: block;
|
||||
height: 100%;
|
||||
border-radius: 99px;
|
||||
background: linear-gradient(90deg, var(--ag-accent), var(--ag-mint));
|
||||
box-shadow: 0 0 12px rgb(125 211 252 / 0.55);
|
||||
transition: width 0.9s cubic-bezier(0.2, 0.9, 0.2, 1);
|
||||
}
|
||||
|
||||
/* A badge in the Passport: a glass medal that tilts towards the pointer and flips. */
|
||||
.ag-medal {
|
||||
perspective: 600px;
|
||||
cursor: default;
|
||||
}
|
||||
|
||||
.ag-medal[data-earned='1'] {
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.ag-medal-body {
|
||||
position: relative;
|
||||
display: block;
|
||||
width: 92px;
|
||||
height: 104px;
|
||||
transform-style: preserve-3d;
|
||||
transform: rotateX(var(--rx, 0deg)) rotateY(calc(var(--ry, 0deg) + var(--flip, 0deg)));
|
||||
transition: transform 0.7s cubic-bezier(0.2, 0.9, 0.25, 1.1);
|
||||
}
|
||||
|
||||
.ag-medal[data-flipped='1'] {
|
||||
--flip: 180deg;
|
||||
}
|
||||
|
||||
.ag-medal-face,
|
||||
.ag-medal-back {
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
backface-visibility: hidden;
|
||||
}
|
||||
|
||||
.ag-medal-back {
|
||||
transform: rotateY(180deg);
|
||||
}
|
||||
|
||||
.ag-medal-shine {
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
clip-path: polygon(50% 0, 100% 25%, 100% 75%, 50% 100%, 0 75%, 0 25%);
|
||||
background:
|
||||
radial-gradient(60% 45% at var(--mx, 30%) var(--my, 20%), rgb(255 255 255 / 0.5), rgb(255 255 255 / 0) 60%),
|
||||
linear-gradient(
|
||||
115deg,
|
||||
rgb(125 211 252 / 0) 30%,
|
||||
rgb(167 139 250 / 0.22) 45%,
|
||||
rgb(94 234 212 / 0.2) 55%,
|
||||
rgb(125 211 252 / 0) 70%
|
||||
);
|
||||
mix-blend-mode: screen;
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
.ag-medal[data-earned='0'] .ag-medal-shine {
|
||||
opacity: 0.25;
|
||||
}
|
||||
|
||||
.ag-shooting-star {
|
||||
position: absolute;
|
||||
width: 140px;
|
||||
height: 2px;
|
||||
border-radius: 99px;
|
||||
transform-origin: right center;
|
||||
background: linear-gradient(90deg, rgb(255 255 255 / 0), rgb(255 255 255 / 0.95));
|
||||
box-shadow: 0 0 10px rgb(186 230 253 / 0.8);
|
||||
}
|
||||
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.ag-medal-body {
|
||||
transform: rotateY(var(--flip, 0deg));
|
||||
}
|
||||
|
||||
.ag-bar > i,
|
||||
.atlas-globe-label {
|
||||
transition: none;
|
||||
}
|
||||
}
|
||||
|
||||
/*
|
||||
* The controls on top of the scene wear TREK's map chrome, like every floating
|
||||
* map control in the app: the sidebar surface, the app's text colours and the
|
||||
* map control shadow. Only the scene itself (sky, globe, labels) is Atlas's own.
|
||||
*/
|
||||
:root .atlas-globe.atlas-globe {
|
||||
--ag-glass: var(--sidebar-bg);
|
||||
--ag-glass-solid: var(--sidebar-bg);
|
||||
--ag-edge: var(--border-primary);
|
||||
--ag-edge-hi: var(--text-faint, var(--border-primary));
|
||||
--ag-hi: 0 0 0 0 transparent;
|
||||
--ag-shadow: 0 2px 10px rgb(0 0 0 / 0.25);
|
||||
--ag-ink: var(--text-primary);
|
||||
--ag-muted: var(--text-muted);
|
||||
--ag-faint: var(--text-faint, var(--text-muted));
|
||||
}
|
||||
|
||||
:root .atlas-globe .ag-glass {
|
||||
backdrop-filter: blur(20px) saturate(180%);
|
||||
-webkit-backdrop-filter: blur(20px) saturate(180%);
|
||||
}
|
||||
|
||||
/*
|
||||
* TREK's liquid glass (the dashboard tiles' tokens, dashboard.css) for every
|
||||
* control over the globe: shells, the stat cards inside them, the search, chips.
|
||||
*/
|
||||
.atlas-globe {
|
||||
/* Over the night sky the dashboard's glass needs more white to still read as white. */
|
||||
--glass-bg: linear-gradient(135deg, oklch(1 0 0 / 0.92) 0%, oklch(0.99 0.006 75 / 0.82) 100%);
|
||||
--glass-border: oklch(1 0 0 / 0.75);
|
||||
--glass-shadow: 0 1px 2px oklch(0.4 0.02 60 / 0.05), 0 12px 32px -14px oklch(0.3 0.02 60 / 0.2);
|
||||
--glass-highlight: inset 0 1px 0 oklch(1 0 0 / 0.8);
|
||||
--glass-blur: blur(22px) saturate(1.7);
|
||||
--glass-card: oklch(1 0 0 / 0.7);
|
||||
}
|
||||
|
||||
.dark .atlas-globe {
|
||||
--glass-bg: linear-gradient(135deg, oklch(0.31 0 0 / 0.58) 0%, oklch(0.25 0 0 / 0.42) 100%);
|
||||
--glass-border: oklch(1 0 0 / 0.1);
|
||||
--glass-shadow: 0 1px 2px oklch(0 0 0 / 0.3), 0 12px 32px -14px oklch(0 0 0 / 0.55);
|
||||
--glass-highlight: inset 0 1px 0 oklch(1 0 0 / 0.09);
|
||||
--glass-card: oklch(1 0 0 / 0.05);
|
||||
}
|
||||
|
||||
[data-no-transparency] .atlas-globe {
|
||||
--glass-bg: var(--bg-card);
|
||||
--glass-border: var(--border-primary);
|
||||
--glass-highlight: 0 0 0 0 transparent;
|
||||
--glass-blur: none;
|
||||
--glass-card: var(--bg-tertiary, var(--bg-card));
|
||||
}
|
||||
|
||||
.atlas-globe .ag-liquid {
|
||||
background: var(--glass-bg);
|
||||
border: 1px solid var(--glass-border);
|
||||
box-shadow: var(--glass-shadow), var(--glass-highlight);
|
||||
backdrop-filter: var(--glass-blur);
|
||||
-webkit-backdrop-filter: var(--glass-blur);
|
||||
}
|
||||
|
||||
.atlas-globe .ag-liquid-card {
|
||||
background: var(--glass-card);
|
||||
border: 1px solid var(--glass-border);
|
||||
box-shadow: var(--glass-highlight);
|
||||
}
|
||||
|
||||
.atlas-globe .ag-liquid-card:is(button):hover {
|
||||
background: color-mix(in oklch, var(--glass-card), var(--text-primary) 6%);
|
||||
}
|
||||
|
||||
/* A wish with coordinates pinned on the globe: a small amber disc with a star. */
|
||||
.ag-pin {
|
||||
display: grid;
|
||||
place-items: center;
|
||||
width: 22px;
|
||||
height: 22px;
|
||||
border-radius: 999px;
|
||||
color: rgb(255 255 255);
|
||||
background: rgb(245 158 11);
|
||||
border: 1.5px solid rgb(255 255 255 / 0.9);
|
||||
box-shadow:
|
||||
0 2px 8px rgb(0 0 0 / 0.45),
|
||||
0 0 14px rgb(251 191 36 / 0.45);
|
||||
will-change: transform, opacity;
|
||||
transition: opacity 0.2s;
|
||||
}
|
||||
|
||||
.ag-pin[data-reached='1'] {
|
||||
background: rgb(20 184 166);
|
||||
box-shadow:
|
||||
0 2px 8px rgb(0 0 0 / 0.45),
|
||||
0 0 14px rgb(45 212 191 / 0.45);
|
||||
}
|
||||
|
||||
/* The ring of light behind a badge that was just reached. */
|
||||
.ag-unlock-ring {
|
||||
position: absolute;
|
||||
width: 220px;
|
||||
height: 220px;
|
||||
margin-top: -36px;
|
||||
border-radius: 999px;
|
||||
background: radial-gradient(circle, rgb(125 211 252 / 0.35) 0%, rgb(167 139 250 / 0.18) 40%, transparent 70%);
|
||||
animation: ag-unlock-pulse 1.6s ease-out infinite;
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
@keyframes ag-unlock-pulse {
|
||||
0% {
|
||||
transform: scale(0.7);
|
||||
opacity: 0.9;
|
||||
}
|
||||
100% {
|
||||
transform: scale(1.5);
|
||||
opacity: 0;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
import type { BadgeTier } from '@trek/shared';
|
||||
|
||||
/** The two tones of each tier's metal, light and deep; medal paint, not UI surfaces. */
|
||||
export const TIERS: Record<BadgeTier, [string, string]> = {
|
||||
bronze: ['#f5b06b', '#a55a1e'], // theme-lint-disable: medal metal
|
||||
silver: ['#eef2f7', '#8a97ab'], // theme-lint-disable: medal metal
|
||||
gold: ['#fde68a', '#c98a0e'], // theme-lint-disable: medal metal
|
||||
aurora: ['#5eead4', '#a78bfa'], // theme-lint-disable: medal metal
|
||||
};
|
||||
@@ -0,0 +1,184 @@
|
||||
/**
|
||||
* Country and region names over the globe. A small pool of absolutely placed
|
||||
* elements moved with transform only; the largest countries win when two
|
||||
* labels would overlap.
|
||||
*/
|
||||
import type { GlobeEngine } from './GlobeEngine';
|
||||
|
||||
export interface GlobeLabel {
|
||||
el: HTMLDivElement;
|
||||
key: string;
|
||||
}
|
||||
|
||||
interface Candidate {
|
||||
key: string;
|
||||
text: string;
|
||||
x: number;
|
||||
y: number;
|
||||
rank: number;
|
||||
region: boolean;
|
||||
fade: number;
|
||||
}
|
||||
|
||||
const MAX_LABELS = 150;
|
||||
const MAX_REGION_LABELS = 120;
|
||||
/**
|
||||
* Region names start here, well after the region fills have faded in: on a
|
||||
* phone at 14, on a wider screen, which shows far more at once, only at 18.
|
||||
*/
|
||||
const REGION_LABEL_ZOOM_PHONE = 14;
|
||||
const REGION_LABEL_ZOOM_WIDE = 18;
|
||||
/** The width below which the globe counts as on a phone, as GlobeEngine lays it out. */
|
||||
const NARROW_WIDTH = 640;
|
||||
|
||||
function minAreaFor(zoom: number): number {
|
||||
// Square degrees a country needs before its name shows at this zoom.
|
||||
return 700 / Math.pow(zoom, 2.4);
|
||||
}
|
||||
|
||||
export function placeLabels(
|
||||
host: HTMLDivElement,
|
||||
pool: GlobeLabel[],
|
||||
engine: GlobeEngine,
|
||||
labelFor: (a2: string) => string | null,
|
||||
labelRegionsOf?: (a2: string) => boolean
|
||||
): void {
|
||||
const m = engine.manifest;
|
||||
if (!m) return;
|
||||
const zoom = engine.zoom;
|
||||
const { width } = engine.vp;
|
||||
const cands: Candidate[] = [];
|
||||
|
||||
const regionsOn = zoom >= (width < NARROW_WIDTH ? REGION_LABEL_ZOOM_PHONE : REGION_LABEL_ZOOM_WIDE);
|
||||
const named = regionsOn ? regionCandidates(engine, cands) : new Set<string>();
|
||||
countryCandidates(engine, cands, named, labelFor, labelRegionsOf);
|
||||
cands.sort((a, b) => b.rank - a.rank);
|
||||
let regionCount = 0;
|
||||
|
||||
const placed: Array<[number, number, number, number]> = [];
|
||||
const chosen: Candidate[] = [];
|
||||
for (const c of cands) {
|
||||
if (chosen.length >= MAX_LABELS) break;
|
||||
if (c.region && regionCount >= MAX_REGION_LABELS) continue;
|
||||
const w = c.text.length * (c.region ? 6.2 : 6.6) + 8;
|
||||
const h = 16;
|
||||
const box: [number, number, number, number] = [c.x - w / 2, c.y - h / 2, c.x + w / 2, c.y + h / 2];
|
||||
if (placed.some((b) => box[0] < b[2] && box[2] > b[0] && box[1] < b[3] && box[3] > b[1])) continue;
|
||||
placed.push(box);
|
||||
chosen.push(c);
|
||||
if (c.region) regionCount++;
|
||||
}
|
||||
|
||||
while (pool.length < chosen.length) {
|
||||
const el = document.createElement('div');
|
||||
el.className = 'atlas-globe-label text-caption';
|
||||
host.appendChild(el);
|
||||
pool.push({ el, key: '' });
|
||||
}
|
||||
pool.forEach((l, i) => {
|
||||
const c = chosen[i];
|
||||
if (!c) {
|
||||
if (l.el.style.opacity !== '0') l.el.style.opacity = '0';
|
||||
return;
|
||||
}
|
||||
if (l.key !== c.key) {
|
||||
l.key = c.key;
|
||||
l.el.textContent = c.text;
|
||||
l.el.dataset.region = c.region ? '1' : '';
|
||||
}
|
||||
l.el.style.transform = `translate3d(${c.x.toFixed(1)}px, ${c.y.toFixed(1)}px, 0) translate(-50%, -50%)`;
|
||||
l.el.style.opacity = String(Math.max(0, Math.min(1, c.fade)));
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* From the region label zoom on, every country in view with regions names
|
||||
* them, and its own name gives way (Kansas, not "United States" above it).
|
||||
* The regions nearest the middle of the view come first, the country under the
|
||||
* middle ahead of all; the collision check keeps it from being a wall.
|
||||
* Returns the countries whose regions were named.
|
||||
*/
|
||||
function regionCandidates(engine: GlobeEngine, cands: Candidate[]): Set<string> {
|
||||
const { width, height } = engine.vp;
|
||||
const focus = centreCountry(engine);
|
||||
const named = new Set<string>();
|
||||
const cx = width / 2;
|
||||
const cy = height / 2;
|
||||
for (const [a2, idx] of engine.regionIndex) {
|
||||
for (const f of idx.features) {
|
||||
if (!f.anchor) continue;
|
||||
const p = engine.project(f.anchor[0], f.anchor[1]);
|
||||
if (p.visible < 0.1 || p.x < 0 || p.x > width || p.y < 0 || p.y > height) continue;
|
||||
named.add(a2);
|
||||
const near = 1 - Math.min(1, Math.hypot(p.x - cx, p.y - cy) / Math.hypot(cx, cy));
|
||||
cands.push({
|
||||
key: `${a2}:${f.code ?? f.name}`,
|
||||
text: f.nameEn ?? f.name ?? '',
|
||||
x: p.x,
|
||||
y: p.y,
|
||||
rank: (a2 === focus ? 2e7 : 1e7) + near * 1e6,
|
||||
region: true,
|
||||
fade: engine.regionAlpha,
|
||||
});
|
||||
}
|
||||
}
|
||||
return named;
|
||||
}
|
||||
|
||||
/** Country names, the large ones first; the user's own countries are named earlier than the rest. */
|
||||
function countryCandidates(
|
||||
engine: GlobeEngine,
|
||||
cands: Candidate[],
|
||||
named: Set<string>,
|
||||
labelFor: (a2: string) => string | null,
|
||||
labelRegionsOf?: (a2: string) => boolean
|
||||
): void {
|
||||
const m = engine.manifest;
|
||||
if (!m) return;
|
||||
const { width, height } = engine.vp;
|
||||
const minArea = minAreaFor(engine.zoom);
|
||||
const regionA = engine.regionAlpha;
|
||||
for (const c of m.countries) {
|
||||
if (!c.a2 || !c.anchor || named.has(c.a2)) continue;
|
||||
const mine = labelRegionsOf ? labelRegionsOf(c.a2) : false;
|
||||
if (c.area < minArea * (mine ? 0.3 : 1)) continue;
|
||||
const p = engine.project(c.anchor[0], c.anchor[1]);
|
||||
if (p.visible < 0.12 || p.x < -40 || p.x > width + 40 || p.y < -20 || p.y > height + 20) continue;
|
||||
const text = labelFor(c.a2);
|
||||
if (!text) continue;
|
||||
cands.push({
|
||||
key: c.a2,
|
||||
text,
|
||||
x: p.x,
|
||||
y: p.y,
|
||||
rank: c.area * (mine ? 4 : 1) * (1 - regionA * 0.7),
|
||||
region: false,
|
||||
fade: Math.min(1, p.visible * 4) * (1 - regionA * 0.55),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/** The country whose label anchor sits nearest the middle of the view. */
|
||||
function centreCountry(engine: GlobeEngine): string | null {
|
||||
const under = engine.focusCountry();
|
||||
if (under) return engine.regionIndex.has(under) ? under : null;
|
||||
// Open water in the middle (a coast, a lake): the country with regions whose
|
||||
// label point is nearest to the middle of the view.
|
||||
const m = engine.manifest;
|
||||
if (!m) return null;
|
||||
const { width, height } = engine.vp;
|
||||
let best: string | null = null;
|
||||
let bestD = Math.min(width, height) * 0.35;
|
||||
for (const a2 of engine.regionIndex.keys()) {
|
||||
const c = m.countries.find((x) => x.a2 === a2);
|
||||
if (!c?.anchor) continue;
|
||||
const p = engine.project(c.anchor[0], c.anchor[1]);
|
||||
if (p.visible <= 0) continue;
|
||||
const d = Math.hypot(p.x - width / 2, p.y - height / 2);
|
||||
if (d < bestD) {
|
||||
bestD = d;
|
||||
best = a2;
|
||||
}
|
||||
}
|
||||
return best;
|
||||
}
|
||||
@@ -0,0 +1,111 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import {
|
||||
angularDistance,
|
||||
arcSegments,
|
||||
frameParams,
|
||||
interpolateGreatCircle,
|
||||
moonPhase,
|
||||
MORPH_END,
|
||||
MORPH_START,
|
||||
morphOf,
|
||||
projectPoint,
|
||||
sunVector,
|
||||
wrapPi,
|
||||
xSqueeze,
|
||||
type GlobeViewport,
|
||||
} from './globeMath';
|
||||
|
||||
const VP: GlobeViewport = { width: 1000, height: 800, baseRadius: 300, globeY: 400, flatY: 400 };
|
||||
|
||||
describe('globeMath', () => {
|
||||
it('wraps angles into [-pi, pi)', () => {
|
||||
expect(wrapPi(0)).toBe(0);
|
||||
expect(wrapPi(Math.PI * 3)).toBeCloseTo(-Math.PI);
|
||||
expect(wrapPi(-Math.PI * 1.5)).toBeCloseTo(Math.PI / 2);
|
||||
});
|
||||
|
||||
it('is a globe below the morph and a flat map above it', () => {
|
||||
expect(morphOf(1)).toBe(0);
|
||||
expect(morphOf(MORPH_START)).toBe(0);
|
||||
expect(morphOf(MORPH_END)).toBe(1);
|
||||
const mid = morphOf((MORPH_START + MORPH_END) / 2);
|
||||
expect(mid).toBeGreaterThan(0.4);
|
||||
expect(mid).toBeLessThan(0.6);
|
||||
});
|
||||
|
||||
it('puts the centre of the camera on the screen centre, on the globe and flat', () => {
|
||||
for (const zoom of [1, 6]) {
|
||||
const f = frameParams({ lon: 10, lat: 45, zoom }, VP);
|
||||
const p = projectPoint(10, 45, f);
|
||||
expect(p.x).toBeCloseTo(500, 3);
|
||||
expect(p.y).toBeCloseTo(400, 3);
|
||||
expect(p.visible).toBeGreaterThan(0);
|
||||
}
|
||||
});
|
||||
|
||||
it('hides the far side of the globe', () => {
|
||||
const f = frameParams({ lon: 0, lat: 0, zoom: 1 }, VP);
|
||||
expect(projectPoint(180, 0, f).visible).toBeLessThan(0);
|
||||
expect(projectPoint(60, 0, f).visible).toBeGreaterThan(0);
|
||||
// An orthographic globe: 90 degrees east sits on the limb, one radius away.
|
||||
expect(projectPoint(89.9, 0, f).x).toBeCloseTo(800, 0);
|
||||
});
|
||||
|
||||
it('keeps proportions at the centre latitude once flat', () => {
|
||||
const f = frameParams({ lon: 10, lat: 50, zoom: 8 }, VP);
|
||||
const a = projectPoint(10, 50, f);
|
||||
const east = projectPoint(11, 50, f);
|
||||
const north = projectPoint(10, 51, f);
|
||||
const dx = east.x - a.x;
|
||||
const dy = a.y - north.y;
|
||||
// One degree east is cos(50 deg) of one degree north, as on the ground.
|
||||
expect(dx / dy).toBeCloseTo(Math.cos((50 * Math.PI) / 180), 2);
|
||||
expect(xSqueeze(f)).toBeCloseTo(Math.cos((50 * Math.PI) / 180), 3);
|
||||
});
|
||||
|
||||
it('does not tear a shape across the back of the globe', () => {
|
||||
const f = frameParams({ lon: 0, lat: 0, zoom: 1 }, VP);
|
||||
// Both sides of the antimeridian, unwrapped against one reference, stay apart by
|
||||
// their real distance rather than flipping to opposite screen edges.
|
||||
const a = projectPoint(179, 10, f, 179, 10);
|
||||
const b = projectPoint(-179, 10, f, 179, 10);
|
||||
expect(Math.abs(a.x - b.x)).toBeLessThan(20);
|
||||
});
|
||||
|
||||
it('measures great circles', () => {
|
||||
expect(angularDistance(0, 0, 90, 0)).toBeCloseTo(Math.PI / 2);
|
||||
const [lon, lat] = interpolateGreatCircle(0, 0, 90, 0, 0.5);
|
||||
expect(lon).toBeCloseTo(45);
|
||||
expect(lat).toBeCloseTo(0);
|
||||
});
|
||||
|
||||
it('cuts an arc into lifted, ordered segments', () => {
|
||||
const { data, count } = arcSegments([{ a: [8.57, 50.03], b: [-73.78, 40.64] }], 10);
|
||||
expect(count).toBe(10);
|
||||
// Lift is zero at both airports and highest in the middle.
|
||||
expect(data[4]).toBe(0);
|
||||
expect(data[(count - 1) * 8 + 5]).toBeCloseTo(0, 6);
|
||||
expect(data[5 * 8 + 4]).toBeGreaterThan(data[1 * 8 + 4]);
|
||||
// Progress runs from 0 to 1.
|
||||
expect(data[6]).toBe(0);
|
||||
expect(data[(count - 1) * 8 + 7]).toBe(1);
|
||||
});
|
||||
|
||||
it('points the sun at the right hemisphere through the year', () => {
|
||||
const june = sunVector(new Date(Date.UTC(2026, 5, 21, 12)));
|
||||
const december = sunVector(new Date(Date.UTC(2026, 11, 21, 12)));
|
||||
expect(Math.hypot(...june)).toBeCloseTo(1);
|
||||
expect(june[2]).toBeGreaterThan(0.38);
|
||||
expect(december[2]).toBeLessThan(-0.38);
|
||||
// Around noon UTC the sun stands near the Greenwich meridian.
|
||||
const lon = (Math.atan2(june[1], june[0]) * 180) / Math.PI;
|
||||
expect(Math.abs(lon)).toBeLessThan(10);
|
||||
});
|
||||
|
||||
it('knows the moon phase', () => {
|
||||
const full = moonPhase(new Date(Date.UTC(2026, 0, 3, 10)));
|
||||
expect(full.lit).toBeGreaterThan(0.95);
|
||||
const fresh = moonPhase(new Date(Date.UTC(2026, 0, 18, 19)));
|
||||
expect(fresh.lit).toBeLessThan(0.05);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,235 @@
|
||||
/**
|
||||
* The Atlas globe projection, in plain numbers. The vertex shaders in
|
||||
* globeShaders.ts run the same formula on the GPU; this copy places labels,
|
||||
* hit-tests the camera and is what the unit tests pin.
|
||||
*
|
||||
* One parameter `t` morphs an orthographic globe (t = 0) into an
|
||||
* equirectangular map (t = 1) without a cut: the sphere first turns so the
|
||||
* centre latitude sits on the equator by (1 - t), then the hemisphere unrolls
|
||||
* with x = sin(k·λ)/k, which is the globe at k = 1 and the flat map as k → 0.
|
||||
*/
|
||||
|
||||
export const RAD = Math.PI / 180;
|
||||
const TAU = Math.PI * 2;
|
||||
|
||||
/** Zoom where the globe starts to unroll and where it lies flat. */
|
||||
export const MORPH_START = 1.35;
|
||||
export const MORPH_END = 2.6;
|
||||
export const MIN_ZOOM = 0.85;
|
||||
export const MAX_ZOOM = 32;
|
||||
|
||||
export interface GlobeCamera {
|
||||
/** Centre longitude and latitude in degrees. */
|
||||
lon: number;
|
||||
lat: number;
|
||||
/** 1 = the whole globe fits; higher zooms in. */
|
||||
zoom: number;
|
||||
}
|
||||
|
||||
export interface GlobeViewport {
|
||||
/** Size in CSS pixels. */
|
||||
width: number;
|
||||
height: number;
|
||||
/** Globe radius at zoom 1, CSS pixels. */
|
||||
baseRadius: number;
|
||||
/** Screen position of the globe centre at t = 0 and of the map centre at t = 1. */
|
||||
globeY: number;
|
||||
flatY: number;
|
||||
}
|
||||
|
||||
export function smoothstep(a: number, b: number, x: number): number {
|
||||
const t = Math.max(0, Math.min(1, (x - a) / (b - a)));
|
||||
return t * t * (3 - 2 * t);
|
||||
}
|
||||
|
||||
export function morphOf(zoom: number): number {
|
||||
return smoothstep(MORPH_START, MORPH_END, zoom);
|
||||
}
|
||||
|
||||
export function wrapPi(a: number): number {
|
||||
return a - TAU * Math.floor((a + Math.PI) / TAU);
|
||||
}
|
||||
|
||||
export interface FrameParams {
|
||||
t: number;
|
||||
k: number;
|
||||
scale: number;
|
||||
originX: number;
|
||||
originY: number;
|
||||
centerLon: number;
|
||||
centerLat: number;
|
||||
}
|
||||
|
||||
export function frameParams(cam: GlobeCamera, vp: GlobeViewport): FrameParams {
|
||||
const t = morphOf(cam.zoom);
|
||||
return {
|
||||
t,
|
||||
k: 1 - t * 0.9995,
|
||||
scale: vp.baseRadius * cam.zoom,
|
||||
originX: vp.width / 2,
|
||||
originY: vp.globeY + (vp.flatY - vp.globeY) * t,
|
||||
centerLon: cam.lon * RAD,
|
||||
centerLat: cam.lat * RAD,
|
||||
};
|
||||
}
|
||||
|
||||
export interface ScreenPoint {
|
||||
x: number;
|
||||
y: number;
|
||||
/** Positive while the point is on the visible side; larger is further from the edge. */
|
||||
visible: number;
|
||||
/** 1 facing the viewer, 0 at the limb (globe); 1 everywhere once flat. */
|
||||
shade: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Projects a point given in degrees. `refLon/refLat` is the point the
|
||||
* longitude is unwrapped against (the polygon or segment it belongs to), so a
|
||||
* shape that crosses the back of the globe never tears across the screen.
|
||||
*/
|
||||
export function projectPoint(
|
||||
lonDeg: number,
|
||||
latDeg: number,
|
||||
f: FrameParams,
|
||||
refLonDeg = lonDeg,
|
||||
refLatDeg = latDeg
|
||||
): ScreenPoint {
|
||||
const lon = lonDeg * RAD;
|
||||
const lat = latDeg * RAD;
|
||||
const refLon = refLonDeg * RAD;
|
||||
const refLat = refLatDeg * RAD;
|
||||
const phiR = f.centerLat * (1 - f.t);
|
||||
const cphi = Math.cos(phiR);
|
||||
const sphi = Math.sin(phiR);
|
||||
|
||||
const dlr = wrapPi(refLon - f.centerLon);
|
||||
const dl = dlr + wrapPi(lon - f.centerLon - dlr);
|
||||
|
||||
const cl = Math.cos(lat);
|
||||
const px = cl * Math.sin(dl);
|
||||
const py = Math.sin(lat);
|
||||
const pz = cl * Math.cos(dl);
|
||||
const qy = py * cphi - pz * sphi;
|
||||
const qz = py * sphi + pz * cphi;
|
||||
let lam = Math.atan2(px, qz);
|
||||
const phi = Math.asin(Math.max(-1, Math.min(1, qy)));
|
||||
|
||||
const cr = Math.cos(refLat);
|
||||
const rx = cr * Math.sin(dlr);
|
||||
const rz = Math.sin(refLat) * sphi + cr * Math.cos(dlr) * cphi;
|
||||
const lamR = Math.atan2(rx, rz);
|
||||
lam = lamR + wrapPi(lam - lamR);
|
||||
|
||||
const x = (Math.sin(f.k * lam) / f.k) * (Math.cos(phi) * (1 - f.t) + f.t) * xSqueeze(f);
|
||||
const y = Math.sin(phi) * (1 - f.t) + phi * f.t;
|
||||
const c = Math.acos(Math.max(-1, Math.min(1, Math.cos(phi) * Math.cos(lam))));
|
||||
const lim = Math.min(Math.PI, (0.5 * Math.PI) / f.k);
|
||||
return {
|
||||
x: f.originX + x * f.scale,
|
||||
y: f.originY - (y - f.centerLat * f.t) * f.scale,
|
||||
visible: Math.abs(lam) <= Math.PI ? lim - c : -1,
|
||||
shade: Math.max(0, Math.cos(c)) * (1 - f.t) + f.t,
|
||||
};
|
||||
}
|
||||
|
||||
/** How much the flat map squeezes longitude: the cosine of the centre latitude. */
|
||||
export function xSqueeze(f: FrameParams): number {
|
||||
return 1 + (Math.max(0.3, Math.cos(f.centerLat)) - 1) * f.t;
|
||||
}
|
||||
|
||||
/** Great-circle distance in radians between two points given in degrees. */
|
||||
export function angularDistance(lon1: number, lat1: number, lon2: number, lat2: number): number {
|
||||
const a1 = lat1 * RAD;
|
||||
const a2 = lat2 * RAD;
|
||||
const d = (lon2 - lon1) * RAD;
|
||||
const c = Math.sin(a1) * Math.sin(a2) + Math.cos(a1) * Math.cos(a2) * Math.cos(d);
|
||||
return Math.acos(Math.max(-1, Math.min(1, c)));
|
||||
}
|
||||
|
||||
/** Point along the great circle from a to b at fraction s (degrees in, degrees out). */
|
||||
export function interpolateGreatCircle(
|
||||
lon1: number,
|
||||
lat1: number,
|
||||
lon2: number,
|
||||
lat2: number,
|
||||
s: number
|
||||
): [number, number] {
|
||||
const p1 = [
|
||||
Math.cos(lat1 * RAD) * Math.cos(lon1 * RAD),
|
||||
Math.cos(lat1 * RAD) * Math.sin(lon1 * RAD),
|
||||
Math.sin(lat1 * RAD),
|
||||
];
|
||||
const p2 = [
|
||||
Math.cos(lat2 * RAD) * Math.cos(lon2 * RAD),
|
||||
Math.cos(lat2 * RAD) * Math.sin(lon2 * RAD),
|
||||
Math.sin(lat2 * RAD),
|
||||
];
|
||||
const d = angularDistance(lon1, lat1, lon2, lat2);
|
||||
if (d < 1e-9) return [lon1, lat1];
|
||||
const a = Math.sin((1 - s) * d) / Math.sin(d);
|
||||
const b = Math.sin(s * d) / Math.sin(d);
|
||||
const x = a * p1[0] + b * p2[0];
|
||||
const y = a * p1[1] + b * p2[1];
|
||||
const z = a * p1[2] + b * p2[2];
|
||||
return [Math.atan2(y, x) / RAD, Math.atan2(z, Math.hypot(x, y)) / RAD];
|
||||
}
|
||||
|
||||
/**
|
||||
* Unit vector to the sun in earth-fixed coordinates (x towards 0°/0°, z north)
|
||||
* for a moment in time. Low-precision solar position, good to a fraction of a
|
||||
* degree, which is plenty for a day/night line.
|
||||
*/
|
||||
export function sunVector(date: Date): [number, number, number] {
|
||||
const d = date.getTime() / 86400000 - 10957.5; // days since J2000
|
||||
const g = (357.529 + 0.98560028 * d) * RAD;
|
||||
const q = 280.459 + 0.98564736 * d;
|
||||
const L = (q + 1.915 * Math.sin(g) + 0.02 * Math.sin(2 * g)) * RAD;
|
||||
const e = (23.439 - 0.00000036 * d) * RAD;
|
||||
const decl = Math.asin(Math.sin(e) * Math.sin(L));
|
||||
const ra = Math.atan2(Math.cos(e) * Math.sin(L), Math.cos(L));
|
||||
const gmst = ((280.46061837 + 360.98564736629 * d) % 360) * RAD;
|
||||
const lon = ra - gmst;
|
||||
return [Math.cos(decl) * Math.cos(lon), Math.cos(decl) * Math.sin(lon), Math.sin(decl)];
|
||||
}
|
||||
|
||||
/** Moon phase 0..1 (0 new, 0.5 full) and illuminated share, for a moment in time. */
|
||||
export function moonPhase(date: Date): { phase: number; lit: number } {
|
||||
const synodic = 29.530588853;
|
||||
const ref = Date.UTC(2000, 0, 6, 18, 14);
|
||||
const days = (date.getTime() - ref) / 86400000;
|
||||
const phase = (((days % synodic) + synodic) % synodic) / synodic;
|
||||
return { phase, lit: (1 - Math.cos(phase * 2 * Math.PI)) / 2 };
|
||||
}
|
||||
|
||||
/**
|
||||
* A flight arc as instanced segments for the line shader: per segment
|
||||
* a.lon, a.lat, b.lon, b.lat (radians), lift at a and b, and the share of the
|
||||
* arc reached at a and b (so the arc can draw itself in).
|
||||
*/
|
||||
export function arcSegments(
|
||||
routes: Array<{ a: [number, number]; b: [number, number] }>,
|
||||
steps = 48
|
||||
): { data: Float32Array; count: number } {
|
||||
const out = new Float32Array(routes.length * steps * 8);
|
||||
let o = 0;
|
||||
for (const r of routes) {
|
||||
const d = angularDistance(r.a[0], r.a[1], r.b[0], r.b[1]);
|
||||
const peak = 0.015 + d * 0.06;
|
||||
let prev = interpolateGreatCircle(r.a[0], r.a[1], r.b[0], r.b[1], 0);
|
||||
for (let i = 1; i <= steps; i++) {
|
||||
const s0 = (i - 1) / steps;
|
||||
const s1 = i / steps;
|
||||
const next = interpolateGreatCircle(r.a[0], r.a[1], r.b[0], r.b[1], s1);
|
||||
out[o++] = prev[0] * RAD;
|
||||
out[o++] = prev[1] * RAD;
|
||||
out[o++] = next[0] * RAD;
|
||||
out[o++] = next[1] * RAD;
|
||||
out[o++] = peak * Math.sin(Math.PI * s0);
|
||||
out[o++] = peak * Math.sin(Math.PI * s1);
|
||||
out[o++] = s0;
|
||||
out[o++] = s1;
|
||||
prev = next;
|
||||
}
|
||||
}
|
||||
return { data: out, count: o / 8 };
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
import type { Topology } from 'topojson-specification';
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { buildLayer, buildOcean, densify, tessellate } from './globeMesh';
|
||||
|
||||
/** Two squares sharing one edge, as TopoJSON with that edge stored once. */
|
||||
const TWO_SQUARES: Topology = {
|
||||
type: 'Topology',
|
||||
arcs: [
|
||||
[
|
||||
[10, 0],
|
||||
[10, 10],
|
||||
], // shared
|
||||
[
|
||||
[10, 10],
|
||||
[0, 10],
|
||||
[0, 0],
|
||||
[10, 0],
|
||||
],
|
||||
[
|
||||
[10, 0],
|
||||
[20, 0],
|
||||
[20, 10],
|
||||
[10, 10],
|
||||
],
|
||||
],
|
||||
objects: {
|
||||
countries: {
|
||||
type: 'GeometryCollection',
|
||||
geometries: [
|
||||
{ type: 'Polygon', id: 0, arcs: [[0, 1]] },
|
||||
{ type: 'Polygon', id: 1, arcs: [[~0, 2]] },
|
||||
],
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
describe('globeMesh', () => {
|
||||
it('splits triangles until every edge is short enough', () => {
|
||||
const coords = [0, 0, 40, 0, 0, 40];
|
||||
const tris = tessellate(coords, [0, 1, 2], 8);
|
||||
for (let i = 0; i < tris.length; i += 3) {
|
||||
const [a, b, c] = [tris[i], tris[i + 1], tris[i + 2]];
|
||||
for (const [p, q] of [
|
||||
[a, b],
|
||||
[b, c],
|
||||
[c, a],
|
||||
]) {
|
||||
expect(Math.hypot(coords[p * 2] - coords[q * 2], coords[p * 2 + 1] - coords[q * 2 + 1])).toBeLessThanOrEqual(
|
||||
8 + 1e-9
|
||||
);
|
||||
}
|
||||
}
|
||||
expect(tris.length / 3).toBeGreaterThan(10);
|
||||
});
|
||||
|
||||
it('densifies lines without moving their ends', () => {
|
||||
const d = densify(
|
||||
[
|
||||
[0, 0],
|
||||
[10, 0],
|
||||
],
|
||||
2
|
||||
);
|
||||
expect(d).toHaveLength(6);
|
||||
expect(d[0]).toEqual([0, 0]);
|
||||
expect(d[5]).toEqual([10, 0]);
|
||||
});
|
||||
|
||||
it('builds fills with the right ids and the shared border once', () => {
|
||||
const layer = buildLayer(TWO_SQUARES, 'countries', 100, (n) => 40 + n);
|
||||
const ids = new Set(Array.from(layer.fill.fid));
|
||||
expect(ids).toEqual(new Set([40, 41]));
|
||||
expect(layer.fill.index.length % 3).toBe(0);
|
||||
// The shared edge is one border segment, the outline is the coast.
|
||||
expect(layer.borders.count).toBe(1);
|
||||
expect(layer.coast.count).toBeGreaterThanOrEqual(6);
|
||||
// Everything leaves in radians.
|
||||
expect(Math.max(...Array.from(layer.fill.ll))).toBeLessThanOrEqual((20 * Math.PI) / 180 + 1e-6);
|
||||
});
|
||||
|
||||
it('covers the whole sphere with the ocean grid', () => {
|
||||
const o = buildOcean(30);
|
||||
expect(o.index.length).toBe((360 / 30) * (180 / 30) * 6);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,220 @@
|
||||
/**
|
||||
* Turns a TopoJSON level of detail into GPU-ready arrays: triangles for the
|
||||
* fills, segments for the borders. Pure, so the worker and the tests share it.
|
||||
*
|
||||
* Coordinates leave here in radians. Each fill vertex carries the centre of its
|
||||
* polygon as the reference the shader unwraps longitude against, so a polygon
|
||||
* that crosses the back of the globe stays in one piece.
|
||||
*/
|
||||
import earcut from 'earcut';
|
||||
import type { LineString, MultiLineString, MultiPolygon, Polygon, Position } from 'geojson';
|
||||
import { feature, mesh } from 'topojson-client';
|
||||
import type { GeometryCollection, Topology } from 'topojson-specification';
|
||||
|
||||
const RAD = Math.PI / 180;
|
||||
|
||||
export interface FillMesh {
|
||||
/** lon, lat per vertex (radians) */
|
||||
ll: Float32Array;
|
||||
/** reference lon, lat per vertex (radians) */
|
||||
ref: Float32Array;
|
||||
/** feature id per vertex */
|
||||
fid: Float32Array;
|
||||
index: Uint32Array;
|
||||
}
|
||||
|
||||
export interface LineMesh {
|
||||
/** per segment: a.lon, a.lat, b.lon, b.lat (radians) */
|
||||
seg: Float32Array;
|
||||
count: number;
|
||||
}
|
||||
|
||||
export interface BuiltLayer {
|
||||
fill: FillMesh;
|
||||
coast: LineMesh;
|
||||
borders: LineMesh;
|
||||
}
|
||||
|
||||
/** Splits triangles until no edge is longer than maxEdge degrees, so they bend with the sphere. */
|
||||
export function tessellate(coords: number[], tris: number[], maxEdge: number): number[] {
|
||||
const out: number[] = [];
|
||||
const mid = new Map<string, number>();
|
||||
const midpoint = (a: number, b: number): number => {
|
||||
const key = a < b ? `${a}:${b}` : `${b}:${a}`;
|
||||
let m = mid.get(key);
|
||||
if (m === undefined) {
|
||||
m = coords.length / 2;
|
||||
coords.push((coords[a * 2] + coords[b * 2]) / 2, (coords[a * 2 + 1] + coords[b * 2 + 1]) / 2);
|
||||
mid.set(key, m);
|
||||
}
|
||||
return m;
|
||||
};
|
||||
const len = (a: number, b: number): number =>
|
||||
Math.hypot(coords[a * 2] - coords[b * 2], coords[a * 2 + 1] - coords[b * 2 + 1]);
|
||||
const stack: Array<[number, number, number]> = [];
|
||||
for (let i = 0; i < tris.length; i += 3) stack.push([tris[i], tris[i + 1], tris[i + 2]]);
|
||||
while (stack.length) {
|
||||
const [a, b, c] = stack.pop() as [number, number, number];
|
||||
const ab = len(a, b);
|
||||
const bc = len(b, c);
|
||||
const ca = len(c, a);
|
||||
const m = Math.max(ab, bc, ca);
|
||||
if (m <= maxEdge) {
|
||||
out.push(a, b, c);
|
||||
} else if (m === ab) {
|
||||
const d = midpoint(a, b);
|
||||
stack.push([a, d, c], [d, b, c]);
|
||||
} else if (m === bc) {
|
||||
const d = midpoint(b, c);
|
||||
stack.push([a, b, d], [a, d, c]);
|
||||
} else {
|
||||
const d = midpoint(c, a);
|
||||
stack.push([a, b, d], [d, b, c]);
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/** Inserts points so no segment is longer than maxEdge degrees. */
|
||||
export function densify(line: Position[], maxEdge: number): Position[] {
|
||||
const out: Position[] = [line[0]];
|
||||
for (let i = 1; i < line.length; i++) {
|
||||
const [x0, y0] = line[i - 1];
|
||||
const [x1, y1] = line[i];
|
||||
const n = Math.max(1, Math.ceil(Math.hypot(x1 - x0, y1 - y0) / maxEdge));
|
||||
for (let k = 1; k <= n; k++) out.push([x0 + ((x1 - x0) * k) / n, y0 + ((y1 - y0) * k) / n]);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
function polygonsOf(g: Polygon | MultiPolygon | null): Position[][][] {
|
||||
if (!g) return [];
|
||||
return g.type === 'Polygon' ? [g.coordinates] : g.coordinates;
|
||||
}
|
||||
|
||||
function centreOf(ring: Position[]): [number, number] {
|
||||
let w = Infinity;
|
||||
let e = -Infinity;
|
||||
let s = Infinity;
|
||||
let n = -Infinity;
|
||||
for (const [x, y] of ring) {
|
||||
if (x < w) w = x;
|
||||
if (x > e) e = x;
|
||||
if (y < s) s = y;
|
||||
if (y > n) n = y;
|
||||
}
|
||||
return [(w + e) / 2, (s + n) / 2];
|
||||
}
|
||||
|
||||
class Grow {
|
||||
data: Float32Array;
|
||||
length = 0;
|
||||
constructor(n = 4096) {
|
||||
this.data = new Float32Array(n);
|
||||
}
|
||||
push(...v: number[]): void {
|
||||
if (this.length + v.length > this.data.length) {
|
||||
const next = new Float32Array(Math.max(this.data.length * 2, this.length + v.length));
|
||||
next.set(this.data);
|
||||
this.data = next;
|
||||
}
|
||||
for (const x of v) this.data[this.length++] = x;
|
||||
}
|
||||
done(): Float32Array {
|
||||
return this.data.slice(0, this.length);
|
||||
}
|
||||
}
|
||||
|
||||
function linesOf(ml: MultiLineString | LineString, maxEdge: number): LineMesh {
|
||||
const seg = new Grow();
|
||||
const parts = ml.type === 'MultiLineString' ? ml.coordinates : [ml.coordinates];
|
||||
for (const part of parts) {
|
||||
if (part.length < 2) continue;
|
||||
const d = densify(part, maxEdge);
|
||||
for (let i = 1; i < d.length; i++) seg.push(d[i - 1][0] * RAD, d[i - 1][1] * RAD, d[i][0] * RAD, d[i][1] * RAD);
|
||||
}
|
||||
const arr = seg.done();
|
||||
return { seg: arr, count: arr.length / 4 };
|
||||
}
|
||||
|
||||
/**
|
||||
* Builds one layer. `ids` maps a topology feature's numeric id to the id the
|
||||
* status texture knows it by (countries: their manifest index; regions: a block
|
||||
* reserved for that country).
|
||||
*/
|
||||
export function buildLayer(
|
||||
topo: Topology,
|
||||
objectName: string,
|
||||
maxEdge: number,
|
||||
ids: (topoId: number) => number
|
||||
): BuiltLayer {
|
||||
const obj = topo.objects[objectName] as GeometryCollection;
|
||||
const fc = feature(topo, obj);
|
||||
const ll = new Grow(1 << 16);
|
||||
const ref = new Grow(1 << 16);
|
||||
const fid = new Grow(1 << 15);
|
||||
let index: number[] = [];
|
||||
let vbase = 0;
|
||||
for (const f of fc.features) {
|
||||
const id = ids(Number(f.id));
|
||||
for (const poly of polygonsOf(f.geometry as Polygon | MultiPolygon)) {
|
||||
if (!poly.length || poly[0].length < 4) continue;
|
||||
const flat: number[] = [];
|
||||
const holes: number[] = [];
|
||||
poly.forEach((ring, ri) => {
|
||||
if (ri > 0) holes.push(flat.length / 2);
|
||||
for (let i = 0; i < ring.length - 1; i++) flat.push(ring[i][0], ring[i][1]);
|
||||
});
|
||||
const tris = tessellate(flat, earcut(flat, holes, 2), maxEdge);
|
||||
const [cx, cy] = centreOf(poly[0]);
|
||||
for (let i = 0; i < flat.length; i += 2) {
|
||||
ll.push(flat[i] * RAD, flat[i + 1] * RAD);
|
||||
ref.push(cx * RAD, cy * RAD);
|
||||
fid.push(id);
|
||||
}
|
||||
for (const t of tris) index.push(vbase + t);
|
||||
vbase += flat.length / 2;
|
||||
}
|
||||
if (index.length > 1 << 20) index = index.slice();
|
||||
}
|
||||
const coast = mesh(topo, obj, (a, b) => a === b) as MultiLineString;
|
||||
const borders = mesh(topo, obj, (a, b) => a !== b) as MultiLineString;
|
||||
return {
|
||||
fill: { ll: ll.done(), ref: ref.done(), fid: fid.done(), index: Uint32Array.from(index) },
|
||||
coast: linesOf(coast, maxEdge),
|
||||
borders: linesOf(borders, maxEdge),
|
||||
};
|
||||
}
|
||||
|
||||
/** A latitude/longitude grid over the whole sphere, the ocean the land sits on. */
|
||||
export function buildOcean(step = 6): FillMesh {
|
||||
const ll: number[] = [];
|
||||
const ref: number[] = [];
|
||||
const fid: number[] = [];
|
||||
const index: number[] = [];
|
||||
let v = 0;
|
||||
for (let lon = -180; lon < 180; lon += step) {
|
||||
for (let lat = -90; lat < 90; lat += step) {
|
||||
const cx = (lon + step / 2) * RAD;
|
||||
const cy = (lat + step / 2) * RAD;
|
||||
for (const [x, y] of [
|
||||
[lon, lat],
|
||||
[lon + step, lat],
|
||||
[lon + step, lat + step],
|
||||
[lon, lat + step],
|
||||
]) {
|
||||
ll.push(x * RAD, Math.min(90, y) * RAD);
|
||||
ref.push(cx, cy);
|
||||
fid.push(0);
|
||||
}
|
||||
index.push(v, v + 1, v + 2, v, v + 2, v + 3);
|
||||
v += 4;
|
||||
}
|
||||
}
|
||||
return {
|
||||
ll: Float32Array.from(ll),
|
||||
ref: Float32Array.from(ref),
|
||||
fid: Float32Array.from(fid),
|
||||
index: Uint32Array.from(index),
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
/// <reference lib="webworker" />
|
||||
/**
|
||||
* Builds globe layers off the main thread. The main thread fetches the
|
||||
* topology (it owns auth and the API base) and hands it over; this worker
|
||||
* triangulates and sends the arrays back as transferables.
|
||||
*/
|
||||
import type { Topology } from 'topojson-specification';
|
||||
import { buildLayer, type BuiltLayer } from './globeMesh';
|
||||
|
||||
export interface MeshRequest {
|
||||
job: number;
|
||||
topo: Topology;
|
||||
object: string;
|
||||
maxEdge: number;
|
||||
/** Status-texture id of topology feature 0; feature n gets idBase + n. */
|
||||
idBase: number;
|
||||
}
|
||||
|
||||
export interface MeshResponse {
|
||||
job: number;
|
||||
layer?: BuiltLayer;
|
||||
error?: string;
|
||||
}
|
||||
|
||||
const scope = self as unknown as DedicatedWorkerGlobalScope;
|
||||
|
||||
scope.onmessage = (e: MessageEvent<MeshRequest>) => {
|
||||
const { job, topo, object, maxEdge, idBase } = e.data;
|
||||
try {
|
||||
const layer = buildLayer(topo, object, maxEdge, (n) => idBase + n);
|
||||
const transfer = [
|
||||
layer.fill.ll.buffer,
|
||||
layer.fill.ref.buffer,
|
||||
layer.fill.fid.buffer,
|
||||
layer.fill.index.buffer,
|
||||
layer.coast.seg.buffer,
|
||||
layer.borders.seg.buffer,
|
||||
];
|
||||
scope.postMessage({ job, layer } satisfies MeshResponse, transfer);
|
||||
} catch (err) {
|
||||
scope.postMessage({ job, error: err instanceof Error ? err.message : String(err) } satisfies MeshResponse);
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,308 @@
|
||||
/**
|
||||
* GLSL for the Atlas globe. PROJECT is the GPU twin of projectPoint() in
|
||||
* globeMath.ts; a change to one belongs in the other.
|
||||
*/
|
||||
|
||||
const PROJECT = /* glsl */ `
|
||||
uniform vec2 u_center; // centre lon, lat in radians
|
||||
uniform float u_t; // 0 globe .. 1 flat map
|
||||
uniform float u_scale; // device px per radian
|
||||
uniform vec2 u_origin; // device px of the centre
|
||||
uniform vec2 u_viewport; // device px
|
||||
const float PI = 3.14159265;
|
||||
|
||||
float wrapPi(float a) { return a - 2.0 * PI * floor((a + PI) / (2.0 * PI)); }
|
||||
|
||||
// xy: screen px, z: visibility (> 0 visible), w: shade
|
||||
vec4 project(vec2 ll, vec2 ref) {
|
||||
float k = 1.0 - u_t * 0.9995;
|
||||
float phiR = u_center.y * (1.0 - u_t);
|
||||
float cphi = cos(phiR), sphi = sin(phiR);
|
||||
float dlr = wrapPi(ref.x - u_center.x);
|
||||
float dl = dlr + wrapPi(ll.x - u_center.x - dlr);
|
||||
float cl = cos(ll.y);
|
||||
vec3 p = vec3(cl * sin(dl), sin(ll.y), cl * cos(dl));
|
||||
float qy = p.y * cphi - p.z * sphi;
|
||||
float qz = p.y * sphi + p.z * cphi;
|
||||
float lam = atan(p.x, qz);
|
||||
float phi = asin(clamp(qy, -1.0, 1.0));
|
||||
float cr = cos(ref.y);
|
||||
float lamR = atan(cr * sin(dlr), sin(ref.y) * sphi + cr * cos(dlr) * cphi);
|
||||
lam = lamR + wrapPi(lam - lamR);
|
||||
// Flat, longitude is squeezed by the cosine of the centre latitude, so shapes keep
|
||||
// their proportions where the user looks instead of widening towards the poles.
|
||||
float xs = mix(1.0, max(0.3, cos(u_center.y)), u_t);
|
||||
float x = sin(k * lam) / k * (cos(phi) * (1.0 - u_t) + u_t) * xs;
|
||||
float y = sin(phi) * (1.0 - u_t) + phi * u_t;
|
||||
vec2 s = u_origin + vec2(x, -(y - u_center.y * u_t)) * u_scale;
|
||||
float c = acos(clamp(cos(phi) * cos(lam), -1.0, 1.0));
|
||||
float lim = min(PI, 0.5 * PI / k);
|
||||
float vis = abs(lam) <= PI ? lim - c : -1.0;
|
||||
float shade = max(0.0, cos(c)) * (1.0 - u_t) + u_t;
|
||||
return vec4(s, vis, shade);
|
||||
}
|
||||
|
||||
vec4 toClip(vec2 s) {
|
||||
return vec4(s.x / u_viewport.x * 2.0 - 1.0, 1.0 - s.y / u_viewport.y * 2.0, 0.0, 1.0);
|
||||
}
|
||||
`;
|
||||
|
||||
export const FILL_VS = /* glsl */ `#version 300 es
|
||||
precision highp float;
|
||||
${PROJECT}
|
||||
in vec2 a_ll; // radians
|
||||
in vec2 a_ref; // radians
|
||||
in float a_fid;
|
||||
out float v_vis;
|
||||
out float v_shade;
|
||||
out vec2 v_ll;
|
||||
flat out int v_fid;
|
||||
void main() {
|
||||
vec4 p = project(a_ll, a_ref);
|
||||
v_vis = p.z;
|
||||
v_shade = p.w;
|
||||
v_ll = a_ll;
|
||||
v_fid = int(a_fid + 0.5);
|
||||
gl_Position = toClip(p.xy);
|
||||
}
|
||||
`;
|
||||
|
||||
export const FILL_FS = /* glsl */ `#version 300 es
|
||||
precision highp float;
|
||||
precision highp usampler2D;
|
||||
in float v_vis;
|
||||
in float v_shade;
|
||||
in vec2 v_ll;
|
||||
flat in int v_fid;
|
||||
uniform sampler2D u_status; // rgb colour, a strength
|
||||
uniform sampler2D u_fx; // r hatch, g reveal order, b outline flag
|
||||
uniform int u_mode; // 0 land, 1 ocean, 2 region layer
|
||||
uniform vec3 u_land;
|
||||
uniform vec3 u_ocean;
|
||||
uniform vec3 u_oceanDeep;
|
||||
uniform float u_layerAlpha;
|
||||
uniform float u_time;
|
||||
uniform float u_revealStart;
|
||||
uniform int u_hover;
|
||||
uniform int u_selected;
|
||||
uniform int u_inkId;
|
||||
uniform vec2 u_inkLL;
|
||||
uniform float u_inkR;
|
||||
uniform float u_dpr;
|
||||
uniform float u_t;
|
||||
uniform float u_dimBase;
|
||||
uniform float u_regionFade;
|
||||
uniform vec3 u_sun; // unit vector to the sun, earth-fixed
|
||||
uniform float u_night; // how strongly the night side darkens
|
||||
uniform float u_shadeMin; // brightness at the limb (light mode keeps it high)
|
||||
uniform vec4 u_hoverTint; // rgb + strength; selection uses 1.8x the strength
|
||||
out vec4 outColor;
|
||||
|
||||
vec4 fetch(sampler2D tex, int id) { return texelFetch(tex, ivec2(id % 256, id / 256), 0); }
|
||||
|
||||
void main() {
|
||||
if (v_vis < 0.0) discard;
|
||||
float edge = smoothstep(0.0, 0.004, v_vis);
|
||||
float light = mix(u_shadeMin, 1.0, pow(v_shade, 0.65));
|
||||
vec3 nrm = vec3(cos(v_ll.y) * cos(v_ll.x), cos(v_ll.y) * sin(v_ll.x), sin(v_ll.y));
|
||||
float sunDot = dot(nrm, u_sun);
|
||||
float day = smoothstep(-0.12, 0.1, sunDot);
|
||||
float nightMul = mix(1.0 - u_night, 1.0, day);
|
||||
if (u_mode == 1) {
|
||||
vec3 col = mix(u_oceanDeep, u_ocean, pow(v_shade, 0.9));
|
||||
col *= mix(1.0 - u_night * 0.7, 1.0, day);
|
||||
// A faint glint where the sun stands over the sea.
|
||||
col += vec3(0.35, 0.45, 0.6) * pow(max(0.0, sunDot), 40.0) * 0.25 * (1.0 - u_t) * v_shade;
|
||||
outColor = vec4(col, edge);
|
||||
return;
|
||||
}
|
||||
vec4 st = fetch(u_status, v_fid);
|
||||
vec4 fx = fetch(u_fx, v_fid);
|
||||
float reveal = clamp((u_time - u_revealStart - fx.g * 1.6) / 0.45, 0.0, 1.0);
|
||||
float a = st.a * reveal;
|
||||
if (v_fid == u_inkId) {
|
||||
vec3 p1 = vec3(cos(v_ll.y) * cos(v_ll.x), cos(v_ll.y) * sin(v_ll.x), sin(v_ll.y));
|
||||
vec3 p2 = vec3(cos(u_inkLL.y) * cos(u_inkLL.x), cos(u_inkLL.y) * sin(u_inkLL.x), sin(u_inkLL.y));
|
||||
float d = acos(clamp(dot(p1, p2), -1.0, 1.0));
|
||||
a *= 1.0 - smoothstep(u_inkR - 0.01, u_inkR, d);
|
||||
}
|
||||
// A country whose regions are on screen steps back so its regions read.
|
||||
if (u_mode == 0 && fx.b > 0.5) a *= 1.0 - 0.32 * u_regionFade;
|
||||
vec3 base = u_land * (u_mode == 2 ? 1.0 : u_dimBase);
|
||||
vec3 col = mix(base, st.rgb, a);
|
||||
if (fx.r > 0.5) {
|
||||
float h = step(mod(gl_FragCoord.x + gl_FragCoord.y, 7.0 * u_dpr), 1.6 * u_dpr);
|
||||
col = mix(col, st.rgb, h * 0.9 * reveal);
|
||||
a = max(a, h * 0.9 * reveal);
|
||||
}
|
||||
if (v_fid == u_selected) col = mix(col, u_hoverTint.rgb, u_hoverTint.a * 1.8);
|
||||
else if (v_fid == u_hover) col = mix(col, u_hoverTint.rgb, u_hoverTint.a);
|
||||
col *= light;
|
||||
// Night darkens the land; what you marked keeps most of its colour, like lights on.
|
||||
col *= mix(nightMul, 1.0, a * 0.75);
|
||||
float alpha = edge;
|
||||
if (u_mode == 2) alpha *= u_layerAlpha * max(a, (v_fid == u_hover || v_fid == u_selected) ? 0.25 : 0.0);
|
||||
outColor = vec4(col, alpha);
|
||||
}
|
||||
`;
|
||||
|
||||
export const PICK_FS = /* glsl */ `#version 300 es
|
||||
precision highp float;
|
||||
in float v_vis;
|
||||
in float v_shade;
|
||||
in vec2 v_ll;
|
||||
flat in int v_fid;
|
||||
uniform int u_idBase;
|
||||
out vec4 outColor;
|
||||
void main() {
|
||||
if (v_vis < 0.0) discard;
|
||||
int id = v_fid + 1;
|
||||
outColor = vec4(float(id & 255) / 255.0, float((id >> 8) & 255) / 255.0, float((id >> 16) & 255) / 255.0, 1.0);
|
||||
}
|
||||
`;
|
||||
|
||||
/** Instanced screen-space lines: borders, coasts, outlines and flight arcs. */
|
||||
export const LINE_VS = /* glsl */ `#version 300 es
|
||||
precision highp float;
|
||||
${PROJECT}
|
||||
in vec2 a_corner; // x: 0 start .. 1 end, y: -1 .. 1 across
|
||||
in vec2 a_a; // radians
|
||||
in vec2 a_b; // radians
|
||||
in vec2 a_h; // lift of a and b (arcs), share of the radius
|
||||
in vec2 a_s; // position along the whole line, 0..1, at a and b
|
||||
uniform float u_width; // device px
|
||||
uniform float u_lift; // 1 lifts arcs above the surface
|
||||
out float v_vis;
|
||||
out float v_across;
|
||||
out float v_s;
|
||||
out float v_shade;
|
||||
vec2 lifted(vec4 p, float h) {
|
||||
vec2 d = p.xy - u_origin;
|
||||
vec2 globe = u_origin + d * (1.0 + h);
|
||||
vec2 flat2 = p.xy - vec2(0.0, h * u_scale * 0.35);
|
||||
return mix(globe, flat2, u_t);
|
||||
}
|
||||
void main() {
|
||||
vec2 mid = (a_a + a_b) * 0.5;
|
||||
if (abs(a_a.x - a_b.x) > PI) mid.x = a_a.x;
|
||||
vec4 pa = project(a_a, mid);
|
||||
vec4 pb = project(a_b, mid);
|
||||
vec2 sa = u_lift > 0.5 ? lifted(pa, a_h.x) : pa.xy;
|
||||
vec2 sb = u_lift > 0.5 ? lifted(pb, a_h.y) : pb.xy;
|
||||
vec2 dir = sb - sa;
|
||||
float len = length(dir);
|
||||
dir = len > 1e-5 ? dir / len : vec2(1.0, 0.0);
|
||||
vec2 n = vec2(-dir.y, dir.x);
|
||||
vec2 s = mix(sa, sb, a_corner.x) + n * a_corner.y * (u_width * 0.5 + 1.0) + dir * (a_corner.x * 2.0 - 1.0) * 0.5;
|
||||
float hv = mix(a_h.x, a_h.y, a_corner.x);
|
||||
v_vis = mix(pa.z, pb.z, a_corner.x) + (u_lift > 0.5 ? hv * 0.6 : 0.0);
|
||||
v_across = a_corner.y * (u_width * 0.5 + 1.0);
|
||||
v_s = mix(a_s.x, a_s.y, a_corner.x);
|
||||
v_shade = mix(pa.w, pb.w, a_corner.x);
|
||||
gl_Position = toClip(s);
|
||||
}
|
||||
`;
|
||||
|
||||
export const LINE_FS = /* glsl */ `#version 300 es
|
||||
precision highp float;
|
||||
in float v_vis;
|
||||
in float v_across;
|
||||
in float v_s;
|
||||
in float v_shade;
|
||||
uniform vec4 u_color;
|
||||
uniform float u_width;
|
||||
uniform float u_progress; // draws the line up to this share (arcs drawing in)
|
||||
uniform float u_glow;
|
||||
out vec4 outColor;
|
||||
void main() {
|
||||
if (v_vis < 0.0 || v_s > u_progress) discard;
|
||||
float d = abs(v_across);
|
||||
float core = 1.0 - smoothstep(u_width * 0.5 - 0.5, u_width * 0.5 + 0.5, d);
|
||||
float a = core;
|
||||
if (u_glow > 0.0) a = max(core, exp(-d * d / (u_width * u_width * 1.2)) * u_glow);
|
||||
float limb = smoothstep(0.0, 0.03, v_vis);
|
||||
outColor = vec4(u_color.rgb, u_color.a * a * limb * mix(0.55, 1.0, v_shade));
|
||||
}
|
||||
`;
|
||||
|
||||
/** Full-screen quad for the backdrop: deep space, stars, atmosphere. */
|
||||
export const SKY_VS = /* glsl */ `#version 300 es
|
||||
precision highp float;
|
||||
in vec2 a_pos;
|
||||
out vec2 v_uv;
|
||||
void main() {
|
||||
v_uv = a_pos * 0.5 + 0.5;
|
||||
gl_Position = vec4(a_pos, 0.0, 1.0);
|
||||
}
|
||||
`;
|
||||
|
||||
export const SKY_FS = /* glsl */ `#version 300 es
|
||||
precision highp float;
|
||||
in vec2 v_uv;
|
||||
uniform vec2 u_viewport; // device px
|
||||
uniform vec2 u_globe; // device px of the globe centre
|
||||
uniform float u_radius; // device px
|
||||
uniform float u_t;
|
||||
uniform float u_time;
|
||||
uniform vec2 u_drift; // parallax from the camera, radians
|
||||
uniform vec3 u_space0;
|
||||
uniform vec3 u_space1;
|
||||
uniform vec3 u_glow;
|
||||
uniform float u_dark;
|
||||
out vec4 outColor;
|
||||
|
||||
float hash(vec2 p) { return fract(sin(dot(p, vec2(127.1, 311.7))) * 43758.5453); }
|
||||
|
||||
float stars(vec2 px, float cell, float density, float size) {
|
||||
vec2 g = floor(px / cell);
|
||||
vec2 f = fract(px / cell);
|
||||
float h = hash(g);
|
||||
if (h > density) return 0.0;
|
||||
vec2 c = vec2(hash(g + 3.1), hash(g + 7.7)) * 0.8 + 0.1;
|
||||
float d = length(f - c) * cell;
|
||||
float tw = 0.65 + 0.35 * sin(u_time * (0.6 + h * 2.0) + h * 40.0);
|
||||
return smoothstep(size, 0.0, d) * tw * (0.4 + 0.6 * hash(g + 1.3));
|
||||
}
|
||||
|
||||
void main() {
|
||||
vec2 px = v_uv * u_viewport;
|
||||
px.y = u_viewport.y - px.y;
|
||||
float r = length(px - u_globe);
|
||||
vec3 col = mix(u_space1, u_space0, smoothstep(0.0, max(u_viewport.x, u_viewport.y) * 0.8, r));
|
||||
float sky = (1.0 - u_t * 0.9) * u_dark;
|
||||
// Milky way: a soft band across the sky, drifting with the camera.
|
||||
vec2 q = px / u_viewport.y + u_drift * vec2(0.08, 0.05);
|
||||
float band = exp(-pow((q.y - 0.35 - 0.45 * q.x + 0.25) * 3.2, 2.0));
|
||||
float dust = hash(floor(px * 0.5)) * 0.5 + 0.5;
|
||||
col += vec3(0.20, 0.24, 0.42) * band * 0.10 * sky * dust;
|
||||
vec2 sp = px + u_drift * vec2(60.0, 40.0) * u_viewport.y / 900.0;
|
||||
float s = stars(sp, 38.0, 0.20, 1.6) + stars(sp * 1.7 + 13.0, 31.0, 0.12, 1.1) * 0.7 + band * stars(sp * 2.3 + 5.0, 17.0, 0.35, 0.9) * 0.8;
|
||||
col += vec3(0.85, 0.9, 1.0) * s * sky;
|
||||
// Atmosphere: a glow hugging the globe, gone once the map lies flat.
|
||||
float atm = (1.0 - smoothstep(0.0, 0.7, u_t));
|
||||
float outside = smoothstep(u_radius * 0.985, u_radius * 1.0, r);
|
||||
float glow = exp(-max(0.0, r - u_radius) / (u_radius * 0.075)) * outside;
|
||||
col += u_glow * glow * 0.55 * atm;
|
||||
outColor = vec4(col, 1.0);
|
||||
}
|
||||
`;
|
||||
|
||||
/** A thin bright rim on the limb, drawn over the globe. */
|
||||
export const RIM_FS = /* glsl */ `#version 300 es
|
||||
precision highp float;
|
||||
in vec2 v_uv;
|
||||
uniform vec2 u_viewport;
|
||||
uniform vec2 u_globe;
|
||||
uniform float u_radius;
|
||||
uniform float u_t;
|
||||
uniform vec3 u_glow;
|
||||
out vec4 outColor;
|
||||
void main() {
|
||||
vec2 px = v_uv * u_viewport;
|
||||
px.y = u_viewport.y - px.y;
|
||||
float r = length(px - u_globe);
|
||||
float inner = smoothstep(u_radius * 0.82, u_radius, r) * (1.0 - smoothstep(u_radius, u_radius * 1.004, r));
|
||||
float a = pow(inner, 3.0) * 0.55 * (1.0 - smoothstep(0.0, 0.5, u_t));
|
||||
outColor = vec4(u_glow, a);
|
||||
}
|
||||
`;
|
||||
@@ -0,0 +1,65 @@
|
||||
/**
|
||||
* Map paint for the Atlas globe. These are rendering colours for WebGL, not UI
|
||||
* surfaces, so they are numbers here rather than appearance tokens; the accent
|
||||
* is read from the live --accent token so the globe follows the user's scheme.
|
||||
*/
|
||||
import type { GlobeTheme, Rgb } from './GlobeRenderer';
|
||||
|
||||
export function hexToRgb(hex: string): Rgb {
|
||||
const h = hex.replace('#', '').trim();
|
||||
const full =
|
||||
h.length === 3
|
||||
? h
|
||||
.split('')
|
||||
.map((c) => c + c)
|
||||
.join('')
|
||||
: h.slice(0, 6);
|
||||
const n = parseInt(full, 16);
|
||||
if (Number.isNaN(n)) return [0.5, 0.5, 0.5];
|
||||
return [((n >> 16) & 255) / 255, ((n >> 8) & 255) / 255, (n & 255) / 255];
|
||||
}
|
||||
|
||||
export function rgbToBytes(c: Rgb): [number, number, number] {
|
||||
return [Math.round(c[0] * 255), Math.round(c[1] * 255), Math.round(c[2] * 255)];
|
||||
}
|
||||
|
||||
function readCssColor(name: string, fallback: string): string {
|
||||
if (typeof document === 'undefined') return fallback;
|
||||
const v = getComputedStyle(document.documentElement).getPropertyValue(name).trim();
|
||||
return /^#[0-9a-f]{3,8}$/i.test(v) ? v : fallback;
|
||||
}
|
||||
|
||||
export function globeTheme(dark: boolean): GlobeTheme {
|
||||
const accent = hexToRgb(readCssColor('--accent', dark ? '#e4e4e7' : '#111827'));
|
||||
if (dark) {
|
||||
return {
|
||||
land: [0.15, 0.18, 0.27],
|
||||
ocean: [0.07, 0.11, 0.22],
|
||||
oceanDeep: [0.025, 0.04, 0.09],
|
||||
space0: [0.008, 0.012, 0.03],
|
||||
space1: [0.04, 0.06, 0.13],
|
||||
glow: [0.49, 0.78, 0.99],
|
||||
border: [0.03, 0.04, 0.09, 0.9],
|
||||
coast: [0.55, 0.75, 1.0, 0.16],
|
||||
regionBorder: [0.9, 0.95, 1.0, 0.32],
|
||||
selection: [1, 1, 1, 0.95],
|
||||
arc: [0.88, 0.95, 1.0, 0.95],
|
||||
dark: true,
|
||||
};
|
||||
}
|
||||
// Daylight: a clear sky, a bright sea, warm grey land and white borders.
|
||||
return {
|
||||
land: [0.985, 0.985, 0.98],
|
||||
ocean: [0.72, 0.84, 0.96],
|
||||
oceanDeep: [0.55, 0.7, 0.88],
|
||||
space0: [0.88, 0.93, 0.98],
|
||||
space1: [0.75, 0.85, 0.96],
|
||||
glow: [0.62, 0.8, 1.0],
|
||||
border: [0.72, 0.78, 0.86, 0.9],
|
||||
coast: [0.3, 0.45, 0.65, 0.3],
|
||||
regionBorder: [0.75, 0.8, 0.88, 0.75],
|
||||
selection: [accent[0], accent[1], accent[2], 0.95],
|
||||
arc: [0.16, 0.32, 0.72, 0.9],
|
||||
dark: false,
|
||||
};
|
||||
}
|
||||
@@ -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] })],
|
||||
})
|
||||
|
||||
@@ -16,7 +16,7 @@ import type { CostsSettlementResponse } from './costsModel';
|
||||
import { useCostsLedger } from './useCostsLedger';
|
||||
import { useFreezeMissingRates } from './useFreezeMissingRates';
|
||||
|
||||
// FE-BUDGET-LEDGER-001 to FE-BUDGET-LEDGER-023
|
||||
// FE-BUDGET-LEDGER-001 to FE-BUDGET-LEDGER-024
|
||||
|
||||
const fx = vi.hoisted(() => ({
|
||||
// One stable converter, the way useExchangeRates hands out a memoised one: USD is half a euro.
|
||||
@@ -183,6 +183,28 @@ describe('useCostsLedger: loading', () => {
|
||||
expect(result.current.settlement).toEqual(SETTLEMENT);
|
||||
});
|
||||
|
||||
it('FE-BUDGET-LEDGER-024: a settlement answer that lands after the ledger is gone changes no state', async () => {
|
||||
let fail: (reason: Error) => void = () => undefined;
|
||||
settlementMock().mockImplementation(
|
||||
() =>
|
||||
new Promise<CostsSettlementResponse>((_resolve, reject) => {
|
||||
fail = reject;
|
||||
})
|
||||
);
|
||||
const { unmount } = setup();
|
||||
await waitFor(() => expect(settlementMock()).toHaveBeenCalled());
|
||||
unmount();
|
||||
// React reads window.event when a state update is scheduled, and a test
|
||||
// environment that is already torn down has no window.
|
||||
vi.stubGlobal('window', undefined);
|
||||
try {
|
||||
fail(new Error('gone'));
|
||||
await new Promise((resolve) => setTimeout(resolve, 20));
|
||||
} finally {
|
||||
vi.unstubAllGlobals();
|
||||
}
|
||||
});
|
||||
|
||||
it('FE-BUDGET-LEDGER-006: hands the unconverted rows to the rate freeze, which reads the settlement again once healed', async () => {
|
||||
const { result } = setup();
|
||||
await waitFor(() => expect(result.current.settlement).not.toBeNull());
|
||||
|
||||
@@ -120,6 +120,13 @@ export function useCostsLedger({
|
||||
// Only the latest read may land: an answer for the currency picked before would
|
||||
// otherwise overwrite the one for the currency shown now.
|
||||
const latestRead = useRef(0);
|
||||
// An answer that lands after the ledger is gone has nobody to show it to.
|
||||
useEffect(() => {
|
||||
const reads = latestRead;
|
||||
return () => {
|
||||
reads.current += 1;
|
||||
};
|
||||
}, []);
|
||||
|
||||
// The browser's own figure for the display currency goes along, for the server to
|
||||
// answer in it when it cannot fetch a quote itself.
|
||||
|
||||
@@ -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) => (
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
// FE-COMP-MSAVESHEET-001 to FE-COMP-MSAVESHEET-016
|
||||
import React from 'react';
|
||||
import { afterEach, beforeEach } from 'vitest';
|
||||
import { render, screen, fireEvent, waitFor, within } from '../../../tests/helpers/render';
|
||||
import type { Collection, CollectionListResponse, CollectionMembership, CollectionSaveResult } from '@trek/shared';
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
// FE-COMP-SAVETOCOL-001 to FE-COMP-SAVETOCOL-020
|
||||
import React from 'react';
|
||||
import { afterEach, beforeEach } from 'vitest';
|
||||
import { render, screen, fireEvent, waitFor, within } from '../../../tests/helpers/render';
|
||||
import type { Collection, CollectionListResponse, CollectionMembership, CollectionSaveResult } from '@trek/shared';
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
import React from 'react';
|
||||
import { describe, it, expect, beforeEach, vi } from 'vitest';
|
||||
import { http, HttpResponse } from 'msw';
|
||||
import { render, screen, fireEvent, waitFor } from '../../../tests/helpers/render';
|
||||
|
||||
@@ -1,637 +0,0 @@
|
||||
// FE-DAWARICH-ATLASDLG-001 to FE-DAWARICH-ATLASDLG-029
|
||||
/**
|
||||
* The room where Dawarich's two Atlas questions get answered.
|
||||
*
|
||||
* Nothing in here runs on its own, and that is the whole design: the Atlas is a
|
||||
* curated list that carries tombstones precisely so a country somebody removed
|
||||
* stays removed, so every read and every write starts with a person pressing a
|
||||
* button. What is worth pinning is therefore not "does it fetch" but everything
|
||||
* arranged around the fetch.
|
||||
*
|
||||
* - **What is written, and dated when.** A wish is ticked off on the day it was
|
||||
* reached, not on today, and wishes reached on the same day travel in one
|
||||
* request. A regression here either back-dates somebody's list wrongly or
|
||||
* turns one confirmation into twenty requests.
|
||||
* - **The five states each half can be in.** Unasked, in flight, answered,
|
||||
* answered with nothing, answered with caveats. The confirm button is
|
||||
* rendered or absent rather than merely greyed out, so each state has to
|
||||
* decide whether that control exists at all, and the caveats under the list
|
||||
* are only said when there is something to say.
|
||||
* - **Refusing to write blind.** Offline is not a server error: nothing was
|
||||
* sent, and "something went wrong talking to Dawarich" for a train tunnel
|
||||
* sends people hunting for a bug in their own instance.
|
||||
* - **Both shells.** The phone gets an MSheet with its own footer, the desktop
|
||||
* a Modal; the body between them is the same tree, so a regression that
|
||||
* dropped one shell would otherwise only surface on a device.
|
||||
*/
|
||||
import React from 'react'
|
||||
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
|
||||
import { render, screen, waitFor } from '../../../tests/helpers/render'
|
||||
import { act, fireEvent } from '@testing-library/react'
|
||||
import { setForcedOffline } from '../../sync/networkMode'
|
||||
import { DawarichOfflineError } from '../../repo/dawarichRepo'
|
||||
import DawarichAtlasDialog from './DawarichAtlasDialog'
|
||||
|
||||
const toast = { success: vi.fn(), error: vi.fn(), info: vi.fn(), warning: vi.fn() }
|
||||
vi.mock('../shared/Toast', () => ({ useToast: () => toast, default: () => toast }))
|
||||
|
||||
const repo = {
|
||||
bucketScan: vi.fn(),
|
||||
atlasSuggestions: vi.fn(),
|
||||
}
|
||||
vi.mock('../../repo/dawarichRepo', () => ({
|
||||
dawarichRepo: {
|
||||
bucketScan: (...args: unknown[]) => repo.bucketScan(...args),
|
||||
atlasSuggestions: (...args: unknown[]) => repo.atlasSuggestions(...args),
|
||||
},
|
||||
DawarichOfflineError: class extends Error {},
|
||||
}))
|
||||
|
||||
const api = {
|
||||
confirmBucketVisits: vi.fn(),
|
||||
acceptAtlasCountries: vi.fn(),
|
||||
}
|
||||
vi.mock('../../api/dawarich', () => ({
|
||||
dawarichApi: {
|
||||
confirmBucketVisits: (...args: unknown[]) => api.confirmBucketVisits(...args),
|
||||
acceptAtlasCountries: (...args: unknown[]) => api.acceptAtlasCountries(...args),
|
||||
},
|
||||
}))
|
||||
|
||||
// The one thing the dialog reads about the device. A hoisted flag rather than a
|
||||
// resize: useIsPhone is matchMedia-driven and the global stub always answers false.
|
||||
const phone = vi.hoisted(() => ({ value: false }))
|
||||
vi.mock('../../mobile/useIsPhone', () => ({ useIsPhone: () => phone.value }))
|
||||
|
||||
const SCAN = {
|
||||
matches: [
|
||||
{
|
||||
itemId: 11,
|
||||
name: 'Museum Ludwig',
|
||||
match: { at: '2026-09-10T14:00:00Z', minutes: 145, distanceMeters: 49, points: 60 },
|
||||
alreadyVisited: false,
|
||||
},
|
||||
{
|
||||
itemId: 12,
|
||||
name: 'Kölner Dom',
|
||||
match: { at: '2026-09-09T14:00:00Z', minutes: 30, distanceMeters: 80, points: 12 },
|
||||
alreadyVisited: true,
|
||||
},
|
||||
{ itemId: 13, name: 'Rheinpark', match: null, alreadyVisited: false },
|
||||
],
|
||||
skippedWithoutCoordinates: 2,
|
||||
truncated: false,
|
||||
fetchedAt: '2026-09-12T10:00:00Z',
|
||||
}
|
||||
|
||||
const COUNTRIES = {
|
||||
countries: [
|
||||
{ countryCode: 'DE', sourceName: 'Germany', cities: [{ name: 'Cologne', minutes: 400, lastSeenAt: '2026-09-10T10:00:00Z' }], alreadyVisited: true },
|
||||
{ countryCode: 'NL', sourceName: 'Netherlands', cities: [{ name: 'Maastricht', minutes: 90, lastSeenAt: '2026-09-08T10:00:00Z' }], alreadyVisited: false },
|
||||
],
|
||||
unresolved: ['Freedonia'],
|
||||
fetchedAt: '2026-09-12T10:00:00Z',
|
||||
}
|
||||
|
||||
/**
|
||||
* Three wishes reached on two days. The pair sharing a timestamp is the whole
|
||||
* point of the fixture: the dialog groups by the date it is about to write, and
|
||||
* a regression that lost the grouping would send one request per wish. The
|
||||
* third one sits far enough away to be reported in kilometres rather than
|
||||
* metres, which is the other half of the row's arithmetic.
|
||||
*/
|
||||
const SAME_DAY = {
|
||||
matches: [
|
||||
{
|
||||
itemId: 21,
|
||||
name: 'Van Gogh Museum',
|
||||
match: { at: '2026-08-02T11:00:00Z', minutes: 95, distanceMeters: 30, points: 40 },
|
||||
alreadyVisited: false,
|
||||
},
|
||||
{
|
||||
itemId: 22,
|
||||
name: 'Rijksmuseum',
|
||||
match: { at: '2026-08-02T11:00:00Z', minutes: 120, distanceMeters: 55, points: 51 },
|
||||
alreadyVisited: false,
|
||||
},
|
||||
{
|
||||
itemId: 23,
|
||||
name: 'Kinderdijk',
|
||||
match: { at: '2026-07-30T09:00:00Z', minutes: 70, distanceMeters: 1400, points: 22 },
|
||||
alreadyVisited: false,
|
||||
},
|
||||
],
|
||||
skippedWithoutCoordinates: 0,
|
||||
truncated: false,
|
||||
fetchedAt: '2026-09-12T10:00:00Z',
|
||||
}
|
||||
|
||||
/**
|
||||
* A reading with nothing to apologise for: no unmatched names, one country with
|
||||
* more cities than fit beside a flag and one with none at all.
|
||||
*/
|
||||
const MORE_COUNTRIES = {
|
||||
countries: [
|
||||
{
|
||||
countryCode: 'FR',
|
||||
sourceName: 'France',
|
||||
cities: ['Paris', 'Lyon', 'Nice', 'Nantes'].map(name => ({
|
||||
name,
|
||||
minutes: 120,
|
||||
lastSeenAt: '2026-08-02T10:00:00Z',
|
||||
})),
|
||||
alreadyVisited: false,
|
||||
},
|
||||
{ countryCode: 'BE', sourceName: 'Belgium', cities: [], alreadyVisited: false },
|
||||
],
|
||||
unresolved: [],
|
||||
fetchedAt: '2026-09-12T10:00:00Z',
|
||||
}
|
||||
|
||||
/** A promise this test settles by hand, to pin down what is on screen mid-flight. */
|
||||
function deferred<T>() {
|
||||
let resolve!: (value: T) => void
|
||||
const promise = new Promise<T>(res => {
|
||||
resolve = res
|
||||
})
|
||||
return { promise, resolve }
|
||||
}
|
||||
|
||||
function open(props: Partial<React.ComponentProps<typeof DawarichAtlasDialog>> = {}) {
|
||||
return render(<DawarichAtlasDialog isOpen onClose={vi.fn()} {...props} />)
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
phone.value = false
|
||||
setForcedOffline(false)
|
||||
toast.success.mockReset()
|
||||
toast.error.mockReset()
|
||||
repo.bucketScan.mockReset().mockResolvedValue(SCAN)
|
||||
repo.atlasSuggestions.mockReset().mockResolvedValue(COUNTRIES)
|
||||
api.confirmBucketVisits.mockReset().mockResolvedValue({ updated: 1 })
|
||||
api.acceptAtlasCountries.mockReset().mockResolvedValue({ marked: 1 })
|
||||
})
|
||||
|
||||
// Force-offline is module state, not component state: left on, it would leak
|
||||
// into the next file's writes.
|
||||
afterEach(() => setForcedOffline(false))
|
||||
|
||||
describe('DawarichAtlasDialog', () => {
|
||||
it('FE-DAWARICH-ATLASDLG-001: asks nothing on its own — the scan runs when the reader says so', () => {
|
||||
open()
|
||||
expect(repo.bucketScan).not.toHaveBeenCalled()
|
||||
expect(screen.getByRole('button', { name: 'Check wishlist' })).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('FE-DAWARICH-ATLASDLG-002: offers no confirmation before there is anything to confirm', () => {
|
||||
open()
|
||||
// Hidden until a result is on screen rather than merely disabled: a greyed
|
||||
// out "Tick off 0" is a dead control asking to be understood, and `hidden`
|
||||
// keeps it out of the accessibility tree too.
|
||||
expect(screen.queryByRole('button', { name: /Tick off/ })).toBeNull()
|
||||
})
|
||||
|
||||
it('FE-DAWARICH-ATLASDLG-003: a scan lists what it found, with the distance, the time and the day', async () => {
|
||||
open()
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Check wishlist' }))
|
||||
|
||||
await waitFor(() => expect(screen.getByRole('checkbox', { name: 'Museum Ludwig' })).toBeInTheDocument())
|
||||
const row = screen.getByRole('checkbox', { name: 'Museum Ludwig' })
|
||||
expect(row.textContent).toContain('49 m away')
|
||||
expect(row.textContent).toContain('2 h 25 min')
|
||||
// A wish with no match at all is not a row — there is nothing to decide.
|
||||
expect(screen.queryByRole('checkbox', { name: 'Rheinpark' })).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('FE-DAWARICH-ATLASDLG-004: open wishes start selected, already ticked ones do not', async () => {
|
||||
open()
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Check wishlist' }))
|
||||
|
||||
await waitFor(() => expect(screen.getByRole('checkbox', { name: 'Museum Ludwig' })).toBeInTheDocument())
|
||||
expect(screen.getByRole('checkbox', { name: 'Museum Ludwig' })).toHaveAttribute('aria-checked', 'true')
|
||||
expect(screen.getByRole('checkbox', { name: 'Kölner Dom' })).toHaveAttribute('aria-checked', 'false')
|
||||
expect(screen.getByRole('checkbox', { name: 'Kölner Dom' })).toBeDisabled()
|
||||
})
|
||||
|
||||
it('FE-DAWARICH-ATLASDLG-005: unticking a row takes it out of what gets written', async () => {
|
||||
open()
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Check wishlist' }))
|
||||
await waitFor(() => expect(screen.getByRole('checkbox', { name: 'Museum Ludwig' })).toBeInTheDocument())
|
||||
|
||||
fireEvent.click(screen.getByRole('checkbox', { name: 'Museum Ludwig' }))
|
||||
|
||||
expect(screen.getByRole('button', { name: /Tick off 0/ })).toBeDisabled()
|
||||
})
|
||||
|
||||
it('FE-DAWARICH-ATLASDLG-006: confirming writes exactly the picked wishes and reports back', async () => {
|
||||
const onChanged = vi.fn()
|
||||
open({ onChanged })
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Check wishlist' }))
|
||||
await waitFor(() => expect(screen.getByRole('checkbox', { name: 'Museum Ludwig' })).toBeInTheDocument())
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: /Tick off 1/ }))
|
||||
|
||||
// With the date the stay was actually reached on — a wish from last year
|
||||
// ticked off with today's date is a wrong entry in a list people keep.
|
||||
await waitFor(() => expect(api.confirmBucketVisits).toHaveBeenCalledWith([11], '2026-09-10T14:00:00Z'))
|
||||
expect(onChanged).toHaveBeenCalled()
|
||||
// Marked in place rather than rescanned — one upstream request per wish is
|
||||
// not worth spending to tell the reader what they just did.
|
||||
await waitFor(() => expect(screen.getByRole('checkbox', { name: 'Museum Ludwig' })).toBeDisabled())
|
||||
expect(repo.bucketScan).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('FE-DAWARICH-ATLASDLG-007: the countries tab offers only what the Atlas does not already have', async () => {
|
||||
open({ initialTab: 'countries' })
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Look for countries' }))
|
||||
|
||||
await waitFor(() => expect(screen.getByRole('checkbox', { name: 'Netherlands' })).toBeInTheDocument())
|
||||
expect(screen.queryByRole('checkbox', { name: 'Germany' })).not.toBeInTheDocument()
|
||||
// A country Dawarich named but TREK could not code is said out loud, not dropped.
|
||||
expect(screen.getByText(/Freedonia/)).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('FE-DAWARICH-ATLASDLG-008: confirming countries sends their codes', async () => {
|
||||
open({ initialTab: 'countries' })
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Look for countries' }))
|
||||
await waitFor(() => expect(screen.getByRole('checkbox', { name: 'Netherlands' })).toBeInTheDocument())
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: /Add 1 country/ }))
|
||||
|
||||
await waitFor(() => expect(api.acceptAtlasCountries).toHaveBeenCalledWith(['NL']))
|
||||
})
|
||||
|
||||
it('FE-DAWARICH-ATLASDLG-009: a scan that fails says so and leaves the dialog usable', async () => {
|
||||
repo.bucketScan.mockRejectedValue({ response: { data: { error: 'Dawarich rejected the API key.' } } })
|
||||
open()
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Check wishlist' }))
|
||||
|
||||
await waitFor(() => expect(toast.error).toHaveBeenCalledWith('Dawarich rejected the API key.'))
|
||||
expect(screen.getByRole('button', { name: 'Check wishlist' })).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('FE-DAWARICH-ATLASDLG-010: while the recordings are being read there are placeholders and nothing to press', async () => {
|
||||
const scan = deferred<typeof SCAN>()
|
||||
repo.bucketScan.mockReturnValueOnce(scan.promise)
|
||||
open()
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Check wishlist' }))
|
||||
|
||||
expect(screen.getByText('Checking…')).toBeInTheDocument()
|
||||
expect(screen.queryByRole('checkbox')).toBeNull()
|
||||
// Neither control exists yet: there is nothing to confirm, and "check again"
|
||||
// before the first answer is a second request for the same thing.
|
||||
expect(screen.queryByRole('button', { name: /Tick off/ })).toBeNull()
|
||||
expect(screen.queryByRole('button', { name: 'Check again' })).toBeNull()
|
||||
|
||||
await act(async () => {
|
||||
scan.resolve(SCAN)
|
||||
})
|
||||
await waitFor(() => expect(screen.getByRole('checkbox', { name: 'Museum Ludwig' })).toBeInTheDocument())
|
||||
})
|
||||
|
||||
it('FE-DAWARICH-ATLASDLG-011: a scan that found nothing says so in a sentence and offers no confirmation', async () => {
|
||||
repo.bucketScan.mockResolvedValue({ ...SCAN, matches: [], skippedWithoutCoordinates: 0 })
|
||||
open()
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Check wishlist' }))
|
||||
|
||||
await waitFor(() =>
|
||||
expect(screen.getByText('Nothing on your wishlist turned up in your recordings.')).toBeInTheDocument(),
|
||||
)
|
||||
// Absent, not greyed out: a dead "Tick off 0" under an empty state only asks
|
||||
// to be understood.
|
||||
expect(screen.queryByRole('button', { name: /Tick off/ })).toBeNull()
|
||||
// The rule stays on screen, because it is the answer to "why did nothing
|
||||
// turn up": driving past a wish does not count as reaching it.
|
||||
expect(screen.getByText(/A wish counts as reached within 250 m and after 20 minutes/)).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('FE-DAWARICH-ATLASDLG-012: the caveats under a scan are only said when there are any', async () => {
|
||||
repo.bucketScan.mockResolvedValue({ ...SCAN, skippedWithoutCoordinates: 0, truncated: true })
|
||||
open()
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Check wishlist' }))
|
||||
|
||||
await waitFor(() =>
|
||||
expect(screen.getByText('Only the first entries were checked. Run it again for the rest.')).toBeInTheDocument(),
|
||||
)
|
||||
// Nothing was skipped this time, so nothing is said about skipping: a
|
||||
// "0 entries have no coordinates" line is noise dressed as information.
|
||||
expect(screen.queryByText(/have no coordinates/)).toBeNull()
|
||||
})
|
||||
|
||||
it('FE-DAWARICH-ATLASDLG-013: a country shows the first of its cities, one without any shows none', async () => {
|
||||
repo.atlasSuggestions.mockResolvedValue(MORE_COUNTRIES)
|
||||
open({ initialTab: 'countries' })
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Look for countries' }))
|
||||
|
||||
await waitFor(() => expect(screen.getByRole('checkbox', { name: 'France' })).toBeInTheDocument())
|
||||
const france = screen.getByRole('checkbox', { name: 'France' })
|
||||
// The badge counts all four; the line beside it names three, which is what
|
||||
// fits beside a flag at the width a phone gives this dialog.
|
||||
expect(france.textContent).toContain('4 cities')
|
||||
expect(france.textContent).toContain('Paris, Lyon, Nice')
|
||||
expect(france.textContent).not.toContain('Nantes')
|
||||
expect(screen.getByRole('checkbox', { name: 'Belgium' }).textContent).not.toContain('cities')
|
||||
// Everything matched, so the dialog does not mention matching at all.
|
||||
expect(screen.queryByText(/could not match these to a country/)).toBeNull()
|
||||
expect(screen.getByText('The last 12 months were looked at.')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('FE-DAWARICH-ATLASDLG-014: a reading with nothing new in it says so rather than showing an empty list', async () => {
|
||||
// Germany alone, and the Atlas already has it.
|
||||
repo.atlasSuggestions.mockResolvedValue({ ...COUNTRIES, countries: [COUNTRIES.countries[0]] })
|
||||
open({ initialTab: 'countries' })
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Look for countries' }))
|
||||
|
||||
await waitFor(() =>
|
||||
expect(screen.getByText('Your recordings show no countries TREK does not already have.')).toBeInTheDocument(),
|
||||
)
|
||||
expect(screen.queryByRole('button', { name: /Add \d+ countr/ })).toBeNull()
|
||||
})
|
||||
|
||||
it('FE-DAWARICH-ATLASDLG-015: wishes reached on one day travel in one request, another day in its own', async () => {
|
||||
repo.bucketScan.mockResolvedValue(SAME_DAY)
|
||||
open()
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Check wishlist' }))
|
||||
await waitFor(() => expect(screen.getByRole('checkbox', { name: 'Rijksmuseum' })).toBeInTheDocument())
|
||||
// Over a kilometre out is said in kilometres: "1400 m away" is a
|
||||
// measurement, "1.4 km away" is how far it was.
|
||||
expect(screen.getByRole('checkbox', { name: 'Kinderdijk' }).textContent).toContain('1.4 km away')
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: /Tick off 3/ }))
|
||||
|
||||
await waitFor(() => expect(api.confirmBucketVisits).toHaveBeenCalledTimes(2))
|
||||
// Grouped by date, not ordered by it: the row order inside a day is the
|
||||
// sort's business and nothing here depends on it.
|
||||
const calls = api.confirmBucketVisits.mock.calls as Array<[number[], string]>
|
||||
const byDate = new Map(calls.map(([ids, at]) => [at, [...ids].sort((a, b) => a - b)]))
|
||||
expect(byDate.get('2026-08-02T11:00:00Z')).toEqual([21, 22])
|
||||
expect(byDate.get('2026-07-30T09:00:00Z')).toEqual([23])
|
||||
// Both answers counted, not just the last one to come back.
|
||||
expect(toast.success).toHaveBeenCalledWith('2 wishes ticked off')
|
||||
})
|
||||
|
||||
it('FE-DAWARICH-ATLASDLG-016: an unticked wish is left out of the write entirely', async () => {
|
||||
repo.bucketScan.mockResolvedValue(SAME_DAY)
|
||||
open()
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Check wishlist' }))
|
||||
await waitFor(() => expect(screen.getByRole('checkbox', { name: 'Kinderdijk' })).toBeInTheDocument())
|
||||
|
||||
fireEvent.click(screen.getByRole('checkbox', { name: 'Kinderdijk' }))
|
||||
fireEvent.click(screen.getByRole('checkbox', { name: 'Rijksmuseum' }))
|
||||
fireEvent.click(screen.getByRole('button', { name: /Tick off 1/ }))
|
||||
|
||||
// One request, for one day, carrying one id. The day whose other wish was
|
||||
// dropped does not travel half-empty, and the other day does not travel at all.
|
||||
await waitFor(() => expect(api.confirmBucketVisits).toHaveBeenCalledTimes(1))
|
||||
expect(api.confirmBucketVisits).toHaveBeenCalledWith([21], '2026-08-02T11:00:00Z')
|
||||
})
|
||||
|
||||
it('FE-DAWARICH-ATLASDLG-017: a row that was unticked can be put back', async () => {
|
||||
open()
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Check wishlist' }))
|
||||
await waitFor(() => expect(screen.getByRole('checkbox', { name: 'Museum Ludwig' })).toBeInTheDocument())
|
||||
|
||||
fireEvent.click(screen.getByRole('checkbox', { name: 'Museum Ludwig' }))
|
||||
expect(screen.getByRole('checkbox', { name: 'Museum Ludwig' })).toHaveAttribute('aria-checked', 'false')
|
||||
|
||||
fireEvent.click(screen.getByRole('checkbox', { name: 'Museum Ludwig' }))
|
||||
|
||||
expect(screen.getByRole('checkbox', { name: 'Museum Ludwig' })).toHaveAttribute('aria-checked', 'true')
|
||||
expect(screen.getByRole('button', { name: /Tick off 1/ })).toBeEnabled()
|
||||
})
|
||||
|
||||
it('FE-DAWARICH-ATLASDLG-018: offline, a wish confirmation is refused before anything is sent', async () => {
|
||||
open()
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Check wishlist' }))
|
||||
await waitFor(() => expect(screen.getByRole('checkbox', { name: 'Museum Ludwig' })).toBeInTheDocument())
|
||||
|
||||
setForcedOffline(true)
|
||||
fireEvent.click(screen.getByRole('button', { name: /Tick off 1/ }))
|
||||
|
||||
expect(toast.error).toHaveBeenCalledWith(expect.stringContaining('TREK is offline right now'))
|
||||
// Not attempted at all: a confirmation fired into a dead connection hangs to
|
||||
// a timeout and then reports a server error for something no server saw.
|
||||
expect(api.confirmBucketVisits).not.toHaveBeenCalled()
|
||||
// And the selection survives, so pressing it again once there is signal is enough.
|
||||
expect(screen.getByRole('button', { name: /Tick off 1/ })).toBeEnabled()
|
||||
})
|
||||
|
||||
it('FE-DAWARICH-ATLASDLG-019: offline, a country confirmation is refused before anything is sent', async () => {
|
||||
open({ initialTab: 'countries' })
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Look for countries' }))
|
||||
await waitFor(() => expect(screen.getByRole('checkbox', { name: 'Netherlands' })).toBeInTheDocument())
|
||||
|
||||
setForcedOffline(true)
|
||||
fireEvent.click(screen.getByRole('button', { name: /Add 1 country/ }))
|
||||
|
||||
expect(toast.error).toHaveBeenCalledWith(expect.stringContaining('TREK is offline right now'))
|
||||
expect(api.acceptAtlasCountries).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('FE-DAWARICH-ATLASDLG-020: a write that failed leaves every row exactly as it was', async () => {
|
||||
// A rejection with no `{ error }` envelope at all: a socket that died
|
||||
// mid-request rather than a server that answered.
|
||||
api.confirmBucketVisits.mockRejectedValue(new Error('socket hang up'))
|
||||
const onChanged = vi.fn()
|
||||
open({ onChanged })
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Check wishlist' }))
|
||||
await waitFor(() => expect(screen.getByRole('checkbox', { name: 'Museum Ludwig' })).toBeInTheDocument())
|
||||
fireEvent.click(screen.getByRole('button', { name: /Tick off 1/ }))
|
||||
|
||||
await waitFor(() => expect(toast.error).toHaveBeenCalledWith('Something went wrong talking to Dawarich.'))
|
||||
// Nothing was marked off locally, so a second attempt still has something to
|
||||
// send, and the Atlas is not asked to re-read for a write that never landed.
|
||||
expect(screen.getByRole('checkbox', { name: 'Museum Ludwig' })).toHaveAttribute('aria-checked', 'true')
|
||||
expect(screen.getByRole('checkbox', { name: 'Museum Ludwig' })).toBeEnabled()
|
||||
expect(onChanged).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('FE-DAWARICH-ATLASDLG-021: a refusal carrying no readable reason still gets a sentence', async () => {
|
||||
// An `{ error }` that is not a string is not a message: falling through to
|
||||
// the generic sentence beats printing "[object Object]" at somebody.
|
||||
api.acceptAtlasCountries.mockRejectedValue({ response: { data: { error: { code: 502 } } } })
|
||||
open({ initialTab: 'countries' })
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Look for countries' }))
|
||||
await waitFor(() => expect(screen.getByRole('checkbox', { name: 'Netherlands' })).toBeInTheDocument())
|
||||
fireEvent.click(screen.getByRole('button', { name: /Add 1 country/ }))
|
||||
|
||||
await waitFor(() => expect(toast.error).toHaveBeenCalledWith('Something went wrong talking to Dawarich.'))
|
||||
expect(screen.getByRole('checkbox', { name: 'Netherlands' })).toHaveAttribute('aria-checked', 'true')
|
||||
})
|
||||
|
||||
it('FE-DAWARICH-ATLASDLG-022: a read that never left the device reads as a connection, not a failure', async () => {
|
||||
// The repo refuses offline reads itself, and its refusal has to survive the
|
||||
// trip through failureText as the connection message rather than as
|
||||
// "something went wrong talking to Dawarich", which points at the instance.
|
||||
repo.atlasSuggestions.mockRejectedValue(new DawarichOfflineError())
|
||||
open({ initialTab: 'countries' })
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Look for countries' }))
|
||||
|
||||
await waitFor(() =>
|
||||
expect(toast.error).toHaveBeenCalledWith(expect.stringContaining('TREK is offline right now')),
|
||||
)
|
||||
// Still unasked, so the button that asks is the one on screen.
|
||||
expect(screen.getByRole('button', { name: 'Look for countries' })).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('FE-DAWARICH-ATLASDLG-023: the other tab asks the other question, and each keeps its own answer', async () => {
|
||||
open()
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Check wishlist' }))
|
||||
await waitFor(() => expect(screen.getByRole('checkbox', { name: 'Museum Ludwig' })).toBeInTheDocument())
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: /Countries/ }))
|
||||
|
||||
// Switching tabs asks nothing on its own: a country reading costs an
|
||||
// upstream request, and nobody asked for it by moving their eyes.
|
||||
expect(repo.atlasSuggestions).not.toHaveBeenCalled()
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Look for countries' }))
|
||||
await waitFor(() => expect(screen.getByRole('checkbox', { name: 'Netherlands' })).toBeInTheDocument())
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: /Wishlist/ }))
|
||||
|
||||
// The scan is still there, and was not repeated for the return trip.
|
||||
expect(screen.getByRole('checkbox', { name: 'Museum Ludwig' })).toBeInTheDocument()
|
||||
expect(repo.bucketScan).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('FE-DAWARICH-ATLASDLG-024: "Check again" re-runs the scan and is inert while it runs', async () => {
|
||||
open()
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Check wishlist' }))
|
||||
await waitFor(() => expect(screen.getByRole('checkbox', { name: 'Museum Ludwig' })).toBeInTheDocument())
|
||||
|
||||
const second = deferred<typeof SCAN>()
|
||||
repo.bucketScan.mockReturnValueOnce(second.promise)
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Check again' }))
|
||||
|
||||
// A second press while the first is in flight would run the whole scan twice:
|
||||
// one upstream request per wish, for the same answer.
|
||||
expect(screen.getByRole('button', { name: 'Check again' })).toBeDisabled()
|
||||
|
||||
await act(async () => {
|
||||
second.resolve(SCAN)
|
||||
})
|
||||
|
||||
await waitFor(() => expect(screen.getByRole('button', { name: 'Check again' })).toBeEnabled())
|
||||
expect(repo.bucketScan).toHaveBeenCalledTimes(2)
|
||||
})
|
||||
|
||||
it('FE-DAWARICH-ATLASDLG-025: "Check again" on the countries tab re-reads the countries, not the wishes', async () => {
|
||||
open({ initialTab: 'countries' })
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Look for countries' }))
|
||||
await waitFor(() => expect(screen.getByRole('checkbox', { name: 'Netherlands' })).toBeInTheDocument())
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Check again' }))
|
||||
|
||||
await waitFor(() => expect(repo.atlasSuggestions).toHaveBeenCalledTimes(2))
|
||||
expect(repo.bucketScan).not.toHaveBeenCalled()
|
||||
// A year back from the moment it was asked, both times: the window is the
|
||||
// same question asked again, not a widening one.
|
||||
const calls = repo.atlasSuggestions.mock.calls as Array<[string, string]>
|
||||
for (const [from, to] of calls) {
|
||||
expect(Date.parse(to) - Date.parse(from)).toBe(365 * 24 * 60 * 60 * 1000)
|
||||
}
|
||||
expect(Date.parse(calls[1][0])).toBeGreaterThanOrEqual(Date.parse(calls[0][0]))
|
||||
})
|
||||
|
||||
it('FE-DAWARICH-ATLASDLG-026: on a phone it is a sheet, and the count and the confirm live in its own footer', async () => {
|
||||
phone.value = true
|
||||
const onClose = vi.fn()
|
||||
open({ onClose })
|
||||
|
||||
expect(screen.getByRole('dialog', { name: 'Dawarich' })).toBeInTheDocument()
|
||||
// The desktop modal puts the title in a heading: its absence is the tell
|
||||
// that the right shell rendered.
|
||||
expect(screen.queryByRole('heading', { name: /Dawarich/ })).toBeNull()
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Check wishlist' }))
|
||||
await waitFor(() => expect(screen.getByRole('checkbox', { name: 'Museum Ludwig' })).toBeInTheDocument())
|
||||
|
||||
expect(screen.getByText('1 selected')).toBeInTheDocument()
|
||||
fireEvent.click(screen.getByRole('button', { name: /Tick off 1/ }))
|
||||
await waitFor(() => expect(api.confirmBucketVisits).toHaveBeenCalledWith([11], '2026-09-10T14:00:00Z'))
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Close' }))
|
||||
expect(onClose).toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('FE-DAWARICH-ATLASDLG-027: a country that was just added stops being offered, and the Atlas is told', async () => {
|
||||
const onChanged = vi.fn()
|
||||
open({ initialTab: 'countries', onChanged })
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Look for countries' }))
|
||||
await waitFor(() => expect(screen.getByRole('checkbox', { name: 'Netherlands' })).toBeInTheDocument())
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: /Add 1 country/ }))
|
||||
|
||||
await waitFor(() => expect(toast.success).toHaveBeenCalledWith('1 country added'))
|
||||
// Marked in place rather than re-read: the reading costs an upstream request
|
||||
// and the only thing that changed is what the reader just pressed. The row
|
||||
// leaving the list is what says the write landed.
|
||||
await waitFor(() =>
|
||||
expect(screen.getByText('Your recordings show no countries TREK does not already have.')).toBeInTheDocument(),
|
||||
)
|
||||
expect(screen.queryByRole('checkbox', { name: 'Netherlands' })).toBeNull()
|
||||
expect(screen.queryByRole('button', { name: /Add \d+ countr/ })).toBeNull()
|
||||
expect(repo.atlasSuggestions).toHaveBeenCalledTimes(1)
|
||||
// The Atlas keeps its own map and its own counts; without this the country
|
||||
// it was just told about only appears there after a reload.
|
||||
expect(onChanged).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('FE-DAWARICH-ATLASDLG-028: a request that died without a reason at all still gets a sentence', async () => {
|
||||
// An aborted request rejects with nothing: not an Error, not a response.
|
||||
// Reaching into `.response.data` on that must not be the thing that takes
|
||||
// the dialog down, because a crash here loses the scan the reader is
|
||||
// looking at as well as the message they needed.
|
||||
repo.bucketScan.mockRejectedValue(undefined)
|
||||
open()
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Check wishlist' }))
|
||||
|
||||
await waitFor(() => expect(toast.error).toHaveBeenCalledWith('Something went wrong talking to Dawarich.'))
|
||||
expect(screen.getByRole('button', { name: 'Check wishlist' })).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('FE-DAWARICH-ATLASDLG-029: a country can be unticked and put back, and only the ticked ones are written', async () => {
|
||||
// Both offers start ticked, which is the useful default but not the answer
|
||||
// every time: a border crossed on the way to somewhere else is a country
|
||||
// Dawarich saw and the reader does not want in their Atlas. Taking one out
|
||||
// has to actually take it out of the write, and changing one's mind has to
|
||||
// put it back, because the Atlas carries tombstones and an unwanted country
|
||||
// added here is removed by hand afterwards.
|
||||
repo.atlasSuggestions.mockResolvedValue(MORE_COUNTRIES)
|
||||
open({ initialTab: 'countries' })
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Look for countries' }))
|
||||
await waitFor(() => expect(screen.getByRole('checkbox', { name: 'Belgium' })).toBeInTheDocument())
|
||||
expect(screen.getByRole('button', { name: /Add 2 countries/ })).toBeEnabled()
|
||||
|
||||
fireEvent.click(screen.getByRole('checkbox', { name: 'Belgium' }))
|
||||
expect(screen.getByRole('checkbox', { name: 'Belgium' })).toHaveAttribute('aria-checked', 'false')
|
||||
|
||||
// Out and back in again: the tick is a toggle, not a one-way door.
|
||||
fireEvent.click(screen.getByRole('checkbox', { name: 'France' }))
|
||||
expect(screen.getByRole('button', { name: /Add 0 countries/ })).toBeDisabled()
|
||||
fireEvent.click(screen.getByRole('checkbox', { name: 'France' }))
|
||||
expect(screen.getByRole('checkbox', { name: 'France' })).toHaveAttribute('aria-checked', 'true')
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: /Add 1 country/ }))
|
||||
|
||||
// Belgium was never sent, so nothing has to be undone in the Atlas after.
|
||||
await waitFor(() => expect(api.acceptAtlasCountries).toHaveBeenCalledWith(['FR']))
|
||||
await waitFor(() => expect(toast.success).toHaveBeenCalledWith('1 country added'))
|
||||
// And it is still on offer, still unticked, for the trip it does belong to.
|
||||
expect(screen.getByRole('checkbox', { name: 'Belgium' })).toHaveAttribute('aria-checked', 'false')
|
||||
})
|
||||
})
|
||||
@@ -1,575 +0,0 @@
|
||||
import React, { useId, useState } from 'react'
|
||||
import { Building2, Check, CalendarDays, Globe2, Hourglass, Info, Loader2, MapPin, RefreshCw, Star } from 'lucide-react'
|
||||
import type { DawarichAtlasSuggestions, DawarichBucketScan } from '@trek/shared'
|
||||
import { DAWARICH_BUCKET_MATCH_MIN_MINUTES, DAWARICH_BUCKET_MATCH_RADIUS_M } from '@trek/shared'
|
||||
import { useTranslation } from '../../i18n'
|
||||
import { useToast } from '../shared/Toast'
|
||||
import { Skeleton } from '../shared/Skeleton'
|
||||
import { SlidingTabs } from '../shared/SlidingTabs'
|
||||
import { DialogFooter, DialogHeader, DialogShell, NEUTRAL_TINT } from '../shared/DialogShell'
|
||||
import MSheet from '../../mobile/components/MSheet'
|
||||
import { FormSheetHeader } from '../../mobile/screens/trip/sheets/PlSheetChrome'
|
||||
import { useIsPhone } from '../../mobile/useIsPhone'
|
||||
import DawarichIcon from '../shared/DawarichIcon'
|
||||
import DawarichBadge from './DawarichBadge'
|
||||
import { dawarichApi } from '../../api/dawarich'
|
||||
import { dawarichRepo, DawarichOfflineError } from '../../repo/dawarichRepo'
|
||||
import { isEffectivelyOffline } from '../../sync/networkMode'
|
||||
import { formatDuration } from './dawarichSuggestionModel'
|
||||
import { cityLine, countryLabel, countryWindow, formatDistance, newCountries, orderedMatches } from './dawarichAtlasModel'
|
||||
|
||||
type Tab = 'wishes' | 'countries'
|
||||
|
||||
/**
|
||||
* Everything Dawarich can answer about the Atlas, in a room of its own.
|
||||
*
|
||||
* It used to be a card wedged under the wishlist, which made two different
|
||||
* questions — "which wishes did I actually reach?" and "which countries was I
|
||||
* in?" — look like one paragraph of small print. Both are offers that need
|
||||
* reading before they are accepted, and reading needs space, so they get a
|
||||
* dialog with a tab each, one selection model and one confirm button.
|
||||
*
|
||||
* Nothing here runs on its own. The Atlas is curated — it carries tombstones
|
||||
* precisely so a country somebody removed stays removed — and a background job
|
||||
* that ticked countries off would be fighting its owner.
|
||||
*/
|
||||
export default function DawarichAtlasDialog({
|
||||
isOpen,
|
||||
initialTab = 'wishes',
|
||||
onClose,
|
||||
onChanged,
|
||||
}: {
|
||||
isOpen: boolean
|
||||
/** Which question was asked to open it — the panel has a button per tab. */
|
||||
initialTab?: Tab
|
||||
onClose: () => void
|
||||
/** Called after something was written, so the Atlas can re-read itself. */
|
||||
onChanged?: () => void
|
||||
}): React.ReactElement {
|
||||
const { t, locale } = useTranslation()
|
||||
const toast = useToast()
|
||||
const phone = useIsPhone()
|
||||
const labelId = useId()
|
||||
const [tab, setTab] = useState<Tab>(initialTab)
|
||||
|
||||
const [scan, setScan] = useState<DawarichBucketScan | null>(null)
|
||||
const [scanning, setScanning] = useState(false)
|
||||
const [picked, setPicked] = useState<Set<number>>(new Set())
|
||||
|
||||
const [countries, setCountries] = useState<DawarichAtlasSuggestions | null>(null)
|
||||
const [loadingCountries, setLoadingCountries] = useState(false)
|
||||
const [pickedCountries, setPickedCountries] = useState<Set<string>>(new Set())
|
||||
// One write at a time: the button stays on screen while the request is in
|
||||
// flight, and a second press would send the same confirmation twice.
|
||||
const [writing, setWriting] = useState(false)
|
||||
|
||||
const matches = orderedMatches(scan?.matches ?? [])
|
||||
const openMatches = matches.filter(match => !match.alreadyVisited)
|
||||
const offered = newCountries(countries?.countries ?? [])
|
||||
|
||||
const runScan = async (): Promise<void> => {
|
||||
setScanning(true)
|
||||
try {
|
||||
const result = await dawarichRepo.bucketScan()
|
||||
setScan(result)
|
||||
// Everything with a match and not already ticked starts selected: the
|
||||
// common case is "yes, all of those", and unticking the odd one is less
|
||||
// work than ticking twenty.
|
||||
setPicked(new Set(result.matches.filter(m => m.match && !m.alreadyVisited).map(m => m.itemId)))
|
||||
} catch (err) {
|
||||
toast.error(failureText(err, t))
|
||||
} finally {
|
||||
setScanning(false)
|
||||
}
|
||||
}
|
||||
|
||||
const loadCountries = async (): Promise<void> => {
|
||||
setLoadingCountries(true)
|
||||
try {
|
||||
const { from, to } = countryWindow(new Date())
|
||||
const result = await dawarichRepo.atlasSuggestions(from, to)
|
||||
setCountries(result)
|
||||
setPickedCountries(new Set(newCountries(result.countries).map(c => c.countryCode)))
|
||||
} catch (err) {
|
||||
toast.error(failureText(err, t))
|
||||
} finally {
|
||||
setLoadingCountries(false)
|
||||
}
|
||||
}
|
||||
|
||||
const confirmWishes = async (): Promise<void> => {
|
||||
if (picked.size === 0 || writing) return
|
||||
// Writes are online-only: the reads are gated in the repo, and firing a
|
||||
// confirmation into a dead connection would hang to a timeout and then
|
||||
// report a server error for something the server never saw.
|
||||
if (isEffectivelyOffline()) {
|
||||
toast.error(t('dawarich.error.offline'))
|
||||
return
|
||||
}
|
||||
setWriting(true)
|
||||
try {
|
||||
// Ticked off on the day each wish was reached, not on today. The dialog is
|
||||
// holding that date for every row it is about to write, so it says it;
|
||||
// grouping by date keeps that to one request per day rather than per wish.
|
||||
const byDate = new Map<string, number[]>()
|
||||
for (const m of matches) {
|
||||
if (!picked.has(m.itemId) || !m.match) continue
|
||||
const bucket = byDate.get(m.match.at)
|
||||
if (bucket) bucket.push(m.itemId)
|
||||
else byDate.set(m.match.at, [m.itemId])
|
||||
}
|
||||
const results = await Promise.all(
|
||||
[...byDate].map(([at, ids]) => dawarichApi.confirmBucketVisits(ids, at)),
|
||||
)
|
||||
const result = { updated: results.reduce((sum, r) => sum + r.updated, 0) }
|
||||
toast.success(t('dawarich.bucket.confirmed', { count: result.updated }))
|
||||
// Marked in place rather than rescanned: the scan costs one upstream
|
||||
// request per wish, and the reader already knows what they just ticked.
|
||||
setScan(prev =>
|
||||
prev === null
|
||||
? prev
|
||||
: { ...prev, matches: prev.matches.map(m => (picked.has(m.itemId) ? { ...m, alreadyVisited: true } : m)) },
|
||||
)
|
||||
setPicked(new Set())
|
||||
onChanged?.()
|
||||
} catch (err) {
|
||||
toast.error(failureText(err, t))
|
||||
} finally {
|
||||
setWriting(false)
|
||||
}
|
||||
}
|
||||
|
||||
const confirmCountries = async (): Promise<void> => {
|
||||
if (pickedCountries.size === 0 || writing) return
|
||||
if (isEffectivelyOffline()) {
|
||||
toast.error(t('dawarich.error.offline'))
|
||||
return
|
||||
}
|
||||
setWriting(true)
|
||||
try {
|
||||
const result = await dawarichApi.acceptAtlasCountries([...pickedCountries])
|
||||
toast.success(t('dawarich.atlas.accepted', { count: result.marked }))
|
||||
setCountries(prev =>
|
||||
prev === null
|
||||
? prev
|
||||
: {
|
||||
...prev,
|
||||
countries: prev.countries.map(c =>
|
||||
pickedCountries.has(c.countryCode) ? { ...c, alreadyVisited: true } : c,
|
||||
),
|
||||
},
|
||||
)
|
||||
setPickedCountries(new Set())
|
||||
onChanged?.()
|
||||
} catch (err) {
|
||||
toast.error(failureText(err, t))
|
||||
} finally {
|
||||
setWriting(false)
|
||||
}
|
||||
}
|
||||
|
||||
const toggle = <T,>(set: Set<T>, value: T): Set<T> => {
|
||||
const next = new Set(set)
|
||||
if (next.has(value)) next.delete(value)
|
||||
else next.add(value)
|
||||
return next
|
||||
}
|
||||
|
||||
const busy = tab === 'wishes' ? scanning : loadingCountries
|
||||
const loaded = tab === 'wishes' ? scan !== null : countries !== null
|
||||
const selected = tab === 'wishes' ? picked.size : pickedCountries.size
|
||||
// Nothing was found, so there is nothing to confirm — the empty state says so
|
||||
// in a sentence, and a greyed-out "Add 0 countries" underneath it only asks to
|
||||
// be understood.
|
||||
const anything = tab === 'wishes' ? matches.length > 0 : offered.length > 0
|
||||
|
||||
// The same two questions in both shells — only the frame differs.
|
||||
const body = (
|
||||
<div className="space-y-4">
|
||||
<SlidingTabs<Tab>
|
||||
tabs={[
|
||||
{ id: 'wishes', label: t('dawarich.atlas.tab.wishes'), icon: Star, count: openMatches.length || undefined },
|
||||
{ id: 'countries', label: t('dawarich.atlas.tab.countries'), icon: Globe2, count: offered.length || undefined },
|
||||
]}
|
||||
activeTab={tab}
|
||||
onChange={setTab}
|
||||
size="sm"
|
||||
fullWidth
|
||||
/>
|
||||
|
||||
{tab === 'wishes' ? (
|
||||
<Section
|
||||
icon={Star}
|
||||
title={t('dawarich.bucket.title')}
|
||||
description={t('dawarich.bucket.description')}
|
||||
action={t('dawarich.bucket.scan')}
|
||||
busyLabel={t('dawarich.bucket.scanning')}
|
||||
busy={scanning}
|
||||
loaded={scan !== null}
|
||||
onRun={() => { void runScan() }}
|
||||
empty={matches.length === 0}
|
||||
emptyLabel={t('dawarich.bucket.noMatches')}
|
||||
notes={[
|
||||
scan && scan.skippedWithoutCoordinates > 0
|
||||
? t('dawarich.bucket.skipped', { count: scan.skippedWithoutCoordinates })
|
||||
: null,
|
||||
scan?.truncated ? t('dawarich.bucket.truncated') : null,
|
||||
t('dawarich.bucket.rule', {
|
||||
meters: DAWARICH_BUCKET_MATCH_RADIUS_M,
|
||||
count: DAWARICH_BUCKET_MATCH_MIN_MINUTES,
|
||||
}),
|
||||
]}
|
||||
>
|
||||
{matches.map(match => (
|
||||
<Row
|
||||
key={match.itemId}
|
||||
name={match.name}
|
||||
checked={picked.has(match.itemId)}
|
||||
disabled={match.alreadyVisited}
|
||||
onToggle={() => setPicked(prev => toggle(prev, match.itemId))}
|
||||
leading={
|
||||
<span className="flex h-8 w-8 flex-shrink-0 items-center justify-center rounded-lg bg-surface-secondary">
|
||||
<Star className="w-4 h-4 text-accent-on" />
|
||||
</span>
|
||||
}
|
||||
>
|
||||
{match.alreadyVisited ? (
|
||||
<DawarichBadge icon={Check} tone="success" size="sm">
|
||||
{t('dawarich.bucket.alreadyVisited')}
|
||||
</DawarichBadge>
|
||||
) : (
|
||||
<>
|
||||
<DawarichBadge icon={MapPin} size="sm">
|
||||
{formatDistance(match.match!.distanceMeters, t)}
|
||||
</DawarichBadge>
|
||||
<DawarichBadge icon={Hourglass} size="sm">
|
||||
{formatDuration(match.match!.minutes, t)}
|
||||
</DawarichBadge>
|
||||
<DawarichBadge icon={CalendarDays} size="sm">
|
||||
{new Date(match.match!.at).toLocaleDateString(locale, {
|
||||
weekday: 'short',
|
||||
day: 'numeric',
|
||||
month: 'short',
|
||||
})}
|
||||
</DawarichBadge>
|
||||
</>
|
||||
)}
|
||||
</Row>
|
||||
))}
|
||||
</Section>
|
||||
) : (
|
||||
<Section
|
||||
icon={Globe2}
|
||||
title={t('dawarich.atlas.title')}
|
||||
description={t('dawarich.atlas.description')}
|
||||
action={t('dawarich.atlas.load')}
|
||||
busyLabel={t('dawarich.atlas.loading')}
|
||||
busy={loadingCountries}
|
||||
loaded={countries !== null}
|
||||
onRun={() => { void loadCountries() }}
|
||||
empty={offered.length === 0}
|
||||
emptyLabel={t('dawarich.atlas.empty')}
|
||||
notes={[
|
||||
countries && countries.unresolved.length > 0
|
||||
? t('dawarich.atlas.unresolved', { names: countries.unresolved.join(', ') })
|
||||
: null,
|
||||
countries ? t('dawarich.atlas.window') : null,
|
||||
]}
|
||||
>
|
||||
{offered.map(country => (
|
||||
<Row
|
||||
key={country.countryCode}
|
||||
name={countryLabel(country.countryCode, country.sourceName, locale)}
|
||||
checked={pickedCountries.has(country.countryCode)}
|
||||
onToggle={() => setPickedCountries(prev => toggle(prev, country.countryCode))}
|
||||
leading={
|
||||
// The Atlas page draws its countries with the same flags, and a
|
||||
// list of country names without them looks like a spreadsheet.
|
||||
<img
|
||||
src={`https://flagcdn.com/w40/${country.countryCode.toLowerCase()}.png`}
|
||||
alt=""
|
||||
className="h-6 w-8 flex-shrink-0 rounded object-cover"
|
||||
/>
|
||||
}
|
||||
>
|
||||
{country.cities.length > 0 && (
|
||||
<>
|
||||
<DawarichBadge icon={Building2} size="sm">
|
||||
{t('dawarich.atlas.cities', { count: country.cities.length })}
|
||||
</DawarichBadge>
|
||||
<span className="min-w-0 truncate text-caption text-content-muted">
|
||||
{cityLine(country.cities)}
|
||||
</span>
|
||||
</>
|
||||
)}
|
||||
</Row>
|
||||
))}
|
||||
</Section>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
|
||||
// Rendered or not, rather than `hidden`: the attribute loses to the display
|
||||
// utility on the class list, so the button stayed on screen greyed out.
|
||||
const confirmButton = !loaded || !anything ? null : (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => { void (tab === 'wishes' ? confirmWishes() : confirmCountries()) }}
|
||||
disabled={selected === 0 || writing}
|
||||
className={
|
||||
phone
|
||||
? 'inline-flex h-[38px] items-center gap-2 rounded-full bg-m-act px-4 text-[0.8125rem] font-bold text-m-actfg disabled:opacity-40'
|
||||
: 'inline-flex items-center gap-1.5 rounded-[10px] bg-accent px-4 py-2 text-body font-medium text-accent-text hover:opacity-90 disabled:opacity-40'
|
||||
}
|
||||
>
|
||||
<Check className="w-3.5 h-3.5" />
|
||||
{tab === 'wishes'
|
||||
? t('dawarich.bucket.confirm', { count: selected })
|
||||
: t('dawarich.atlas.accept', { count: selected })}
|
||||
</button>
|
||||
)
|
||||
|
||||
const againButton = loaded ? (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => { void (tab === 'wishes' ? runScan() : loadCountries()) }}
|
||||
disabled={busy}
|
||||
className={
|
||||
phone
|
||||
? 'inline-flex h-[38px] items-center gap-2 rounded-full border border-[color:var(--m-rowbr)] bg-[color:var(--m-ic)] px-4 text-[0.8125rem] font-bold text-m-muted disabled:opacity-50'
|
||||
: 'inline-flex items-center gap-1.5 rounded-[10px] bg-surface-card px-3.5 py-2 text-body font-medium text-content shadow-sm ring-1 ring-edge-faint hover:bg-surface-secondary disabled:opacity-50'
|
||||
}
|
||||
>
|
||||
{busy ? <Loader2 className="w-3.5 h-3.5 animate-spin" /> : <RefreshCw className="w-3.5 h-3.5" />}
|
||||
{t('dawarich.again')}
|
||||
</button>
|
||||
) : null
|
||||
|
||||
// The phone shell has its own sheet, its own rounding and its own pill
|
||||
// buttons, and every other panel on it uses them.
|
||||
if (phone) {
|
||||
return (
|
||||
<MSheet open={isOpen} onClose={onClose} variant="bottom" material="glass" ariaLabel={t('dawarich.title')}>
|
||||
<div className="flex max-h-[88dvh] min-h-0 flex-col">
|
||||
<FormSheetHeader
|
||||
leading={
|
||||
<span className="flex h-10 w-10 flex-none overflow-hidden rounded-[13px]">
|
||||
<DawarichIcon size={40} />
|
||||
</span>
|
||||
}
|
||||
title={t('dawarich.title')}
|
||||
subtitle={t('dawarich.atlas.dialogSubtitle')}
|
||||
onClose={onClose}
|
||||
closeLabel={t('common.close')}
|
||||
/>
|
||||
<div className="min-h-0 flex-1 overflow-y-auto px-[18px] pb-3">{body}</div>
|
||||
<div className="flex flex-none items-center gap-2 border-t border-[color:var(--m-rowbr)] px-[18px] pb-4 pt-3">
|
||||
<span className="min-w-0 flex-1 truncate font-geist text-[0.71875rem] text-m-muted">
|
||||
{selected > 0 ? t('dawarich.selected', { count: selected }) : ''}
|
||||
</span>
|
||||
{againButton}
|
||||
{confirmButton}
|
||||
</div>
|
||||
</div>
|
||||
</MSheet>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<DialogShell
|
||||
open={isOpen}
|
||||
onClose={onClose}
|
||||
labelledBy={labelId}
|
||||
width="editor"
|
||||
// The answer replaces the pitch below the tabs, so the upper edge stays put.
|
||||
align="top"
|
||||
header={(
|
||||
<DialogHeader
|
||||
// The mark fills its tile, rounded like the phone's: a small logo in a
|
||||
// grey square reads as a placeholder.
|
||||
tile={<span className="flex h-[46px] w-[46px] flex-none overflow-hidden rounded-[14px] shadow-sm"><DawarichIcon size={46} /></span>}
|
||||
tint={NEUTRAL_TINT}
|
||||
labelId={labelId}
|
||||
onClose={onClose}
|
||||
title={t('dawarich.title')}
|
||||
sub={t('dawarich.atlas.dialogSubtitle')}
|
||||
/>
|
||||
)}
|
||||
// Before the first answer the pitch carries its own button, so there is no bar to show.
|
||||
footer={againButton || confirmButton ? (
|
||||
<DialogFooter>
|
||||
<span className="min-w-0 flex-1 truncate text-caption text-content-muted">
|
||||
{selected > 0 ? t('dawarich.selected', { count: selected }) : ''}
|
||||
</span>
|
||||
{againButton}
|
||||
{confirmButton}
|
||||
</DialogFooter>
|
||||
) : undefined}
|
||||
>
|
||||
{body}
|
||||
</DialogShell>
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* One half of the dialog: the pitch before anything has been asked, the wait
|
||||
* while it is being asked, and the answer.
|
||||
*
|
||||
* Both halves behave identically, which is the point — the two questions are
|
||||
* different, the shape of answering them is not.
|
||||
*/
|
||||
function Section({
|
||||
icon: Icon,
|
||||
title,
|
||||
description,
|
||||
action,
|
||||
busyLabel,
|
||||
busy,
|
||||
loaded,
|
||||
onRun,
|
||||
empty,
|
||||
emptyLabel,
|
||||
notes,
|
||||
children,
|
||||
}: {
|
||||
icon: React.ComponentType<{ className?: string }>
|
||||
title: string
|
||||
description: string
|
||||
action: string
|
||||
busyLabel: string
|
||||
busy: boolean
|
||||
loaded: boolean
|
||||
onRun: () => void
|
||||
empty: boolean
|
||||
emptyLabel: string
|
||||
notes: (string | null)[]
|
||||
children: React.ReactNode
|
||||
}): React.ReactElement {
|
||||
if (busy) {
|
||||
return (
|
||||
<div className="space-y-2" aria-busy>
|
||||
<p className="text-caption text-content-muted">{busyLabel}</p>
|
||||
{[0, 1, 2].map(i => (
|
||||
<div key={i} className="flex items-center gap-3 rounded-xl border border-edge p-3">
|
||||
<Skeleton width={32} height={32} radius={8} />
|
||||
<div className="flex-1 space-y-1.5">
|
||||
<Skeleton width="45%" height={13} radius={4} />
|
||||
<Skeleton width="70%" height={11} radius={4} />
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
if (!loaded) {
|
||||
return (
|
||||
<div className="flex flex-col items-center rounded-xl border border-dashed border-edge px-6 py-8 text-center">
|
||||
<span className="mb-3 flex h-12 w-12 items-center justify-center rounded-full bg-surface-secondary">
|
||||
<Icon className="w-5 h-5 text-content-secondary" />
|
||||
</span>
|
||||
<p className="text-body font-semibold text-content">{title}</p>
|
||||
<p className="mt-1.5 max-w-md text-caption text-content-muted">{description}</p>
|
||||
<button
|
||||
type="button"
|
||||
onClick={onRun}
|
||||
className="mt-4 inline-flex items-center gap-2 rounded-lg bg-accent px-4 py-2 text-caption font-semibold text-accent-text hover:bg-accent-hover"
|
||||
>
|
||||
<RefreshCw className="w-3.5 h-3.5" />
|
||||
{action}
|
||||
</button>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-3">
|
||||
{empty ? (
|
||||
<div className="rounded-xl border border-dashed border-edge px-6 py-8 text-center text-caption text-content-muted">
|
||||
{emptyLabel}
|
||||
</div>
|
||||
) : (
|
||||
<div className="space-y-1.5">{children}</div>
|
||||
)}
|
||||
{notes.filter(Boolean).length > 0 && (
|
||||
<div className="space-y-1 border-t border-edge-faint pt-2.5">
|
||||
{notes.filter(Boolean).map(note => (
|
||||
<p key={note} className="flex items-start gap-1.5 text-caption text-content-faint">
|
||||
<Info className="w-3 h-3 flex-shrink-0 mt-0.5" />
|
||||
{note}
|
||||
</p>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* A selectable answer: what it is on the left, why it is being offered
|
||||
* underneath, and a tick that says whether it will be applied.
|
||||
*
|
||||
* The whole row is the control — a 16px checkbox is a hard target on a phone,
|
||||
* and there is nothing else in the row to click.
|
||||
*/
|
||||
function Row({
|
||||
name,
|
||||
checked,
|
||||
disabled = false,
|
||||
onToggle,
|
||||
leading,
|
||||
children,
|
||||
}: {
|
||||
name: string
|
||||
checked: boolean
|
||||
disabled?: boolean
|
||||
onToggle: () => void
|
||||
leading: React.ReactNode
|
||||
children: React.ReactNode
|
||||
}): React.ReactElement {
|
||||
return (
|
||||
<button
|
||||
type="button"
|
||||
role="checkbox"
|
||||
aria-checked={checked}
|
||||
aria-label={name}
|
||||
disabled={disabled}
|
||||
onClick={onToggle}
|
||||
className={`flex w-full items-center gap-3 rounded-xl border p-2.5 text-start transition-colors ${
|
||||
checked ? 'border-accent bg-accent-subtle' : 'border-edge hover:bg-surface-hover'
|
||||
} ${disabled ? 'opacity-60' : ''}`}
|
||||
>
|
||||
<span
|
||||
aria-hidden
|
||||
className={`flex h-4 w-4 flex-shrink-0 items-center justify-center rounded ${
|
||||
checked ? 'bg-accent' : 'border-[1.5px] border-edge'
|
||||
}`}
|
||||
>
|
||||
{checked && <Check className="w-2.5 h-2.5 text-accent-text" strokeWidth={3} />}
|
||||
</span>
|
||||
{leading}
|
||||
<span className="min-w-0 flex-1">
|
||||
<span className="block truncate text-body font-medium text-content">{name}</span>
|
||||
<span className="mt-1 flex flex-wrap items-center gap-1">{children}</span>
|
||||
</span>
|
||||
</button>
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* What to tell the reader when a question could not be asked.
|
||||
*
|
||||
* Being offline is not an error the server reported — nothing was sent — and
|
||||
* "something went wrong" for a plane journey is the kind of message that sends
|
||||
* somebody looking for a bug in their Dawarich instance.
|
||||
*/
|
||||
function failureText(err: unknown, t: (key: string) => string): string {
|
||||
if (err instanceof DawarichOfflineError) return t('dawarich.error.offline')
|
||||
return errorText(err) ?? t('dawarich.error.unknown')
|
||||
}
|
||||
|
||||
/** The server's `{ error }` envelope, when there is one. */
|
||||
function errorText(err: unknown): string | null {
|
||||
const data = (err as { response?: { data?: { error?: unknown } } })?.response?.data
|
||||
return typeof data?.error === 'string' ? data.error : null
|
||||
}
|
||||
@@ -1,174 +0,0 @@
|
||||
// FE-DAWARICH-ATLASPANEL-001 to FE-DAWARICH-ATLASPANEL-007
|
||||
/**
|
||||
* Dawarich's own panel on the Atlas, beside the stats.
|
||||
*
|
||||
* The panel itself holds almost no logic, and the little it does hold is the
|
||||
* kind that is invisible until it is wrong:
|
||||
*
|
||||
* - **It has to disappear completely when the addon is off.** Not empty, not a
|
||||
* blank pane of glass in the row beside the stats: absent, so an Atlas
|
||||
* without Dawarich looks exactly as it did before the integration landed.
|
||||
* - **It has to ask the question that was pressed.** Two tiles, one dialog, one
|
||||
* `initialTab` between them. Wiring both tiles to the same tab is a bug that
|
||||
* looks like a working panel.
|
||||
* - **It mounts the dialog on open and throws it away on close**, deliberately,
|
||||
* so a second visit starts from a fresh question rather than from a scan
|
||||
* somebody ran an hour ago.
|
||||
* - **It is made of the same glass as the Atlas panel next to it.** The tint
|
||||
* and the cursor glare are hand-written rgba rather than tokens (a solid
|
||||
* surface token would punch an opaque hole in a panel floating over a blurred
|
||||
* map), so nothing but a test stops the two panels drifting apart in the
|
||||
* dark theme.
|
||||
*
|
||||
* The dialog is pinned by its own file and stands in for itself here, so the
|
||||
* panel's decisions are observable without a scan and without mocking Dawarich.
|
||||
*/
|
||||
import React from 'react'
|
||||
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
|
||||
import { fireEvent } from '@testing-library/react'
|
||||
import { render, screen } from '../../../tests/helpers/render'
|
||||
import { useAddonStore } from '../../store/addonStore'
|
||||
import DawarichAtlasSidePanel from './DawarichAtlasSidePanel'
|
||||
|
||||
vi.mock('./DawarichAtlasDialog', () => ({
|
||||
default: ({
|
||||
initialTab,
|
||||
onClose,
|
||||
onChanged,
|
||||
}: {
|
||||
initialTab: string
|
||||
onClose: () => void
|
||||
onChanged?: () => void
|
||||
}) => (
|
||||
<div data-testid="atlas-dialog">
|
||||
<span>asked: {initialTab}</span>
|
||||
<button type="button" onClick={onClose}>
|
||||
dismiss
|
||||
</button>
|
||||
<button type="button" onClick={() => onChanged?.()}>
|
||||
wrote something
|
||||
</button>
|
||||
</div>
|
||||
),
|
||||
}))
|
||||
|
||||
const ADDON = { id: 'dawarich', name: 'Dawarich', type: 'integration', icon: 'route', enabled: true }
|
||||
|
||||
/** The glass the Atlas hands down, reduced to the one property jsdom can answer for. */
|
||||
const GLASS: React.CSSProperties = { borderRadius: 20 }
|
||||
|
||||
/** Inline rgba comes back from jsdom respaced; nothing here cares about the spaces. */
|
||||
const rgba = (el: HTMLElement): string => el.style.background.replace(/\s/g, '')
|
||||
|
||||
function mount(props: Partial<React.ComponentProps<typeof DawarichAtlasSidePanel>> = {}) {
|
||||
return render(<DawarichAtlasSidePanel style={GLASS} dark {...props} />)
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
useAddonStore.setState({ addons: [ADDON], loaded: true })
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
useAddonStore.setState({ addons: [], loaded: false })
|
||||
})
|
||||
|
||||
describe('DawarichAtlasSidePanel', () => {
|
||||
it('FE-DAWARICH-ATLASPANEL-001: an Atlas without the addon gets no panel at all', () => {
|
||||
useAddonStore.setState({ addons: [{ ...ADDON, enabled: false }] })
|
||||
|
||||
const { container } = mount()
|
||||
|
||||
// Nothing rendered, rather than an empty pane of glass in the row: the
|
||||
// panel is stretched to the height of the stats beside it, so an empty one
|
||||
// would be a visible hole.
|
||||
expect(container).toBeEmptyDOMElement()
|
||||
expect(screen.queryByRole('button', { name: 'Wishlist' })).toBeNull()
|
||||
})
|
||||
|
||||
it('FE-DAWARICH-ATLASPANEL-002: with the addon on it offers two questions and asks neither', () => {
|
||||
const { container } = mount()
|
||||
|
||||
expect(screen.getByText('Dawarich')).toBeInTheDocument()
|
||||
expect(screen.getByRole('button', { name: 'Wishlist' })).toBeInTheDocument()
|
||||
expect(screen.getByRole('button', { name: 'Countries' })).toBeInTheDocument()
|
||||
// A scan costs one upstream request per wish. Nothing is asked until asked.
|
||||
expect(screen.queryByTestId('atlas-dialog')).toBeNull()
|
||||
// And it wears the glass it was handed rather than one of its own.
|
||||
expect(container.firstElementChild).toHaveStyle({ borderRadius: '20px' })
|
||||
})
|
||||
|
||||
it('FE-DAWARICH-ATLASPANEL-003: the wishlist tile opens the dialog on the wishlist, and closing puts it away', () => {
|
||||
mount()
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Wishlist' }))
|
||||
|
||||
expect(screen.getByText('asked: wishes')).toBeInTheDocument()
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: 'dismiss' }))
|
||||
|
||||
// Unmounted, not hidden: the next visit starts from a clean question rather
|
||||
// than from an answer that is an hour old.
|
||||
expect(screen.queryByTestId('atlas-dialog')).toBeNull()
|
||||
})
|
||||
|
||||
it('FE-DAWARICH-ATLASPANEL-004: the countries tile opens the same dialog on the other question', () => {
|
||||
mount()
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Countries' }))
|
||||
|
||||
expect(screen.getByText('asked: countries')).toBeInTheDocument()
|
||||
expect(screen.queryByText('asked: wishes')).toBeNull()
|
||||
})
|
||||
|
||||
it('FE-DAWARICH-ATLASPANEL-005: what the dialog wrote is reported up to the Atlas', () => {
|
||||
// The Atlas keeps its own counts and its own map. Without this the confirmed
|
||||
// countries only appear after a reload.
|
||||
const onChanged = vi.fn()
|
||||
mount({ onChanged })
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Countries' }))
|
||||
fireEvent.click(screen.getByRole('button', { name: 'wrote something' }))
|
||||
|
||||
expect(onChanged).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('FE-DAWARICH-ATLASPANEL-006: the tiles are a tint of the light the panel is made of, per theme', () => {
|
||||
const { rerender } = render(<DawarichAtlasSidePanel style={GLASS} dark={false} />)
|
||||
const wishes = screen.getByRole('button', { name: 'Wishlist' })
|
||||
|
||||
expect(rgba(wishes)).toBe('rgba(0,0,0,0.05)')
|
||||
fireEvent.mouseEnter(wishes)
|
||||
expect(rgba(wishes)).toBe('rgba(0,0,0,0.09)')
|
||||
fireEvent.mouseLeave(wishes)
|
||||
expect(rgba(wishes)).toBe('rgba(0,0,0,0.05)')
|
||||
|
||||
rerender(<DawarichAtlasSidePanel style={GLASS} dark />)
|
||||
|
||||
// Inverted on the dark map, not merely darkened: the tile is light added to
|
||||
// the glass, and a black tint on a dark blurred map is an invisible button.
|
||||
expect(rgba(screen.getByRole('button', { name: 'Wishlist' }))).toBe('rgba(255,255,255,0.07)')
|
||||
})
|
||||
|
||||
it('FE-DAWARICH-ATLASPANEL-007: the glass glare follows the cursor and goes out behind it', () => {
|
||||
const { container } = mount()
|
||||
const panel = container.firstElementChild as HTMLElement
|
||||
const [glare, borderGlare] = Array.from(panel.children) as HTMLElement[]
|
||||
|
||||
expect(glare.style.opacity).toBe('0')
|
||||
|
||||
fireEvent.mouseMove(panel, { clientX: 140, clientY: 60 })
|
||||
|
||||
// The pool of light has to sit under the pointer, not merely exist: the
|
||||
// panel's box measures as the origin here, so the cursor's own coordinates
|
||||
// are what should end up in the gradient. An effect that lit up in a fixed
|
||||
// spot would pass an opacity-only assertion and look broken on screen.
|
||||
expect(glare.style.background).toContain('at 140px 60px')
|
||||
expect(glare.style.opacity).toBe('1')
|
||||
expect(borderGlare.style.opacity).toBe('1')
|
||||
|
||||
fireEvent.mouseLeave(panel)
|
||||
|
||||
expect(glare.style.opacity).toBe('0')
|
||||
expect(borderGlare.style.opacity).toBe('0')
|
||||
})
|
||||
})
|
||||
@@ -1,133 +0,0 @@
|
||||
import React, { useState } from 'react'
|
||||
import { Globe2, Star } from 'lucide-react'
|
||||
import { useTranslation } from '../../i18n'
|
||||
import { useAddonStore } from '../../store/addonStore'
|
||||
import { Tooltip } from '../shared/Tooltip'
|
||||
import { useGlassGlare } from '../Atlas/useGlassGlare'
|
||||
import DawarichIcon from '../shared/DawarichIcon'
|
||||
import DawarichAtlasDialog from './DawarichAtlasDialog'
|
||||
|
||||
type Question = 'wishes' | 'countries'
|
||||
|
||||
/**
|
||||
* Dawarich's own panel on the Atlas, beside the stats.
|
||||
*
|
||||
* The Atlas is a map with a single glass panel floating over it, and everything
|
||||
* it offers lives in that panel. Dawarich answers two questions about the same
|
||||
* map — which wishes were actually reached, and which countries the recordings
|
||||
* say you were in — but they are *its* answers, not the Atlas's own numbers, and
|
||||
* squeezed under the wishlist they read as fine print nobody asked for.
|
||||
*
|
||||
* So it gets a panel of its own, in the same glass and stretched to the same
|
||||
* height, and the two questions are two tiles built like the stat blocks beside
|
||||
* them: a mark, then a small capitalised label. The lists they produce open in a
|
||||
* dialog — they are offers to read and confirm, and a bar over a world map is no
|
||||
* place to read anything.
|
||||
*
|
||||
* Renders nothing when the addon is off, so an Atlas without Dawarich looks
|
||||
* exactly as it did before.
|
||||
*/
|
||||
export default function DawarichAtlasSidePanel({
|
||||
style,
|
||||
dark,
|
||||
onChanged,
|
||||
}: {
|
||||
/** The glass the Atlas panels are made of, handed down so the two cannot drift. */
|
||||
style: React.CSSProperties
|
||||
dark: boolean
|
||||
/** Called after something was written, so the Atlas can re-read itself. */
|
||||
onChanged?: () => void
|
||||
}): React.ReactElement | null {
|
||||
const { t } = useTranslation()
|
||||
const addonEnabled = useAddonStore(state => state.isEnabled)
|
||||
const [asked, setAsked] = useState<Question | null>(null)
|
||||
const glare = useGlassGlare(dark)
|
||||
|
||||
if (!addonEnabled('dawarich')) return null
|
||||
|
||||
// theme-lint-disable — the panel floats on a blurred map: a solid surface
|
||||
// token would punch an opaque hole in the glass, so the tiles are a tint of
|
||||
// the same light the panel is made of.
|
||||
const tile = dark ? 'rgba(255,255,255,0.07)' : 'rgba(0,0,0,0.05)'
|
||||
const tileHover = dark ? 'rgba(255,255,255,0.13)' : 'rgba(0,0,0,0.09)'
|
||||
|
||||
const question = (id: Question, Icon: React.ComponentType<{ size?: number; strokeWidth?: number }>, label: string) => (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setAsked(id)}
|
||||
className="group flex flex-col items-center justify-center text-content-secondary hover:text-content"
|
||||
style={{
|
||||
background: tile,
|
||||
border: 'none',
|
||||
borderRadius: 14,
|
||||
cursor: 'pointer',
|
||||
fontFamily: 'inherit',
|
||||
gap: 6,
|
||||
minWidth: 74,
|
||||
padding: '10px 12px',
|
||||
transition: 'background 0.15s ease, color 0.15s ease',
|
||||
}}
|
||||
onMouseEnter={e => { e.currentTarget.style.background = tileHover }}
|
||||
onMouseLeave={e => { e.currentTarget.style.background = tile }}
|
||||
>
|
||||
<Icon size={17} strokeWidth={2} />
|
||||
<span
|
||||
className="font-bold uppercase tracking-wide whitespace-nowrap"
|
||||
style={{ fontSize: 'calc(9px * var(--fs-scale-caption, 1))' }}
|
||||
>
|
||||
{label}
|
||||
</span>
|
||||
</button>
|
||||
)
|
||||
|
||||
return (
|
||||
<>
|
||||
<div
|
||||
ref={glare.panelRef}
|
||||
onMouseMove={glare.onMouseMove}
|
||||
onMouseLeave={glare.onMouseLeave}
|
||||
className="relative hidden md:flex flex-col justify-center gap-3 overflow-hidden px-5 py-4"
|
||||
style={style}
|
||||
>
|
||||
{/* Liquid glass glare, and the border glow that follows the cursor —
|
||||
the same two layers the Atlas panel carries. */}
|
||||
<div ref={glare.glareRef} className="absolute inset-0 pointer-events-none" style={{ opacity: 0, transition: 'opacity 0.3s ease', borderRadius: 20 }} />
|
||||
<div ref={glare.borderGlareRef} className="absolute inset-0 pointer-events-none" style={{
|
||||
opacity: 0, transition: 'opacity 0.3s ease', borderRadius: 20,
|
||||
border: dark ? '1.5px solid rgba(255,255,255,0.5)' : '2px solid rgba(0,0,0,0.15)',
|
||||
}} />
|
||||
{/* The long explanation moved into the tooltip: on a panel this size it
|
||||
was three lines of grey that said what the two tiles already say. */}
|
||||
<Tooltip label={t('dawarich.atlas.trigger')} placement="top">
|
||||
<span className="relative flex items-center justify-center gap-2.5">
|
||||
<span className="flex-shrink-0 overflow-hidden rounded-[9px]">
|
||||
<DawarichIcon size={30} />
|
||||
</span>
|
||||
<span
|
||||
className="truncate font-black tracking-tight text-content"
|
||||
style={{ fontSize: 'calc(16px * var(--fs-scale-subtitle, 1))' }}
|
||||
>
|
||||
{t('dawarich.title')}
|
||||
</span>
|
||||
</span>
|
||||
</Tooltip>
|
||||
|
||||
<div className="relative flex items-stretch gap-2">
|
||||
{question('wishes', Star, t('dawarich.atlas.tab.wishes'))}
|
||||
{question('countries', Globe2, t('dawarich.atlas.tab.countries'))}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Mounted on open so every visit starts from a clean question rather than
|
||||
from a scan somebody ran an hour ago. */}
|
||||
{asked !== null && (
|
||||
<DawarichAtlasDialog
|
||||
isOpen
|
||||
initialTab={asked}
|
||||
onClose={() => setAsked(null)}
|
||||
onChanged={onChanged}
|
||||
/>
|
||||
)}
|
||||
</>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,205 @@
|
||||
import type { DawarichAtlasSuggestions, DawarichBucketScan } from '@trek/shared';
|
||||
import { DAWARICH_BUCKET_MATCH_MIN_MINUTES, DAWARICH_BUCKET_MATCH_RADIUS_M } from '@trek/shared';
|
||||
import { useState } from 'react';
|
||||
import { useTranslation } from '../../i18n';
|
||||
import { DawarichOfflineError, dawarichRepo } from '../../repo/dawarichRepo';
|
||||
import { isEffectivelyOffline } from '../../sync/networkMode';
|
||||
import { useToast } from '../shared/Toast';
|
||||
import { countryWindow, newCountries, orderedMatches } from './dawarichAtlasModel';
|
||||
|
||||
export type DawarichAtlasTab = 'wishes' | 'countries';
|
||||
|
||||
/**
|
||||
* What to tell the reader when a question could not be asked. Being offline is
|
||||
* not an error the server reported (nothing was sent), and "something went
|
||||
* wrong" for a plane journey sends somebody looking for a bug in Dawarich.
|
||||
*/
|
||||
export function dawarichFailureText(err: unknown, t: (key: string) => string): string {
|
||||
if (err instanceof DawarichOfflineError) return t('dawarich.error.offline');
|
||||
const data = (err as { response?: { data?: { error?: unknown } } })?.response?.data;
|
||||
return typeof data?.error === 'string' ? data.error : t('dawarich.error.unknown');
|
||||
}
|
||||
|
||||
function toggled<T>(set: Set<T>, value: T): Set<T> {
|
||||
const next = new Set(set);
|
||||
if (next.has(value)) next.delete(value);
|
||||
else next.add(value);
|
||||
return next;
|
||||
}
|
||||
|
||||
/**
|
||||
* The two questions Dawarich answers for the Atlas, "which wishes did I reach?"
|
||||
* and "which countries was I in?", with one selection model and one confirm:
|
||||
* the state behind the Atlas dialog and the Atlas hub's Dawarich tab alike.
|
||||
* Nothing runs on its own; the Atlas is curated, so every write is confirmed.
|
||||
*/
|
||||
export function useDawarichAtlas({
|
||||
initialTab = 'wishes',
|
||||
onChanged,
|
||||
}: { initialTab?: DawarichAtlasTab; onChanged?: () => void } = {}) {
|
||||
const { t } = useTranslation();
|
||||
const toast = useToast();
|
||||
const [tab, setTab] = useState<DawarichAtlasTab>(initialTab);
|
||||
const [scan, setScan] = useState<DawarichBucketScan | null>(null);
|
||||
const [scanning, setScanning] = useState(false);
|
||||
const [picked, setPicked] = useState<Set<number>>(new Set());
|
||||
const [countries, setCountries] = useState<DawarichAtlasSuggestions | null>(null);
|
||||
const [loadingCountries, setLoadingCountries] = useState(false);
|
||||
const [pickedCountries, setPickedCountries] = useState<Set<string>>(new Set());
|
||||
// One write at a time: a second press would send the same confirmation twice.
|
||||
const [writing, setWriting] = useState(false);
|
||||
|
||||
const matches = orderedMatches(scan?.matches ?? []);
|
||||
const openMatches = matches.filter((match) => !match.alreadyVisited);
|
||||
const offered = newCountries(countries?.countries ?? []);
|
||||
|
||||
const runScan = async (): Promise<void> => {
|
||||
setScanning(true);
|
||||
try {
|
||||
const result = await dawarichRepo.bucketScan();
|
||||
setScan(result);
|
||||
// Everything with a match starts selected: the common case is "yes, all of those".
|
||||
setPicked(new Set(result.matches.filter((m) => m.match && !m.alreadyVisited).map((m) => m.itemId)));
|
||||
} catch (err) {
|
||||
toast.error(dawarichFailureText(err, t));
|
||||
} finally {
|
||||
setScanning(false);
|
||||
}
|
||||
};
|
||||
|
||||
const loadCountries = async (): Promise<void> => {
|
||||
setLoadingCountries(true);
|
||||
try {
|
||||
const { from, to } = countryWindow(new Date());
|
||||
const result = await dawarichRepo.atlasSuggestions(from, to);
|
||||
setCountries(result);
|
||||
setPickedCountries(new Set(newCountries(result.countries).map((c) => c.countryCode)));
|
||||
} catch (err) {
|
||||
toast.error(dawarichFailureText(err, t));
|
||||
} finally {
|
||||
setLoadingCountries(false);
|
||||
}
|
||||
};
|
||||
|
||||
const confirmWishes = async (): Promise<void> => {
|
||||
if (picked.size === 0 || writing) return;
|
||||
// Writes are online-only: firing one into a dead connection would hang to a
|
||||
// timeout and then report a server error for something the server never saw.
|
||||
if (isEffectivelyOffline()) {
|
||||
toast.error(t('dawarich.error.offline'));
|
||||
return;
|
||||
}
|
||||
setWriting(true);
|
||||
try {
|
||||
// Ticked off on the day each wish was reached, one request per day.
|
||||
const byDate = new Map<string, number[]>();
|
||||
for (const m of matches) {
|
||||
if (!picked.has(m.itemId) || !m.match) continue;
|
||||
const ids = byDate.get(m.match.at);
|
||||
if (ids) ids.push(m.itemId);
|
||||
else byDate.set(m.match.at, [m.itemId]);
|
||||
}
|
||||
const results = await Promise.all([...byDate].map(([at, ids]) => dawarichRepo.confirmBucketVisits(ids, at)));
|
||||
toast.success(t('dawarich.bucket.confirmed', { count: results.reduce((sum, r) => sum + r.updated, 0) }));
|
||||
setScan((prev) =>
|
||||
prev === null
|
||||
? prev
|
||||
: { ...prev, matches: prev.matches.map((m) => (picked.has(m.itemId) ? { ...m, alreadyVisited: true } : m)) }
|
||||
);
|
||||
setPicked(new Set());
|
||||
onChanged?.();
|
||||
} catch (err) {
|
||||
toast.error(dawarichFailureText(err, t));
|
||||
} finally {
|
||||
setWriting(false);
|
||||
}
|
||||
};
|
||||
|
||||
const confirmCountries = async (): Promise<void> => {
|
||||
if (pickedCountries.size === 0 || writing) return;
|
||||
if (isEffectivelyOffline()) {
|
||||
toast.error(t('dawarich.error.offline'));
|
||||
return;
|
||||
}
|
||||
setWriting(true);
|
||||
try {
|
||||
const result = await dawarichRepo.acceptAtlasCountries([...pickedCountries]);
|
||||
toast.success(t('dawarich.atlas.accepted', { count: result.marked }));
|
||||
setCountries((prev) =>
|
||||
prev === null
|
||||
? prev
|
||||
: {
|
||||
...prev,
|
||||
countries: prev.countries.map((c) =>
|
||||
pickedCountries.has(c.countryCode) ? { ...c, alreadyVisited: true } : c
|
||||
),
|
||||
}
|
||||
);
|
||||
setPickedCountries(new Set());
|
||||
onChanged?.();
|
||||
} catch (err) {
|
||||
toast.error(dawarichFailureText(err, t));
|
||||
} finally {
|
||||
setWriting(false);
|
||||
}
|
||||
};
|
||||
|
||||
const busy = tab === 'wishes' ? scanning : loadingCountries;
|
||||
const loaded = tab === 'wishes' ? scan !== null : countries !== null;
|
||||
const selected = tab === 'wishes' ? picked.size : pickedCountries.size;
|
||||
// Nothing found means nothing to confirm; the empty state says so in a sentence.
|
||||
const anything = tab === 'wishes' ? matches.length > 0 : offered.length > 0;
|
||||
|
||||
return {
|
||||
tab,
|
||||
setTab,
|
||||
scan,
|
||||
scanning,
|
||||
picked,
|
||||
togglePicked: (id: number) => setPicked((prev) => toggled(prev, id)),
|
||||
countries,
|
||||
loadingCountries,
|
||||
pickedCountries,
|
||||
togglePickedCountry: (code: string) => setPickedCountries((prev) => toggled(prev, code)),
|
||||
writing,
|
||||
matches,
|
||||
openMatches,
|
||||
offered,
|
||||
runScan,
|
||||
loadCountries,
|
||||
confirmWishes,
|
||||
confirmCountries,
|
||||
/** Ask the open tab's question (again). */
|
||||
run: () => void (tab === 'wishes' ? runScan() : loadCountries()),
|
||||
/** Confirm the open tab's selection. */
|
||||
confirm: () => void (tab === 'wishes' ? confirmWishes() : confirmCountries()),
|
||||
busy,
|
||||
loaded,
|
||||
selected,
|
||||
anything,
|
||||
};
|
||||
}
|
||||
|
||||
export type DawarichAtlasState = ReturnType<typeof useDawarichAtlas>;
|
||||
|
||||
/** What Dawarich offers for one question, built once for the desktop tab; the phone builds its own rows. */
|
||||
export function dawarichNotes(
|
||||
d: DawarichAtlasState,
|
||||
t: (key: string, params?: Record<string, string | number>) => string
|
||||
): string[] {
|
||||
if (d.tab === 'wishes') {
|
||||
return [
|
||||
d.scan && d.scan.skippedWithoutCoordinates > 0
|
||||
? t('dawarich.bucket.skipped', { count: d.scan.skippedWithoutCoordinates })
|
||||
: null,
|
||||
d.scan?.truncated ? t('dawarich.bucket.truncated') : null,
|
||||
t('dawarich.bucket.rule', { meters: DAWARICH_BUCKET_MATCH_RADIUS_M, count: DAWARICH_BUCKET_MATCH_MIN_MINUTES }),
|
||||
].filter((n): n is string => !!n);
|
||||
}
|
||||
return [
|
||||
d.countries && d.countries.unresolved.length > 0
|
||||
? t('dawarich.atlas.unresolved', { names: d.countries.unresolved.join(', ') })
|
||||
: null,
|
||||
d.countries ? t('dawarich.atlas.window') : null,
|
||||
].filter((n): n is string => !!n);
|
||||
}
|
||||
@@ -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,3 @@
|
||||
import React from 'react'
|
||||
import { describe, it, expect, beforeEach } from 'vitest'
|
||||
import { render, screen, fireEvent } from '../../../tests/helpers/render'
|
||||
import { useHelpStore } from '../../store/helpStore'
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
import React from 'react'
|
||||
import { describe, it, expect, beforeEach } from 'vitest'
|
||||
import { http, HttpResponse } from 'msw'
|
||||
import { render, screen, fireEvent, waitFor, within, act } from '../../../tests/helpers/render'
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
// FE-COMP-JOURNEYDATEPICKER-001 to FE-COMP-JOURNEYDATEPICKER-008
|
||||
import React from 'react'
|
||||
import { describe, it, expect, vi } from 'vitest'
|
||||
import { render, screen } from '../../../tests/helpers/render'
|
||||
import userEvent from '@testing-library/user-event'
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -25,7 +25,6 @@
|
||||
* what stops Leaflet from being handed zero-length polylines on every trip that
|
||||
* has no recording.
|
||||
*/
|
||||
import React from 'react'
|
||||
import { describe, it, expect, vi } from 'vitest'
|
||||
import { render, screen } from '@testing-library/react'
|
||||
import type { DawarichTrack, DawarichTrackDay } from '@trek/shared'
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
// FE-COMP-MAPCOMPASS-001 to FE-COMP-MAPCOMPASS-007
|
||||
import React from 'react'
|
||||
import { describe, it, expect, vi } from 'vitest'
|
||||
import { render, screen, fireEvent, act } from '../../../tests/helpers/render'
|
||||
import { MapCompassPill, type CompassMap } from './MapCompassPill'
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
// FE-COMP-MAPLAYER-001 to FE-COMP-MAPLAYER-024
|
||||
import React from 'react'
|
||||
import { describe, it, expect, vi } from 'vitest'
|
||||
import { render, screen, fireEvent } from '../../../tests/helpers/render'
|
||||
import { MapLayerSwitcher, TourMapLayerSwitcher, MAP_ROUND_CONTROL_SIZE } from './MapLayerSwitcher'
|
||||
|
||||
@@ -10,7 +10,7 @@
|
||||
* The click itself has to keep taking Leaflet's route and the page's: it is what closes
|
||||
* an open popup on the map, and an open context menu beside it.
|
||||
*/
|
||||
import React, { useState } from 'react'
|
||||
import { useState } from 'react'
|
||||
import { flushSync } from 'react-dom'
|
||||
import { describe, it, expect, vi, beforeAll, afterAll, afterEach } from 'vitest'
|
||||
import { render, waitFor, act } from '../../../tests/helpers/render'
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
import React from 'react'
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { render, screen } from '@testing-library/react'
|
||||
import PlaceHoverCard from './PlaceHoverCard'
|
||||
|
||||
@@ -3,7 +3,8 @@ 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 { routerAnswer } from './routerAsks'
|
||||
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'
|
||||
@@ -109,12 +110,12 @@ async function routedFetch(
|
||||
const sample = { profile, surface: kind, selfHosted, waypoints: waypoints.length, km }
|
||||
const asked = withoutUTurnIfRefused(url)
|
||||
try {
|
||||
const response = await fetch(asked, { signal })
|
||||
const response = await routerAnswer(fetch(asked, { signal }))
|
||||
countRoute({ ...sample, failed: !response.ok })
|
||||
if (response.ok || !asked.includes(U_TURN_PARAM)) return response
|
||||
const plain = await droppedUTurn(asked, response)
|
||||
if (!plain) return response
|
||||
const second = await fetch(plain, { signal })
|
||||
const second = await routerAnswer(fetch(plain, { signal }))
|
||||
countRoute({ ...sample, failed: !second.ok })
|
||||
return second
|
||||
} catch (err) {
|
||||
@@ -289,6 +290,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 +306,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 +317,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. */
|
||||
@@ -624,11 +637,11 @@ export async function calculateRouteWithLegs(
|
||||
const pluginProfile = parsePluginProfile(profile)
|
||||
if (pluginProfile) {
|
||||
if (tripId == null) throw new Error('Plugin routing needs a trip context')
|
||||
const { route } = await pluginsApi.pluginRoute(pluginProfile.pluginId, pluginProfile.profileId, {
|
||||
const { route } = await routerAnswer(pluginsApi.pluginRoute(pluginProfile.pluginId, pluginProfile.profileId, {
|
||||
tripId,
|
||||
dayId: dayId ?? null,
|
||||
waypoints: waypoints.map((p) => ({ lat: p.lat, lng: p.lng })),
|
||||
}, { signal })
|
||||
}, { signal }))
|
||||
if (!route) throw new Error('No route found')
|
||||
const legs = route.legs.map((leg, i): RouteSegment => ({
|
||||
...legSegment(leg, i, waypoints),
|
||||
|
||||
@@ -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);
|
||||
});
|
||||
});
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user